带有 map_async 的 python 多处理池

标签 python multiprocessing

我尝试在 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_asyncchunksize 关键字参数(参见 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/

相关文章:

python - 反转为 'product',没有找到参数。尝试了 1 个模式 : [u'products/(? P<product>[-\\w]+)/$']

python - 使用原始索引获取 Pandas 重复行数

python - 未找到 Django Python 页面 (404)

python 3.6+ : Nested multiprocessing managers cause FileNotFoundError

python - 在Python多处理模块中使用Pool和Queue

python - json 网页的 Unicode 解码错误

python - 随机种子() : What does it do?

python - Cassandra 多处理无法 pickle _thread.lock 对象

python - 在 python 多处理工作池中使用初始化

Python 管道子进程在连接后挂起