73

我有以下功能:

def copy_file(source_file, target_dir):
    pass

现在我想用它multiprocessing来一次执行这个函数:

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

问题是,lambda 不能被腌制,所以这失败了。解决此问题的最简洁(pythonic)方法是什么?

4

4 回答 4

72

使用函数对象:

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)
于 2011-01-28T11:06:32.227 回答
65

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

import functools
copier = functools.partial(copy_file, target_dir=target_dir)
p.map(copier, file_list)
于 2011-01-28T13:26:55.647 回答
11

问题有点老了,但如果你还在使用 Python 2,我的回答会很有用。

诀窍是使用pathos项目的一部分:进程的多进程分支。它摆脱了原始多进程的烦人限制。

安装: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]
于 2016-06-22T18:55:49.477 回答
1

这个答案中,pathos 让你p.map(lambda x: copy_file(x,target_dir), file_list)直接运行你的 lambda,节省所有的变通方法/黑客

于 2017-01-16T06:19:36.250 回答