最近在使用Pyinstaller打包Python程序的時候發現,打包過程正常,但在運行時會出錯,表現爲進程不斷增加至佔滿電腦CPU死機,程序版本及環境爲:
Windows 10
Python3.6
Pyinstaller 3.4
經過網上的多番搜索查閱發現是因爲程序使用了多進程模式,而在windows上Pyinstaller打包多進程程序需要添加特殊指令。
這裏是官方github給出的解釋:
https://github.com/pyinstaller/pyinstaller/wiki/Recipe-Multiprocessing
修改方式比較簡單,在 if __name__=='__main__:'下添加一句multiprocessing.freeze_support() 即可。
如下:
if __name__=='__main__':
# 在此處添加
multiprocessing.freeze_support()
# 這裏是你的代碼
# ......
1
如果你的Pyinstaller版本低於3.3版本的話,還需要額外添加一個模塊:
import os
import sys
# Module multiprocessing is organized differently in Python 3.4+
try:
# Python 3.4+
if sys.platform.startswith('win'):
import multiprocessing.popen_spawn_win32 as forking
else:
import multiprocessing.popen_fork as forking
except ImportError:
import multiprocessing.forking as forking
if sys.platform.startswith('win'):
# First define a modified version of Popen.
class _Popen(forking.Popen):
def __init__(self, *args, **kw):
if hasattr(sys, 'frozen'):
# We have to set original _MEIPASS2 value from sys._MEIPASS
# to get --onefile mode working.
os.putenv('_MEIPASS2', sys._MEIPASS)
try:
super(_Popen, self).__init__(*args, **kw)
finally:
if hasattr(sys, 'frozen'):
# On some platforms (e.g. AIX) 'os.unsetenv()' is not
# available. In those cases we cannot delete the variable
# but only set it to the empty string. The bootloader
# can handle this case.
if hasattr(os, 'unsetenv'):
os.unsetenv('_MEIPASS2')
else:
os.putenv('_MEIPASS2', '')
# Second override 'Popen' class with our modified version.
forking.Popen = _Popen
把上述內容保存爲multiprocess.py ,然後在你的程序中引入該模塊即可:
from multiprocess import *
1
值得提醒一點的是,上述程序打包時提示的錯誤非常難以定位到多進程處的問題,而是會提示一些別的包或者依賴文件找不到等等。
另外有關Pyinstaller打包常出現的問題可以在我的部分文章中找到一些解決方案:
Pyinstaller基本用法:https://blog.csdn.net/zyc121561/article/details/79563662
Pyinstaller隱式導入出錯解決:https://blog.csdn.net/zyc121561/article/details/79562935