Python running as Windows Service: OSError: [WinError 6] The handle is invalid
<p>I have a Python script, which is running as a Windows Service. The script forks another process with:</p>

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

<p>which causes the following error:</p>

<pre><code>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
</code></pre>

<p>Line 1117 in <code>subprocess.py</code> is:</p>

<pre><code>p2cread = _winapi.GetStdHandle(_winapi.STD_INPUT_HANDLE)
</code></pre>

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

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

<p>In <strong>Python 3.3, 3.4, and 3.5</strong>, you can simply pass <code>stdin=subprocess.DEVNULL</code>. E.g.</p>

<pre><code>subprocess.Popen( args=[self.exec_path], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, stdin=subprocess.DEVNULL)
</code></pre>

<p>In <strong>Python 2.x</strong>, you need to get a filehandler to null, then pass that to popen:</p>

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

python windows subprocess