How to pass arguments to a thread?
Question:
I have test()
as shown below:
def test(arg1, arg2=None, arg3=None):
Now, I tries to create a thread using test()
, and giving it only arg1
and arg2
but not arg3 as shown below:
threading.Thread(target=test, args=(arg1, arg2=arg2)).start()
But, I got a syntax error. How can I solve the error so that I can pass an argument to the thread as arg2?
Answers:
Use the kwargs parameter:
threading.Thread(target=test, args=(arg1,), kwargs={'arg2':arg2}).start()
you can also use lambda to pass args
threading.Thread(target=lambda: test(arg1, arg2=arg2, arg3=arg3)).start()
I have test()
as shown below:
def test(arg1, arg2=None, arg3=None):
Now, I tries to create a thread using test()
, and giving it only arg1
and arg2
but not arg3 as shown below:
threading.Thread(target=test, args=(arg1, arg2=arg2)).start()
But, I got a syntax error. How can I solve the error so that I can pass an argument to the thread as arg2?
Use the kwargs parameter:
threading.Thread(target=test, args=(arg1,), kwargs={'arg2':arg2}).start()
you can also use lambda to pass args
threading.Thread(target=lambda: test(arg1, arg2=arg2, arg3=arg3)).start()