如何让Pool.map使用lambda函数
我有一个这样的函数:
def copy_file(source_file, target_dir):
pass
现在我想用 multiprocessing
来同时执行这个函数:
p = Pool(12)
p.map(lambda x: copy_file(x,target_dir), file_list)
问题是,lambda 表达式不能被序列化,所以这样会失败。有什么比较简洁(符合 Python 风格)的方法来解决这个问题吗?
5 个回答
11
这个问题有点老了,但如果你还在用Python 2,我的回答可能对你有帮助。
这里的窍门是使用pathos项目中的一部分:multiprocess,这是对原始multiprocessing的一个改进版。它解决了原来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]
71
对于Python2.7以上版本或者Python3,你可以使用functools.partial这个功能:
import functools
copier = functools.partial(copy_file, target_dir=target_dir)
p.map(copier, file_list)
78
使用一个函数对象:
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)