Welcome, guest | Sign In | My Account | Store | Cart

On the MS Windows platform, if you launch a subprocess from within a non-console process a console window appears.

This recipe shows how to avoid this by using the python 2.4 library module subprocess.py

Python, 11 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
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"])

Tested on WinXP SP2

4 comments

Antony Kummel 18 years, 3 months ago  # | flag

If it doesn't work for you. And you've downloaded subprocess from effbot, then you should add this line somewhere: subprocess.STARTF_USESHOWWINDOW = 1

Andrew Martin 12 years, 5 months ago  # | flag

After much googling, I stumbled upon this thread for a different issue and figured, "Well, why not try this just to see if it works." Magically, it did!

For anyone else trying to capture psexec output of certain programs that normally either hang subprocess (Popen), or simply don't return any output, the above code (with very slight modifications) seemingly fixes the problem:

[code] import subprocess

def launchWithoutConsole(command, args): """Launches 'command' windowless""" startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW

return subprocess.Popen([command] + args, startupinfo=startupinfo,
                        stderr=subprocess.PIPE, stdout=subprocess.PIPE)

if __name__ == "__main__": process = launchWithoutConsole("d:\bin\gzip.exe", ["-d", "myfile.gz"]) stderr, stdout = process.communicate()

[/code]

So, the new function returns an instance of Popen, which can then be used to fetch the stdout/stderr as usual with Popen.communicate().

Andrew Martin 12 years, 5 months ago  # | flag

OK, let's try that again now that I've read the instructions for posting code...

import subprocess

def launchWithoutConsole(command, args):
   """Launches 'command' windowless"""
   startupinfo = subprocess.STARTUPINFO()
   startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW

   return subprocess.Popen([command] + args, startupinfo=startupinfo,
                    stderr=subprocess.PIPE, stdout=subprocess.PIPE)

if __name__ == "__main__":
   process = launchWithoutConsole("d:\bin\gzip.exe", ["-d", "myfile.gz"])
   stderr, stdout = process.communicate()
Tymoteusz Jankowski 11 years, 11 months ago  # | flag

Any idea, why this fancy recipe :) dosen't work or how to hunt the bug? I'm fed up and with no thoughts... please help :)

I also asked here with no satifaction :(

http://stackoverflow.com/questions/10637450/how-to-hide-console-with-popen-on-windows