Passing multiple arguments in Python thread

22,951

The args parameter is a tuple, and allows you to pass many arguments to the target.

t1 = threading.Thread(target=Main2_TrapToTxtDb, args=(varBinds, otherVariable))

This is documented here:

threading.Thread(group=None, target=None, name=None, args=(), kwargs={})

This constructor should always be called with keyword arguments. Arguments are:

group should be None; reserved for future extension when a ThreadGroup class is implemented.

target is the callable object to be invoked by the run() method. Defaults to None, meaning nothing is called.

name is the thread name. By default, a unique name is constructed of the form “Thread-N” where N is a small decimal number.

args is the argument tuple for the target invocation. Defaults to ().

kwargs is a dictionary of keyword arguments for the target invocation. Defaults to {}.

Share:
22,951
Manoj Kumar M
Author by

Manoj Kumar M

Updated on July 09, 2022

Comments

  • Manoj Kumar M
    Manoj Kumar M almost 2 years

    The following code passes a list (varbinds) and it works fine.

    t1 = threading.Thread(target = Main2_TrapToTxtDb, args = (varBinds,))
    

    Now I need to pass another variable - vString along with this.

    Please help with a simple code.

  • Manoj Kumar M
    Manoj Kumar M over 7 years
    Thanks for the explanation. But the varbinds is a list. So the comma after the variable inside parenthesis...(varBinds,). So what is the syntax to add additional variables be added after a list variable. I feel confused.
  • Right leg
    Right leg over 7 years
    @Manmathan I think you are not sure what you are doing. varBinds is a list, so? Is it a list of arguments? Is it an argument whose type is list? Do you want to pass a list of arguments which contains vString? If so, just append it to varBinds.
  • Right leg
    Right leg over 7 years
    @Manmathan I presume you added that comma because you got an error and noticed that comma got you rid of it. The args parameter receives a tuple, but when you have only one argument, you cannot write (argument), because this is parsed as argument, which is not a tuple. Therefore, you have to put a comma, so it is interpreted as a tuple: (argument, ). Since this tuple is meant to contain the arguments you pass to the thread's function, just put all the arguments in the tuple, as I wrote in the answer: (arg1, arg2, arg3, arg4).
  • Right leg
    Right leg over 7 years
    @Manmathan It seems your list is actually an argument of type list. Therefore, just write (once again, as I wrote in my answer): args=(varBinds, vString) (BTW, here the comma is optional, because there are two elements in the tuple, so Python interprets this unambiguously).
  • Right leg
    Right leg over 7 years
    @Manmathan You're welcome, but think about the documentation next time ;)