将关键字参数传递给 Python threading.Thread 中的目标函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30913201/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Pass keyword arguments to target function in Python threading.Thread
提问by rayu
I want to pass named arguments to the target function, while creating a Thread object.
我想在创建 Thread 对象时将命名参数传递给目标函数。
Following is the code that I have written:
以下是我写的代码:
import threading
def f(x=None, y=None):
print x,y
t = threading.Thread(target=f, args=(x=1,y=2,))
t.start()
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.
我在第 6 行收到“x=1”的语法错误。我想知道如何将关键字参数传递给目标函数。
采纳答案by vladosaurus
t = threading.Thread(target=f, kwargs={'x': 1,'y': 2})
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.
这将传递一个字典,其中关键字参数的名称作为键,参数值作为字典中的值。上面的另一个答案不起作用,因为“x”和“y”在该范围内未定义。
another example, this time with multiprocessing, passing both positional and keyword arguments:
另一个例子,这次使用多处理,同时传递位置和关键字参数:
the function used being:
使用的功能是:
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'})
回答by f43d65
Try to replace args
with kwargs={x: 1, y: 2}
.
尝试替换args
为kwargs={x: 1, y: 2}
.
回答by Daniel
You can also just pass a dictionary straight up to kwargs:
您也可以直接将字典传递给 kwargs:
import threading
def f(x=None, y=None):
print x,y
my_dict = {'x':1, 'y':2}
t = threading.Thread(target=f, kwargs=my_dict)
t.start()