Skip to main content
 首页 » 编程设计

python之Windows 上的 GUI 应用程序中的子进程失败

2025年02月15日23freeliver54

在运行使用 pyinstaller --noconsole 创建的 python windows exe 时调用子进程 Popen、call 或 check_output 会导致以下堆栈出错:

... 
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 

遇到了this issue但没有直接的答案,所以创建这篇文章希望能让解决方案更容易找到。

请您参考如下方法:

我找到了答案 here作者:Alastair McCormack(感谢!!!!!)。事实证明,问题是子进程无法正确解析默认标准输入/输出。

为后代复制:


subprocess.py 中的第 1117 行是:

p2cread = _winapi.GetStdHandle(_winapi.STD_INPUT_HANDLE) 

这让我怀疑服务进程没有与之关联的 STDIN (TBC)

可以通过提供一个文件或空设备作为 popen 的标准输入参数来避免这种麻烦的代码。

在 Python 3.3、3.4 和 3.5 中,您可以简单地传递 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)