Pass keyword arguments to target function in Python threading.Thread

后端 未结 3 810
太阳男子
太阳男子 2020-12-16 09:03

I want to pass named arguments to the target function, while creating a Thread object.

Following is the code that I have written:

import threading

         


        
相关标签:
3条回答
  • 2020-12-16 09:36
    t = threading.Thread(target=f, kwargs={'x': 1,'y': 2})
    

    this will pass a dictionary with the keyword arguments' names as keys and argument values as values in the dictionary. the other answer above won't work, because the "x" and "y" are undefined in that scope.

    another example, this time with multiprocessing, passing both positional and keyword arguments:

    the function used being:

    def f(x, y, kw1=10, kw2='1'):
        pass
    

    and then when called using multiprocessing:

    p = multiprocessing.Process(target=f, args=('a1', 2,), kwargs={'kw1': 1, 'kw2': '2'})
    
    0 讨论(0)
  • 2020-12-16 09:41

    Try to replace args with kwargs={x: 1, y: 2}.

    0 讨论(0)
  • 2020-12-16 09:53

    You can also just pass a dictionary straight up to kwargs:

    import threading
    
    def f(x=None, y=None):
        print x,y
    
    my_dict = {'x':1, 'y':2}
    t = threading.Thread(target=f, kwargs=my_dict)
    t.start()
    
    0 讨论(0)
提交回复
热议问题