如何让Pool.map接受lambda函数

2024-04-19 23:45:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下功能:

def copy_file(source_file, target_dir):
    pass

现在我想使用multiprocessing立即执行此函数:

p = Pool(12)
p.map(lambda x: copy_file(x,target_dir), file_list)

问题是,lambda's不能腌制,所以这次失败了。解决这个问题最简单的方法是什么?


Tags: 方法lambda函数功能mapsourcetargetdef
3条回答

这个问题有点老了,但如果您仍然使用Python 2,我的答案可能会很有用。

诀窍是使用pathos项目的一部分:多处理的multiprocess分叉。它摆脱了原有多进程的烦人限制。

安装:pip install multiprocess

用法:

>>> from multiprocess import Pool
>>> p = Pool(4)
>>> print p.map(lambda x: (lambda y:y**2)(x) + x, xrange(10))
[0, 2, 6, 12, 20, 30, 42, 56, 72, 90]

使用函数对象:

class Copier(object):
    def __init__(self, tgtdir):
        self.target_dir = tgtdir
    def __call__(self, src):
        copy_file(src, self.target_dir)

运行Pool.map

p.map(Copier(target_dir), file_list)

For Python2.7+或Python3,您可以使用functools.partial

import functools
copier = functools.partial(copy_file, target_dir=target_dir)
p.map(copier, file_list)

相关问题 更多 >