我尝试在 python 中将多处理包与池一起使用。
我有一个由 map_async 函数调用的函数 f:
from multiprocessing import Pool
def f(host, x):
print host
print x
hosts = ['1.1.1.1', '2.2.2.2']
pool = Pool(processes=5)
pool.map_async(f,hosts,"test")
pool.close()
pool.join()
这段代码有下一个错误:
Traceback (most recent call last):
File "pool-test.py", line 9, in <module>
pool.map_async(f,hosts,"test")
File "/usr/lib/python2.7/multiprocessing/pool.py", line 290, in map_async
result = MapResult(self._cache, chunksize, len(iterable), callback)
File "/usr/lib/python2.7/multiprocessing/pool.py", line 557, in __init__
self._number_left = length//chunksize + bool(length % chunksize)
TypeError: unsupported operand type(s) for //: 'int' and 'str'
我不知道如何将超过 1 个参数传递给 f 函数。有什么办法吗?
最佳答案
“test”
被解释为 map_async
的 chunksize
关键字参数(参见 the docs)。
您的代码可能应该是(这里是从我的 IPython session 中复制粘贴的):
from multiprocessing import Pool
def f(arg):
host, x = arg
print host
print x
hosts = ['1.1.1.1', '2.2.2.2']
args = ((host, "test") for host in hosts)
pool = Pool(processes=5)
pool.map_async(f, args)
pool.close()
pool.join()
## -- End pasted text --
1.1.1.1
test
2.2.2.2
test
注意:在 Python 3 中,您可以使用 starmap
,它将从元组中解压参数。您将能够避免明确地执行 host, x = arg
。
关于带有 map_async 的 python 多处理池,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16542261/