我有一个 Python 脚本,它作为 Windows 服务运行。该脚本使用以下方式分叉另一个进程:
with subprocess.Popen( args=[self.exec_path], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) as proc:
这会导致以下错误:
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
subprocess.py
中的第1117行是:
p2cread = _winapi.GetStdHandle(_winapi.STD_INPUT_HANDLE)
这让我怀疑服务进程没有与之关联的 STDIN(待定)
可以通过提供文件或空设备作为
popen
的 stdin 参数来避免这种麻烦的代码。
在 Python 3.x 中,您可以简单地传递
stdin=subprocess.DEVNULL
。例如
subprocess.Popen( args=[self.exec_path], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, stdin=subprocess.DEVNULL)
在 Python 2.x 中,您需要将文件处理程序设置为 null,然后将其传递给 popen:
devnull = open(os.devnull, 'wb')
subprocess.Popen( args=[self.exec_path], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, stdin=devnull)
添加
stdin=subprocess.PIPE
,例如:
with subprocess.Popen( args=[self.exec_path], stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.STDOUT) as proc:
在我的 subprocess.py 版本中,问题出现在第 1348 行,柯南被噎住了……
p2cread = _winapi.GetStdHandle(_winapi.STD_INPUT_HANDLE)
解决方案是将这一行更改为:p2cread = None
接下来的几行是:
if p2cread is None:
p2cread, _ = _winapi.CreatePipe(None, 0)
p2cread = Handle(p2cread)
err_close_fds.append(p2cread)
_winapi.CloseHandle(_)