theannouncer
theannouncer

Reputation: 1220

subprocess failing in GUI applications on Windows

Calling subprocess Popen, call, or check_output while running a python windows exe created with pyinstaller --noconsole results in an error with the following stack:

...
File "subprocess.py", line 566, in check_output
File "subprocess.py", line 702, in __init__
File "subprocess.py", line 823, in _get_handles
WindowsError: [Error 6] The handle is invalid

Came across this issue but no direct answer, so creating this post to hopefully make the solution easier to find.

Upvotes: 2

Views: 897

Answers (1)

theannouncer
theannouncer

Reputation: 1220

I found an answer here by Alastair McCormack (thanks!!!!). Turns out the issue is that subprocess fails to properly resolve default stdin/out.

Copied for posterity:


Line 1117 in subprocess.py is:

p2cread = _winapi.GetStdHandle(_winapi.STD_INPUT_HANDLE)

which made me suspect that service processes do not have a STDIN associated with them (TBC)

This troublesome code can be avoided by supplying a file or null device as the stdin argument to popen.

In Python 3.3, 3.4, and 3.5, you can simply pass stdin=subprocess.DEVNULL. E.g.

subprocess.Popen( args=[self.exec_path], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, stdin=subprocess.DEVNULL)

In Python 2.x, you need to get a filehandler to null, then pass that to popen:

devnull = open(os.devnull, 'wb')
subprocess.Popen( args=[self.exec_path], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, stdin=devnull)

Upvotes: 1

Related Questions