window下pyinstaller多进程打包遇到问题

我在windows下用pyinstaller打包程序, 运行python3.11.6和python3.12.0都遇到同样的问题

前提说明

  1. 代码在macOS上运行正常,无论打包与否, 无论是否arm64
  2. windows上直接python运行没问题
  3. 下面的错误是pyinstaller打包后运行出现的错误
Traceback (most recent call last):
File "main.py", line 8, in <module>
File "<frozen importlib._bootstrap>", line 1176, in _find_and_load
File "<frozen importlib._bootstrap>", line 1147, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 690, in _load_unlocked
File "PyInstaller\loader\pyimod02_importers.py", line 419, in exec_module
File "process\scheduler.py", line 14, in <module>
File "multiprocess\context.py", line 150, in freeze_support
File "multiprocess\spawn.py", line 77, in freeze_support
File "multiprocess\spawn.py", line 120, in spawn_main
File "multiprocess\spawn.py", line 130, in _main
File "dill_dill.py", line 287, in load
File "dill_dill.py", line 442, in load
File "dill_dill.py", line 432, in find_class
AttributeError: Can't get attribute 'run_one' on <module 'process.scheduler' from 'C:\Users\xxx\AppData\Local\Temp\_MEI114562\process\scheduler.pyc'>
[3608] Failed to execute script 'main' due to unhandled exception!

如果你遇到这个问题,建议如下

  1. 不要怀疑python版本问题
  2. 不要怀疑pyinstaller的打包能力
  3. 如果pyinstaller打包时出现个别警告, 千万不要怀疑系统有问题

不要问我是怎么知道的。

问题根因:

multiprocess.freeze_support() 会在主进程中调用,以确保只有主进程执行其中的代码。这样就避免了在子进程中重新执行整个脚本。

问题总结

学艺不精,技术不行。

错误代码展示


if IS_WINDOWS:
    multiprocess.freeze_support()


def run_one(tasks, name:string, *args, **kwargs):
    try:
        for key, task in tasks.items():
            if key.lower() == name.lower():
                logger.debug(f'[{task.__class__.__name__}] start...')
                task.run()
                logger.debug(f'[{task.__class__.__name__}] exit!')
                return
        logger.debug(f'[{name}] processor no exist, exit')
    except KeyboardInterrupt:
        logger.info('[main] process received keyboard interrupt signal')

正确代码

def run_one(tasks, name:string, *args, **kwargs):
    try:
        for key, task in tasks.items():
            if key.lower() == name.lower():
                logger.debug(f'[{task.__class__.__name__}] start...')
                task.run()
                logger.debug(f'[{task.__class__.__name__}] exit!')
                return
        logger.debug(f'[{name}] processor no exist, exit')
    except KeyboardInterrupt:
        logger.info('[main] process received keyboard interrupt signal')
        

if IS_WINDOWS:
    multiprocess.freeze_support()
  • 10
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值