Cómo dejar Piscina.map take a lambda function


Tengo la siguiente función:

def copy_file(source_file, target_dir):
    pass

Ahora me gustaría usar multiprocessing para ejecutar esta función a la vez:

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

El problema es que lambda no puede ser encurtido, así que esto falla. ¿Cuál es la más cuidada (python) manera de arreglar esto?

Author: Nicolás, 2011-01-28

4 answers

Utilice un objeto de función:

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

Para ejecutar su Pool.map:

p.map(Copier(target_dir), file_list)
 53
Author: Fred Foo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-07-19 09:33:21

Para Python2. 7 + o Python3, puedes usar funtools.parcial:

import functools
copier = functools.partial(copy_file, target_dir=target_dir)
p.map(copier, file_list)
 21
Author: unutbu,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-07-21 12:09:39

La pregunta es un poco vieja, pero si todavía usas Python 2 mi respuesta puede ser útil.

Truco es utilizar parte de pathosproyecto: multiprocess bifurcación de multiprocesamiento. Se deshace de la limitación molesta de multiproceso original.

Instalación: pip install multiprocess

Uso:

>>> 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]
 1
Author: petRUShka,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-06-22 18:55:49

Desde esta respuesta, pathos vamos a ejecutar su lambda p.map(lambda x: copy_file(x,target_dir), file_list) directamente, guardando todas las soluciones / hacks

 0
Author: Woofas,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 11:55:09