[英]Python Multiprocessing error: AttributeError: Can't get attribute 'task' on <module '__main__' (built-in)>"
I'm using spyder 5.1.5 and I am trying to follow along with the very first example on a website.我正在使用 spyder 5.1.5,我正在尝试遵循网站上的第一个示例。 I'm getting the error:
我收到错误:
AttributeError: Can't get attribute 'task' on <module '__main__' (built-in)>
task
is a function that I define. task
是我定义的 function。
Full example code:完整示例代码:
import multiprocessing
import time
def task(num):
print("a",num)
time.sleep(2)
if __name__ == '__main__':
for i in range(10):
p = multiprocessing.Process(target=task,args=(i,))
p.start()
As per Python's documentation :根据 Python 的文档:
Note: Functionality within this package requires that the
__main__
module be importable by the children.注意:此 package 中的功能要求
__main__
模块可由子模块导入。 This is covered in Programming guidelines , however, it is worth pointing out here.这在编程指南中有介绍,但是,值得在这里指出。 This means that some examples, such as the multiprocessing.pool.Pool examples will not work in the interactive interpreter.
这意味着某些示例,例如multiprocessing.pool.Pool示例将无法在交互式解释器中工作。
Spyder uses IPython console, allowing you to execute commands and interact with data inside IPython interpreters. Spyder 使用 IPython 控制台,允许您在IPython解释器中执行命令并与数据交互。 However, as mentioned here by a Spyder maintainer: "Multiprocessing doesn't work well on Windows in Spyder's IPython console."
然而,正如 Spyder 维护者在此提到的: “在 Spyder 的 IPython 控制台中,多处理在 Windows 上无法正常工作。”
Update your Spyder software, as you are using an old - 5.1.5 as you mentioned - version.更新您的 Spyder 软件,因为您使用的是旧版本 - 如您所提到的5.1.5 - 版本。 However, as stated here , "since our 5.2.0 version (released in November 2021), prints generated while running multiprocessing code are captured and displayed in the IPython console for all operating systems" .
但是,如此处所述, “自我们的5.2.0版本(2021 年 11 月发布)以来,运行多处理代码时生成的打印被捕获并显示在所有操作系统的 IPython 控制台中” 。
Change the console settings to run your code using an external terminal instead.更改控制台设置以使用外部终端运行您的代码。 To do that, please go to:
Run
> Configuration per file...
> Execute in an external system terminal
(under console).为此,请 go 到:
Run
> Configuration per file...
> Execute in an external system terminal
。
As described here , you could write your function into a separate file and import it into your script.如此处所述,您可以将 function 写入单独的文件并将其导入脚本。 For instance:
例如:
tasks.py任务.py
import time
def task(num):
print("a",num)
time.sleep(2)
main.py主文件
import multiprocessing
from tasks import task
if __name__ == '__main__':
for i in range(10):
p = multiprocessing.Process(target=task,args=(i,))
p.start()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.