Pet*_*mit 50 python pool multiprocessing
我有以下功能:
def copy_file(source_file, target_dir):
pass
Run Code Online (Sandbox Code Playgroud)
现在我想用来立即multiprocessing执行这个功能:
p = Pool(12)
p.map(lambda x: copy_file(x,target_dir), file_list)
Run Code Online (Sandbox Code Playgroud)
问题是,lambda不能被腌制,所以这就失败了.解决这个问题最简洁(pythonic)的方法是什么?
Fre*_*Foo 63
使用函数对象:
class Copier(object):
def __init__(self, tgtdir):
self.target_dir = tgtdir
def __call__(self, src):
copy_file(src, self.target_dir)
Run Code Online (Sandbox Code Playgroud)
运行你的Pool.map:
p.map(Copier(target_dir), file_list)
Run Code Online (Sandbox Code Playgroud)
unu*_*tbu 39
对于Python2.7 +或Python3,您可以使用functools.partial:
import functools
copier = functools.partial(copy_file, target_dir=target_dir)
p.map(copier, file_list)
Run Code Online (Sandbox Code Playgroud)
pet*_*hka 10
问题有点老了,但如果您仍在使用 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]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
18867 次 |
| 最近记录: |