我知道这已经得到了回答,但似乎直接执行脚本"python filename.py"不起作用.我在SuSE Linux上有Python 2.6.2.
码:
#!/usr/bin/python # -*- coding: utf-8 -*- from multiprocessing import Pool p = Pool(1) def f(x): return x*x p.map(f, [1, 2, 3])
命令行:
> python example.py Process PoolWorker-1: Traceback (most recent call last): File "/usr/lib/python2.6/multiprocessing/process.py", line 231, in _bootstrap self.run() File "/usr/lib/python2.6/multiprocessing/process.py", line 88, in run self._target(*self._args, **self._kwargs) File "/usr/lib/python2.6/multiprocessing/pool.py", line 57, in worker task = get() File "/usr/lib/python2.6/multiprocessing/queues.py", line 339, in get return recv() AttributeError: 'module' object has no attribute 'f'
Bartosz.. 125
重构代码,以便f()
在创建Pool实例之前定义函数.否则工人看不到你的功能.
#!/usr/bin/python # -*- coding: utf-8 -*- from multiprocessing import Pool def f(x): return x*x p = Pool(1) p.map(f, [1, 2, 3])
棒极了,非常感谢!! 什么神秘的用法! (10认同)
Tamás.. 5
这个工作:
#!/usr/bin/python # -*- coding: utf-8 -*- from multiprocessing import Pool def f(x): return x*x if __name__ == "__main__": p = Pool(1) p.map(f, [1, 2, 3])
我不是100%确定你的代码无法正常工作,但我想原因是该multiprocessing
模块启动的子进程尝试导入主模块(以便访问您定义的方法),并且该if __name__ == "__main__"
节不需要执行设置池的初始化代码.
重构代码,以便f()
在创建Pool实例之前定义函数.否则工人看不到你的功能.
#!/usr/bin/python # -*- coding: utf-8 -*- from multiprocessing import Pool def f(x): return x*x p = Pool(1) p.map(f, [1, 2, 3])
这个工作:
#!/usr/bin/python # -*- coding: utf-8 -*- from multiprocessing import Pool def f(x): return x*x if __name__ == "__main__": p = Pool(1) p.map(f, [1, 2, 3])
我不是100%确定你的代码无法正常工作,但我想原因是该multiprocessing
模块启动的子进程尝试导入主模块(以便访问您定义的方法),并且该if __name__ == "__main__"
节不需要执行设置池的初始化代码.