How to pass arguments to threading.Thread() in Python?
In Python, parameters can be passed to threading.Thread() in several ways.
- arguments
- arguments
import threading
def func(arg1, arg2):
print("Thread function:", arg1, arg2)
t = threading.Thread(target=func, args=("Hello", "World"))
t.start()
- keyword arguments
- keyword arguments
import threading
def func(arg1, arg2):
print("Thread function:", arg1, arg2)
t = threading.Thread(target=func, kwargs={"arg1": "Hello", "arg2": "World"})
t.start()
- arguments
- arguments
- arguments
- arguments
import threading
def func(arg1, arg2):
print("Thread function:", arg1, arg2)
t = threading.Thread(target=func, args=("Hello",), kwargs={"arg2": "World"})
t.start()
The above is a common way of passing parameters through args and kwargs arguments. Of course, parameters can also be flexibly passed through other methods, such as through instance attributes, global variables, and so on.