将关键字参数传递给Python线程中的目标函数 [英] Pass keyword arguments to target function in Python threading.Thread
问题描述
我想在创建Thread对象时将命名参数传递给目标函数.
I want to pass named arguments to the target function, while creating a Thread object.
以下是我编写的代码:
import threading
def f(x=None, y=None):
print x,y
t = threading.Thread(target=f, args=(x=1,y=2,))
t.start()
在第6行中出现"x = 1"的语法错误. 我想知道如何将关键字参数传递给目标函数.
I get a syntax error for "x=1", in Line 6. I want to know how I can pass keyword arguments to the target function.
推荐答案
t = threading.Thread(target=f, kwargs={'x': 1,'y': 2})
这将传递一个字典,该字典将关键字参数的名称作为键,并将参数值作为字典中的值. 上面的其他答案将不起作用,因为在该范围内未定义"x"和"y".
this will pass a dictionary with the keyword arguments' names as keys and argument values as values in the dictionary. the other answer above won't work, because the "x" and "y" are undefined in that scope.
另一个例子,这次是多重处理,同时传递了位置参数和关键字参数:
another example, this time with multiprocessing, passing both positional and keyword arguments:
使用的功能是:
def f(x, y, kw1=10, kw2='1'):
pass
,然后在使用多处理程序调用时:
and then when called using multiprocessing:
p = multiprocessing.Process(target=f, args=('a1', 2,), kwargs={'kw1': 1, 'kw2': '2'})
这篇关于将关键字参数传递给Python线程中的目标函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!