使用pyinstaller打包多进程python工程
在windows环境下,使用python3 + pyinstaller V3.4打包多进程工程时,启动exe后,执行到多进程开始处,软件又启动一个进程,完全是重新初始化整个流程,而不是仅仅启动另一个进程执行target指定的方法,但是在python终端执行源码,则无此现象,百度后,发现通过如下操作可解决此问题。
1. 增加一个myMutilprocess.py文件,内容如下:
import os
import sys
import multiprocessing
# 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
2. 主程序main.py中import myMultiprocess.py启动入口第一行添加一行代码
if __name__ == "__main__":
multiprocessing.freeze_support()
下面开始原来的逻辑
再次打包后,启动exe没有出现启动多个程序的现象。