我正在浏览python中的Multiprocessing库的文档。
这是我想要运行的示例:
from multiprocessing import Pool
def f(x):
return x*x
if __name__ == '__main__':
with Pool(5) as p:
print(p.map(f, [1, 2, 3]))
该示例来自以下链接:Multiprocessing Doc
运行上述程序时出现以下错误:
Process SpawnPoolWorker-1:
Traceback (most recent call last):
File "C:\Python35\lib\multiprocessing\process.py", line 254, in _bootstrap
self.run()
File "C:\Python35\lib\multiprocessing\process.py", line 93, in run
self._target(*self._args, **self._kwargs)
File "C:\Python35\lib\multiprocessing\pool.py", line 108, in worker
task = get()
File "C:\Python35\lib\multiprocessing\queues.py", line 345, in get
return ForkingPickler.loads(res)
AttributeError: Can't get attribute 'f' on <module '__main__' (built-in)>
Process SpawnPoolWorker-3:
Traceback (most recent call last):
File "C:\Python35\lib\multiprocessing\process.py", line 254, in _bootstrap
self.run()
File "C:\Python35\lib\multiprocessing\process.py", line 93, in run
self._target(*self._args, **self._kwargs)
File "C:\Python35\lib\multiprocessing\pool.py", line 108, in worker
task = get()
Process SpawnPoolWorker-5:
File "C:\Python35\lib\multiprocessing\queues.py", line 345, in get
return ForkingPickler.loads(res)
Traceback (most recent call last):
File "C:\Python35\lib\multiprocessing\process.py", line 254, in _bootstrap
self.run()
File "C:\Python35\lib\multiprocessing\process.py", line 93, in run
self._target(*self._args, **self._kwargs)
File "C:\Python35\lib\multiprocessing\pool.py", line 108, in worker
task = get()
File "C:\Python35\lib\multiprocessing\queues.py", line 345, in get
return ForkingPickler.loads(res)
AttributeError: Can't get attribute 'f' on <module '__main__' (built-in)>
AttributeError: Can't get attribute 'f' on <module '__main__' (built-in)>
这个过程也没有结束。如果我尝试按Enter键,python崩溃但程序仍然打开。
请告诉我需要做些什么来解决这个问题。
答案 0 :(得分:1)
Python多处理通过在单独的Python进程(即另一个解释器实例)中再次加载程序来工作。
您正尝试直接使用REPL中的multiprocessing
,输入代码,但这些代码无法正常工作,因为没有其他进程可以加载的文件。
您需要将代码存储在文件中。