Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python running as Windows Service: OSError: [WinError 6] The handle is invalid

Tags:

I have a Python script, which is running as a Windows Service. The script forks another process with:

with subprocess.Popen( args=[self.exec_path], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) as proc: 

which causes the following error:

OSError: [WinError 6] The handle is invalid    File "C:\Program Files (x86)\Python35-32\lib\subprocess.py", line 911, in __init__    File "C:\Program Files (x86)\Python35-32\lib\subprocess.py", line 1117, in _get_handles 
like image 326
Alastair McCormack Avatar asked Oct 18 '16 12:10

Alastair McCormack


2 Answers

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.x, 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) 
like image 136
Alastair McCormack Avatar answered Sep 30 '22 20:09

Alastair McCormack


Add stdin=subprocess.PIPE like:

with subprocess.Popen( args=[self.exec_path], stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.STDOUT) as proc: 
like image 31
zelusp Avatar answered Sep 30 '22 18:09

zelusp