如何按名称将变量传递给 Python 中的线程? [英] How to pass a variable by name to a Thread in Python?

查看:37
本文介绍了如何按名称将变量传递给 Python 中的线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个如下所示的函数:

Say that I have a function that looks like:

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

现在我想使用该函数创建一个线程,并为其提供 arg2 而不是 arg3.我正在尝试如下:

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

#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()

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

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?

推荐答案

使用 kwargs 参数:

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

这篇关于如何按名称将变量传递给 Python 中的线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆