前言
使用pyinstaller打包exe,最近在打包包含subprocess.Popen时发现,加上参数—noconsole时产生的exe文件在运行的时候,进程并没有运行。现将解决方法记录一下:
问题出现时的代码如下:
subprocess使用
我这里需要利用subprocess.Popen创建一个进程去执行一个命令行操作,
mProcess = subprocess.Popen(cmd,stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
pyinstaller打包操作命令如下
pyinstaller -F -w xxx.py
打包后生成的exe,可以运行,不过查看进程并没有如预期正确地工作。
解决方法:
在创建进程时,加上startupinfo参数,如下
si = subprocess.STARTUPINFO()
si.dwFlags|= subprocess.STARTF_USESHOWWINDOW
mProcess=subprocess.Popen(cmd,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE,startupinfo=si)
注:更新代码若有异常,关闭PY文件,重新打开即可。
参考文献:
https://github.com/pyinstaller/pyinstaller/wiki/Recipe-subprocess
方案二、在打包时使用
pyinstaller -F xxx.py方式打包就是带有命令提示
并在if “main” == name:下面写入以下代码
whnd = ctypes.windll.kernel32.GetConsoleWindow() #带控制界面打包exe时隐藏CMD界面
ctypes.windll.user32.ShowWindow(whnd, 0) #带控制界面打包exe时隐藏CMD界面
原理是交提示命令强制隐藏掉