AssertionError

本文解析了Python多进程编程中常见的两个错误:一是进程初始化时未正确指定目标函数;二是忽略if __name__ == '__main__':条件,导致子进程无限递归创建。文章详细解释了错误原因及解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

(1)p1 = multiprocessing.Process(test1)
p2 = multiprocessing.Process(target=test2)
错误: p1缺少target,应为(target=test1)
Traceback (most recent call last):

  File "D:/untitled/多进程练习.py", line 11, in <module>
    p1 = multiprocessing.Process(test1)
  File "D:\python\lib\multiprocessing\process.py", line 74, in __init__
    assert group is None, 'group argument must be None for now'
AssertionError: group argument must be None for now

(2)  在有进程程序中,没有代码:if __name__ == __main__: 会出现如下错误

RuntimeError: RuntimeError      if __name__ == '__main__': 的作用:防止被被其他文件导入时显示多余的程序主体部分
        An attempt has been made to start a new process before the
        current process has finished its bootstrapping phase.
        This probably means that you are not using fork to start your
        child processes and you have forgotten to use the proper idiom
        in the main module:
            if __name__ == '__main__':
                freeze_support()
                ...
        The "freeze_support()" line can be omitted if the program
        is not going to be frozen to produce an executable.:
        An attempt has been made to start a new process before the
        current process has finished its bootstrapping phase.
        This probably means that you are not using fork to start your
        child processes and you have forgotten to use the proper idiom
        in the main module:
            if __name__ == '__main__':
                freeze_support()
                ...
        The "freeze_support()" line can be omitted if the program
        is not going to be frozen to produce an executable.
子进程会在运行时拷贝当前主进程中的所有内容,这也就意味着当一个新的子进程被创建的时候,该子进程就会复制当前模块,当然也包括了以下两行:
 
multiprocessing.Process(target=test1).start()
multiprocessing.Process(target=test).start()
很显然,这样的写法可能形成无限递归式地创建新的子进程。所以为了避免以上情况发生,我们在此引入了 if __name__ == __main__: 。

转载于:https://www.cnblogs.com/ztrblog/p/10033814.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值