我正在使用Pool来使用starmap多线程化我的程序来传递参数。
我被卡住了,因为我似乎无法找到一种方法来传递kwargs以及我在starmap函数中传递的 zip 数组。
pool = Pool(NO_OF_PROCESSES)
branches = pool.starmap(fetch_api, zip(repeat(project_name), api_extensions))
分支机构请求不完整,因为我仍然无法弄清楚如何传递关键字参数。
def fetch_api(project_name, api_extension, payload={}, headers={}, API_LINK=API_LINK, key=False):
headers[AUTH_STRING] = 'Gogo'
call_api = API_LINK + project_name + api_extension
response_api = requests.get(call_api, headers=headers, params=payload)
if key: return project_name + ':' + response_api
else: return response_api
从分支行调用 fetch_api()时,我希望将有效负载作为{'a':1}和key = True传递。
请指导我指导或回答。谢谢。使用Python 3.3 +。
答案 0 :(得分:2)
您可以围绕pool.starmap
创建一个包装器,该包装器还接受over kwargs字典的迭代器。
from itertools import repeat
def starmap_with_kwargs(pool, fn, args_iter, kwargs_iter):
args_for_starmap = zip(repeat(fn), args_iter, kwargs_iter)
return pool.starmap(apply_args_and_kwargs, args_for_starmap)
def apply_args_and_kwargs(fn, args, kwargs):
return fn(*args, **kwargs)
然后您可以按以下方式称呼它:
args_iter = zip(repeat(project_name), api_extensions)
kwargs_iter = repeat(dict(payload={'a': 1}, key=True))
branches = starmap_with_kwargs(pool, fetch_api, args_iter, kwargs_iter)