問題描述
我需要一些方法來使用 pool.map() 中接受多個參數的函數.根據我的理解, pool.map() 的目標函數只能有一個可迭代的參數,但是有沒有一種方法可以傳遞其他參數?在這種情況下,我需要傳入一些配置變量,例如我的 Lock() 和日志信息到目標函數.
I need some way to use a function within pool.map() that accepts more than one parameter. As per my understanding, the target function of pool.map() can only have one iterable as a parameter but is there a way that I can pass other parameters in as well? In this case, I need to pass in a few configuration variables, like my Lock() and logging information to the target function.
我試圖做一些研究,我認為我可以使用部分函數來讓它工作?但是我不完全理解這些是如何工作的.任何幫助將不勝感激!這是我想做的一個簡單示例:
I have tried to do some research and I think that I may be able to use partial functions to get it to work? However I don't fully understand how these work. Any help would be greatly appreciated! Here is a simple example of what I want to do:
def target(items, lock):
for item in items:
# Do cool stuff
if (... some condition here ...):
lock.acquire()
# Write to stdout or logfile, etc.
lock.release()
def main():
iterable = [1, 2, 3, 4, 5]
pool = multiprocessing.Pool()
pool.map(target(PASS PARAMS HERE), iterable)
pool.close()
pool.join()
推薦答案
你可以使用functools.partial
為此(正如您所懷疑的那樣):
You can use functools.partial
for this (as you suspected):
from functools import partial
def target(lock, iterable_item):
for item in iterable_item:
# Do cool stuff
if (... some condition here ...):
lock.acquire()
# Write to stdout or logfile, etc.
lock.release()
def main():
iterable = [1, 2, 3, 4, 5]
pool = multiprocessing.Pool()
l = multiprocessing.Lock()
func = partial(target, l)
pool.map(func, iterable)
pool.close()
pool.join()
例子:
def f(a, b, c):
print("{} {} {}".format(a, b, c))
def main():
iterable = [1, 2, 3, 4, 5]
pool = multiprocessing.Pool()
a = "hi"
b = "there"
func = partial(f, a, b)
pool.map(func, iterable)
pool.close()
pool.join()
if __name__ == "__main__":
main()
輸出:
hi there 1
hi there 2
hi there 3
hi there 4
hi there 5
這篇關于在 Python 中將多個參數傳遞給 pool.map() 函數的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!