如何通过名称将变量传递给Python中的Thread?

时间:2021-07-17 23:16:14

Say that I have a function that looks like:

假设我有一个看起来像这样的函数:

def _thread_function(arg1, arg2=None, arg3=None):
    #Random code

Now I want to create a thread using that function, and giving it arg2 but not arg3. I'm trying to this as below:

现在我想使用该函数创建一个线程,并给它arg2而不是arg3。我正在尝试如下:

#Note: in this code block I have already set a variable called arg1 and a variable called arg2
threading.Thread(target=self._thread_function, args=(arg1, arg2=arg2), name="thread_function").start()

The above code gives me a syntax error. How do I fix it so that I can pass an argument to the thread as arg2?

上面的代码给了我一个语法错误。我如何修复它,以便我可以将参数作为arg2传递给线程?

1 个解决方案

#1


41  

Use the kwargs parameter:

使用kwargs参数:

threading.Thread(target=self._thread_function, args=(arg1,),
                 kwargs={'arg2':arg2}, name='thread_function').start()

#1


41  

Use the kwargs parameter:

使用kwargs参数:

threading.Thread(target=self._thread_function, args=(arg1,),
                 kwargs={'arg2':arg2}, name='thread_function').start()