Pyinstaller打包多进程程序出错解决办法

作者:yooongchun
微信:18217235290


最近在使用Pyinstaller打包Python程序的时候发现,打包过程正常,但在运行时会出错,表现为进程不断增加至占满电脑CPU死机,程序版本及环境为:

修改方式比较简单,在 if __name__=='__main__:'下添加一句multiprocessing.freeze_support() 即可。
如下:

if __name__=='__main__':
	# 在此处添加
	multiprocessing.freeze_support()
	# 这里是你的代码
	# ......

如果你的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 *

值得提醒一点的是,上述程序打包时提示的错误非常难以定位到多进程处的问题,而是会提示一些别的包或者依赖文件找不到等等。

另外有关Pyinstaller打包常出现的问题可以在我的部分文章中找到一些解决方案:
Pyinstaller基本用法:https://blog.csdn.net/zyc121561/article/details/79563662
Pyinstaller隐式导入出错解决:https://blog.csdn.net/zyc121561/article/details/79562935

评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

zoz.cool

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值