You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python多进程报错:无法获取calc_square属性,请求协助解决

Python多进程AttributeError问题解决

问题代码

import multiprocessing
import time

def calc_square(numbers, q):
    for n in numbers:
        q.put(n*n)

def calc_cube(numbers, q):
    for n in numbers:
        q.put(n*n*n)



if __name__ == "__main__":`enter code here`
    numbers = [2,3,5,7,9,10]
    numbers2 = [2,3,5,7,9,10]
    q = multiprocessing.Queue()
    q2 = multiprocessing.Queue()
    p = multiprocessing.Process(target=calc_square, args=(numbers,q))
    p1 = multiprocessing.Process(target=calc_square, args=(numbers2,q2))
    time.sleep(0.05)
    p.start()
    p1.start()
    p.join()
    p1.join()
    while q.empty() is False:
        print(q.get())
    while q2.empty() is False:
        print(q2.get())

报错信息

Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "C:\Users\Hello\AppData\Local\Programs\Python\Python310\lib\multiprocessing\spawn.py", line 116, in spawn_main
    exitcode = _main(fd, parent_sentinel)
  File "C:\Users\Hello\AppData\Local\Programs\Python\Python310\lib\multiprocessing\spawn.py", line 126, in _main
    self = reduction.pickle.load(from_parent)
AttributeError: Can't get attribute 'calc_square' on <module '__main__' (built-in)>
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "C:\Users\Hello\AppData\Local\Programs\Python\Python310\lib\multiprocessing\spawn.py", line 116, in spawn_main
    exitcode = _main(fd, parent_sentinel)
  File "C:\Users\Hello\AppData\Local\Programs\Python\Python310\lib\multiprocessing\spawn.py", line 126, in _main
    self = reduction.pickle.load(from_parent)
AttributeError: Can't get attribute 'calc_square' on <module '__main__' (built-in)>

错误原因

  1. 语法错误:if __name__ == "__main__":行末尾多了无效的enter code here内容,导致子进程在导入主模块时解析失败,无法识别calc_square函数。
  2. Windows系统下multiprocessing默认使用spawn启动方式,子进程会重新执行主模块代码,主模块的语法错误会直接导致函数无法被正常加载。

修复方案

  • 移除if __name__ == "__main__":行末尾的enter code here,修正语法错误。
  • 若原本意图让p1进程计算立方,可将target=calc_square改为target=calc_cube。

修复后的完整代码

import multiprocessing
import time

def calc_square(numbers, q):
    for n in numbers:
        q.put(n*n)

def calc_cube(numbers, q):
    for n in numbers:
        q.put(n*n*n)

if __name__ == "__main__":
    numbers = [2,3,5,7,9,10]
    numbers2 = [2,3,5,7,9,10]
    q = multiprocessing.Queue()
    q2 = multiprocessing.Queue()
    p = multiprocessing.Process(target=calc_square, args=(numbers,q))
    # 如需计算立方,将下面的calc_square替换为calc_cube
    p1 = multiprocessing.Process(target=calc_square, args=(numbers2,q2))
    p.start()
    p1.start()
    p.join()
    p1.join()
    while not q.empty():
        print(q.get())
    while not q2.empty():
        print(q2.get())

内容的提问来源于stack exchange,提问作者Deepu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 20:35:24