Python使用PyInstaller无控制台编译时如何正常获取设备HWID
问题根因
Windows 平台下使用--windowed参数打包的GUI程序没有关联标准输入(stdin)、标准输出(stdout)、标准错误(stderr)三个标准流句柄,subprocess默认会继承父进程的流句柄,找不到有效句柄就会触发OSError: [WinError 6] 句柄无效报错。
修复方案
调用subprocess.Popen时显式指定将标准输入、标准错误重定向到subprocess.DEVNULL,不需要继承父进程的无效句柄即可解决问题。
修改后的代码示例
import subprocess import PySimpleGUIQt as Sg # 新增stdin、stderr参数,显式指定为空设备 hw_id = str(subprocess.Popen( 'wmic csproduct get uuid', shell=True, stdout=subprocess.PIPE, stdin=subprocess.DEVNULL, stderr=subprocess.DEVNULL ).communicate()[0]).split('\r\n')[1].strip('\r').strip() layout = [[Sg.Text(hw_id)]] window = Sg.Window('test', layout) while True: event, values = window.read() if event is None: break
打包验证
使用原无控制台打包命令重新打包即可正常运行:pyinstaller --onefile --windowed testt.py
兼容补充(可选)
如果需要适配Python3.3以下极低版本,可手动打开空设备替代subprocess.DEVNULL:
import os NULL = open(os.devnull, 'w') # 调用Popen时传入stdin=NULL, stderr=NULL即可
内容的提问来源于stack exchange,提问作者Ifan_Ifan
相关产品推荐
相关产品推荐

