用户登录
用户注册

分享至

如何让 Pool.map 采用 lambda 函数

  • 作者: 段友533234
  • 来源: 51数据库
  • 2022-12-08

问题描述

我有以下功能:

def copy_file(source_file, target_dir):
    pass

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

Now I would like to use multiprocessing to execute this function at once:

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

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

The problem is, lambda's can't be pickled, so this fails. What is the most neat (pythonic) way to fix this?

推荐答案

使用函数对象:

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)
软件
前端设计
程序设计
Java相关