Search code examples
pythonpython-multiprocessing

python - ImportError: cannot import name Pool


Code here:

from multiprocessing import pool
def worker(num):
    print 'Worker:', num
    return

if __name__ == '__main__':
    jobs = []
    for i in range(5):
        p = multiprocessing.Process(target=worker, args=(i,))
        jobs.append(p)
        p.start()

Sorry I am new to python. I am getting the below error whenever I try to import pool. It says something wrong with os.chdir(wdir) but I cant figure out what. Any help ?

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Users\z080302\Desktop\WinPython-32bit-2.7.6.3\python-2.7.6\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 540, in runfile
execfile(filename, namespace)
File "C:/Users/z080302/Desktop/Python_Projects/mp_test.py", line 18, in <module>
p = multiprocessing.Process(target=worker, args=(i,))
NameError: name 'multiprocessing' is not defined

Solution

  • Here's your code:

    from multiprocessing import pool
    def worker(num):
        print 'Worker:', num
        return
    
    if __name__ == '__main__':
        jobs = []
        for i in range(5):
            p = multiprocessing.Process(target=worker, args=(i,))
            jobs.append(p)
            p.start()
    

    You have to import the module multiprocessing to use multiprocessing.Process, you have only imported the function/class Pool from multiprocessing, so a simple fix would be:

    import multiprocessing
    pool = multiprocessing.pool
    def worker(num):
        print 'Worker:', num
        return
    
    if __name__ == '__main__':
        jobs = []
        for i in range(5):
            p = multiprocessing.Process(target=worker, args=(i,))
            jobs.append(p)
            p.start()