问题
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
回答1:
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()
回答2:
You are importing only pool
module from multiprocessing
module.
So your interpreter is aware of pool
only and not of multiprocessing
To resolve the problem, you must import multiprocessing
and when you require the pool
in code you can use it like multiprocessing.pool
multiprocessing
|-- __init__.py
|--Process
|--Pool
|--This_also
Like shown above, you are importing only pool
and python doesn't know who the hell this multiprocessing and Process and This_also are.
Usually we have __ init __.py file in python package. A list in this file all = ['pool.py','Process.py',.......'This_also']
contains all the modules contained in the package. So import * will import all the modules. Please go through the https://docs.python.org/2/tutorial/modules.html#
回答3:
If you have written a file called multiprocessing.py, it will try to import that first, which will mean it will not find Pool in it when you do "from multiprocessing import Pool".
multiprocessing is a module included in Python and has Pool in it, so if there are no conflicts the below should work: "from multiprocessing import Pool"
回答4:
Did you call your script 'multiprocessing.py'? Check your directory or file first... if yes -> Python will look for Pool in your script, which probably isn't there.(Rename it if exist) Sounds funny but it happens )
来源:https://stackoverflow.com/questions/28740886/python-importerror-cannot-import-name-pool