windows环境下,使用python3 +pyinstaller V3.4打包多进程工程时,启动exe后,执行到多进程开始处,软件又启动一个进程,完全是重新初始化整个流程,而不是仅仅启动另一个进程执行target指定的方法,但是在python终端执行源码,则无此现象,百度后,发现通过如下操作可解决此问题。
1.增加一个myMutilprocess.py文件,内容如下:
2.importos
3.importsys
4.importmultiprocessing
5.
6.try:
9.importmultiprocessing.popen_spawn_win32asforking
10.else:
11.importmultiprocessing.popen_forkasforking
12.exceptImportError:
13.importmultiprocessing.forkingasforking
14.
16.# First define a modifiedversion of Popen.
17.class_Popen(forking.Popen):
18.def__init__(self,*args,**kw):
19.ifhasattr(sys,'frozen'):
20.os.putenv('_MEIPASS2',sys._MEIPASS)
21.try:
22.super(_Popen,self).__init__(*args,**kw)
23.finally:
24.ifhasattr(sys,'frozen'):
25.# On some platforms (e.g.AIX) 'os.unsetenv()' is not
26.# available. In those caseswe cannot delete the variable
27.# but only set it to theempty string. The bootloader
28.# can handle this case.
29.ifhasattr(os,'unsetenv'):
30.os.unsetenv('_MEIPASS2')
31.else:
32.os.putenv('_MEIPASS2','')
33.# Second override 'Popen'class with our modified version.
34.forking.Popen = _Popen
2.主程序main.py中import myMultiprocess.py启动入口第一行添加一行代码
if __name__ == "__main__":
multiprocessing.freeze_support()
下面开始原来的逻辑
再次打包后,启动exe没有出现启动多个程序的现象。
领取专属 10元无门槛券
私享最新 技术干货