Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cross-platform subprocess with hidden window

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)    
like image 286
endolith Avatar asked Jun 19 '09 04:06

endolith


4 Answers

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)
like image 120
Anurag Uniyal Avatar answered Nov 18 '22 11:11

Anurag Uniyal


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

like image 29
goertzenator Avatar answered Nov 18 '22 13:11

goertzenator


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.

like image 41
SpliFF Avatar answered Nov 18 '22 12:11

SpliFF


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.

like image 1
Nicolas Dumazet Avatar answered Nov 18 '22 13:11

Nicolas Dumazet