Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/359.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 无法将参数传递给使用多重处理的方法。池_Python_Python 2.7_Multiprocessing - Fatal编程技术网

Python 无法将参数传递给使用多重处理的方法。池

Python 无法将参数传递给使用多重处理的方法。池,python,python-2.7,multiprocessing,Python,Python 2.7,Multiprocessing,我的程序接受几个参数,其中一个参数叫做challenges,它从命令行接收整数值。我希望通过将挑战值传递给自定义方法生成来使用多处理: GenParentClass类中的方法生成具有以下简单签名: def generation(self, num): #some stuff 但是,我得到了这个错误: Traceback (most recent call last): File "experiments.py", line 194, in <module> X,

我的程序接受几个参数,其中一个参数叫做challenges,它从命令行接收整数值。我希望通过将挑战值传递给自定义方法生成来使用多处理:

GenParentClass类中的方法生成具有以下简单签名:

def generation(self, num):
   #some stuff
但是,我得到了这个错误:

Traceback (most recent call last):
  File "experiments.py", line 194, in <module>
    X, y = mlp.imap_unordered(gen.generation, [args.challenges])
  File "/anaconda/lib/python2.7/multiprocessing/pool.py", line 668, in next
    raise value
cPickle.PicklingError: Can't pickle <type 'instancemethod'>: attribute lookup __builtin__.instancemethod failed
我不知道如何解决这个问题。在我看来一切都是正确的!!感谢您对操作系统的任何帮助。

多进程模块将pickle参数序列化为imap_无序。似乎gen.generation函数是类中定义的实例方法,这意味着它不能被pickle,因此会出现错误

编辑:这里有一个可能的解决方法,它在类之外定义函数,并向该函数添加其他参数,这些参数使用itertools中的partial填充:

关于pickle能力的更多信息可用

有关functools的更多信息可用

编辑2:如果使用multiprocess.Pool且函数定义使用限定变量名self.a和self.b,则无需在类外重写函数即可执行此操作,但您将无法检索输出,gen2的状态也不会改变,根本无法达到调用函数的目的

gen2 = GenParentClass(4, 6)
p = {}
for key in range(5):
    p[key] = multiprocessing.Process(target = GenParentClass.altgen, args = (gen2, key,))
    p[key].start()

for key in p:
    p[key].join()

对的是否有一种不必更改类的解决方法?我可以使用多处理。处理,条件是变量a和b在altgen函数中是限定的,请参见上面的编辑2,但问题是您无法检索输出。gen是一个类还是一个类的实例?@martineau gen是GenParentClass的实例当我使用生成方法将其作为一个代理类的实例时,我得到了另一个错误:ValueError:没有足够的值来解包预期的2,得到了1。请回答您的问题并添加足够的代码以重新创建问题。看见注意,我还在代码中主任务的正确位置添加了一个if uuuu name_uuuuuuu=='uuuuu main_uuuuuuuuuuu':命令。
import multiprocessing
from functools import partial

class GenParentClass(object):
    a = None
    b = None
    def __init__(self, a, b):
        self.a = a
        self.b = b

# define this outside of GenParentClass (i.e., top level function)
def generation(num, x, y):
    return x+y+num

gen = GenParentClass(3, 5)
mlp = multiprocessing.Pool(processes=multiprocessing.cpu_count())
R = mlp.imap_unordered(partial(generation, x=gen.a, y=gen.b), [1,2,3])
print([r for r in R])   # prints "[9, 10, 11]"
gen2 = GenParentClass(4, 6)
p = {}
for key in range(5):
    p[key] = multiprocessing.Process(target = GenParentClass.altgen, args = (gen2, key,))
    p[key].start()

for key in p:
    p[key].join()