后台Python脚本调用installer.py报错:Bad file descriptor问题求助
问题排查与修复
错误根源分析
- 无效文件句柄传递:main.py启动updater时,将
stdout和stderr重定向到subprocess.PIPE但未读取,导致updater的输入输出流句柄处于异常状态。当updater启动installer时,继承了这些无效句柄,触发Bad file descriptor错误。 - 参数误用:
stdin=subprocess.STDOUT是错误用法——subprocess.STDOUT仅用于指定stderr重定向到stdout,不能用来设置stdin,这会导致程序尝试将无效的stdout句柄作为stdin使用。 - 不必要的
shell=True:Windows下启用shell=True会通过cmd.exe中转执行,既降低效率,还可能引发参数解析异常,且启动Python脚本无需依赖shell。
修复方案
1. 修正updater.py中启动installer的代码
移除错误的流重定向设置,让installer继承系统默认的输入输出流(保证用户交互正常):
from subprocess import Popen import sys # 启动installer,保留用户交互能力 Popen([sys.executable, 'installer.py', latestVersion], stdin=None, stdout=None, stderr=None)
如果需要隐藏installer的控制台窗口(不需要的话可忽略),可添加creationflags=subprocess.CREATE_NO_WINDOW(仅Windows有效)。
2. 优化main.py启动updater的方式
避免未读取的PIPE导致的句柄异常,用DEVNULL丢弃updater的输出,同时设置后台运行标记:
import subprocess import sys # 后台启动updater,丢弃输出避免阻塞和句柄问题 subprocess.Popen( [sys.executable, 'updater.py'], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, creationflags=subprocess.CREATE_NO_WINDOW # Windows下隐藏控制台窗口 )
3. 额外注意事项
- 路径正确性:确保installer.py的路径正确,若updater在子目录运行,建议使用绝对路径:
import os installer_path = os.path.join(os.path.dirname(__file__), 'installer.py') Popen([sys.executable, installer_path, latestVersion], ...) - 参数类型:确保
latestVersion为字符串类型,避免参数传递时出错。
内容的提问来源于stack exchange,提问作者user23406293
相关产品推荐
相关产品推荐

