且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将关键字参数传递给Python线程中的目标函数

更新时间:2022-05-26 03:54:06

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'})