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”的语法错误。我想知道如何将关键字参数传递给目标函数。
3 个解决方案
#1
44
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.
这将传递一个字典,其中关键字参数'names为键,参数值为字典中的值。上面的另一个答案是行不通的,因为在该范围内未定义“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'})
#2
4
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()
#3
1
Try to replace args
with kwargs={x: 1, y: 2}
.
尝试用kwargs = {x:1,y:2}替换args。
#1
44
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.
这将传递一个字典,其中关键字参数'names为键,参数值为字典中的值。上面的另一个答案是行不通的,因为在该范围内未定义“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'})
#2
4
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()
#3
1
Try to replace args
with kwargs={x: 1, y: 2}
.
尝试用kwargs = {x:1,y:2}替换args。