0

我试图使用python的多道处理库,但我遇到了一些困难:多进程Python中的函数,进行了多个参数

def request_solr(limit=10, offset=10): 
    # build my facets here using limit and offset 
    # request solr 
    return response.json() 

def get_list_event_per_user_per_mpm(limit=100): 
    nb_unique_user = get_unique_user() 
    print "Unique user: ", nb_unique_user 
    processor_pool = multiprocessing.Pool(4) 
    offset = range(0, nb_unique_user, limit) 
    list_event_per_user = processor_pool.map(request_solr(limit), offset) 
    return list_event_per_user 

我不知道如何将第二参数传递给函数。我怎样才能使它工作。我有以下错误:

TypeError: 'dict' object is not callable 

回答

1

您需要为此使用lambda表达式。您现在正在执行此操作的方式,它试图将request_solr作为函数的结果映射为offset作为参数。

这应该可以做到。

processor_pool.map(lambda x: request_solr(limit, x), offset) 

注意,这只适用于3.x.在2.x中,您需要创建一个函数对象。例如:

class RequestSolrCaller: 
    def __init__(self, limit) 
     self.limit = limit 
    def __call__(self, offset) 
     return request_solr(self.limit, offset) 

processor_pool.map(RequestSolrCaller(limit), offset) 
+0

我有以下错误:PicklingError:不能咸菜<类型“功能”>:属性查找__builtin __功能失效 – mel

+1

@mel啊,你必须在2.x的这只适用于3.x,我会将其添加到答案。 –

2

你看到的错误,因为你调用的函数之前将它传递给多。

我建议你结合使用starmapitertools.repeat

import itertools as it 

# rest of your code 

processor_pool = multiprocessing.Pool(4) 
offset = range(0, nb_unique_user, limit) 
list_event_per_user = processor_pool.starmap(request_solr, zip(it.repeat(limit), offset)) 

星图将调用功能扩展值对成两个参数。 repeat(limit)只是生成一个迭代器,其所有元素都等于limit

这可以为任意数量的参数工作:

def my_function(a, b, c, d, e): 
    return a+b+c+d+e 

pool = Pool() 
pool.starmap(my_function, [(1,2,3,4,5)]) # calls my_function(1,2,3,4,5) 

由于您使用的是旧版本的Python,你必须解决这个通过修改你的功能或使用包装函数:

def wrapper(arguments): 
    return request_solr(*arguments) 

# later: 

pool.map(wrapper, zip(repeat(limit), offset)) 
+0

我有以下错误:AttributeError:'Pool'对象没有属性'starmap' – mel

+1

@mel这是因为您使用的是古代版本的python。我会写一个替代方案。 – Bakuriu

+0

谢谢我将编辑标签python到python2.7 – mel

1

我曾经使用一个生成器来生成关键字。这是我的simple_multiproc.py的内容。

请注意在等级模块中使用request_solr的重要性。

import multiprocessing 

MAX=5 

def _get_pool_args(**kw): 
    for _ in range(MAX): 
     r = {"limit": 10, "offset": 10} 
     r.update(kw) 
     yield r 


def request_solr(limit=10, offset=10): 
    # build my facets here using limit and offset 
    # request solr 
    print(locals()) 
    response.json() 

if __name__ == "__main__": 
    pool = multiprocessing.Pool(MAX) 
    pool.map(request_solr, _get_pool_args())