38

I want to open a process in the background and interact with it, but this process should be invisible in both Linux and Windows. In Windows you have to do some stuff with STARTUPINFO, while this isn't valid in Linux:

ValueError: startupinfo is only supported on Windows platforms

Is there a simpler way than creating a separate Popen command for each OS?

if os.name == 'nt':
    startupinfo = subprocess.STARTUPINFO()
    startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
    proc = subprocess.Popen(command, startupinfo=startupinfo)
if os.name == 'posix':
    proc = subprocess.Popen(command)    
endolith
  • 25,479
  • 34
  • 128
  • 192

4 Answers4

40

You can reduce one line :)

startupinfo = None
if os.name == 'nt':
    startupinfo = subprocess.STARTUPINFO()
    startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
proc = subprocess.Popen(command, startupinfo=startupinfo)
Anurag Uniyal
  • 85,954
  • 40
  • 175
  • 219
  • Aha. I had tried startupinfo = '' and it didn't work. This is the answer I was looking for. – endolith Jun 20 '09 at 13:44
  • 1
    i just looked thru the subprocess code to see how they generate that error msg and they check if startupinfo is not None, as should be in python – Anurag Uniyal Jun 20 '09 at 14:57
  • 3
    If you set `STARTF_SHOWWINDOW`, you will also want to initialise the `wShowWindow` member of `startupinfo` to one of the `SW_*` constants. This method relies on the program that you run actually acting upon the `wShowWindow` flag; it's not required to do so. – Greg Hewgill Sep 01 '09 at 01:03
12

Just a note: for Python 2.7 I have to use subprocess._subprocess.STARTF_USESHOWWINDOW instead of subprocess.STARTF_USESHOWWINDOW.

alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
goertzenator
  • 1,960
  • 18
  • 28
  • Related Python issue 9861: [subprocess module changed exposed attributes](http://bugs.python.org/issue9861) – Piotr Dobrogost Jul 07 '14 at 13:19
  • 1
    What version of Python 2.7 was it? According to https://code.google.com/p/googleappengine/issues/detail?id=10363#c2 *`subprocess.STARTF_USESHOWWINDOW` is added after Python 2.7.2.* – Piotr Dobrogost Jul 07 '14 at 13:24
4

I'm not sure you can get much simpler than what you've done. You're talking about optimising out maybe 5 lines of code. For the money I would just get on with my project and accept this as a consquence of cross-platform development. If you do it a lot then create a specialised class or function to encapsulate the logic and import it.

SpliFF
  • 38,186
  • 16
  • 91
  • 120
1

You can turn your code into:

params = dict()

if os.name == 'nt':
    startupinfo = subprocess.STARTUPINFO()
    startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
    params['startupinfo'] = startupinfo

proc = subprocess.Popen(command, **params)

but that's not much better.

Nicolas Dumazet
  • 7,147
  • 27
  • 36