简体   繁体   中英

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. I'm getting the error:

AttributeError: Can't get attribute 'task' on <module '__main__' (built-in)>

task is a function that I define.

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 :

Note: Functionality within this package requires that the __main__ module be importable by the children. 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.

Spyder uses IPython console, allowing you to execute commands and interact with data inside IPython interpreters. However, as mentioned here by a Spyder maintainer: "Multiprocessing doesn't work well on Windows in Spyder's IPython console."

Option 1

Update your Spyder software, as you are using an old - 5.1.5 as you mentioned - version. 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" .

Option 2

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).

Option 3

As described here , you could write your function into a separate file and import it into your script. For instance:

tasks.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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM