Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running a process in pythonw with Popen without a console

I have a program with a GUI that runs an external program through a Popen call:

p = subprocess.Popen("<commands>" , stdout=subprocess.PIPE , stderr=subprocess.PIPE , cwd=os.getcwd())
p.communicate()

But a console pops up, regardless of what I do (I've also tried passing it NUL for the file handle). Is there any way to do that without getting the binary I call to free its console?

like image 529
sbirch Avatar asked Nov 28 '09 21:11

sbirch


People also ask

How subprocess popen works in Python?

The subprocess module defines one class, Popen and a few wrapper functions that use that class. The constructor for Popen takes arguments to set up the new process so the parent can communicate with it via pipes. It provides all of the functionality of the other modules and functions it replaces, and more.

What is the difference between subprocess run and Popen?

Popen . The main difference is that subprocess. run() executes a command and waits for it to finish, while with subprocess. Popen you can continue doing your stuff while the process finishes and then just repeatedly call Popen.

Does Popen wait for process to finish?

Using Popen MethodThe Popen method does not wait to complete the process to return a value.

Does Popen need to be closed?

Popen do we need to close the connection or subprocess automatically closes the connection? Usually, the examples in the official documentation are complete. There the connection is not closed. So you do not need to close most probably.


2 Answers

From here:

import subprocess

def launchWithoutConsole(command, args):
    """Launches 'command' windowless and waits until finished"""
    startupinfo = subprocess.STARTUPINFO()
    startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
    return subprocess.Popen([command] + args, startupinfo=startupinfo).wait()

if __name__ == "__main__":
    # test with "pythonw.exe"
    launchWithoutConsole("d:\\bin\\gzip.exe", ["-d", "myfile.gz"])

Note that sometimes suppressing the console makes subprocess calls fail with "Error 6: invalid handle". A quick fix is to redirect stdin, as explained here: Python running as Windows Service: OSError: [WinError 6] The handle is invalid

like image 89
interjay Avatar answered Oct 18 '22 15:10

interjay


just do subprocess.Popen([command], shell=True)

like image 32
Liam Avatar answered Oct 18 '22 16:10

Liam