Subprocess calls failing on Windows

A while ago I wrote a script/algorithm to load a non standard data file with the help of another executable, which basically did:
import subprocess
datafilename=self.getProperty(“File”).value
s=subprocess.check_output([“command”,datafilename])
#process string s and extract data into a new workspace

It worked OK then (Nov 2014) but fails now with “[Error 6] The handle is invalid”.

On investigation this seems to be a general Windows/Python bug and there is a work around using
s=subprocess.check_output([“command”,datafilename],stdin=subprocess.PIPE, stderr=subprocess.PIPE)

There’s still a problem: it pops up a console window (which is blank as the output goes elsewhere) and the window then disappears once the subprocess finishes. This is most annoying as it also grabs keyboard focus, especially if I embed that algorithm in another longer running script and let it get on with processing while I do something else. Is there a better way to do this?

Hi James,

There is a suggestion here that it is possible to use the startupinfo argument to check_output (the Python docs page suggests that check_output takes most arguments that Popen does and pass a flag to turn off the window.

Does something like this work for you situation:

startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW s=subprocess.check_output(["command",datafilename],stdin=subprocess.PIPE, stderr=subprocess.PIPE, startupinfo=startupinfo)

I had already found a rather similar looking workaround elsewhere on the web:
import win32con
listing=subprocess.check_output([“command”,datafilename],stdin=subprocess.PIPE,stderr=subprocess.PIPE,creationflags=win32con.CREATE_NO_WINDOW)
That works and doesn’t pop up windows. It’s Windows only of course - might yours be portable, assuming of course that “command” is available on the other platforms?

I think this unfortunately gets into the realm of operating system specifics and it looks like the whole startupinfo structure is a Windows-only feature so it looks like there isn’t a cross-platform way to do this in Python. However, I believe the default on the other platforms is not to create a separate window to run the command.

I can confirm that this is the case on Linux with the following code:

import subprocess as subp
import sys

if sys.platform == "win32":
    startupinfo = subp.STARTUPINFO()
    startupinfo.dwFlags |= subp.STARTF_USESHOWWINDOW
else:
    startupinfo = None

s = subp.check_output(["ls", "bin"], stdin=subp.PIPE, stderr=subp.PIPE, startupinfo=None)