简体   繁体   中英

TypeError When Passing Arguments to a Python Thread

I am trying to write a simple threading program. It works well when I don't try to pass any variables the target function.

import threading
import time
import datetime

def my_function():
    thread_start_time = str(datetime.datetime.now())
    thread_start_time_remove_microseconds = thread_start_time[:19]

    print("\n\nThread Execution Start Time: ", thread_start_time_remove_microseconds)
    print("I am being printed by mythread. Sleeping for 5 seconds. Main thread will wait till I finish")
    time.sleep(5)

    thread_end_time = str(datetime.datetime.now())
    thread_end_time_remove_microseconds = thread_end_time[:19]

    print("Thread Execution End Time: ", thread_end_time_remove_microseconds)


def main():
    mythread= threading.Thread(target=my_function, name="thread1")
    mythread.start()

    print("\n\n","=" * 31,"I am printed by the main thread","=" * 31,"\n\n")


if __name__ == "__main__":
    main()

which results into:

Thread Execution Start Time: 

 2018-09-09 17:02:46
 =============================== I am printed by the main thread =============================== 


I am being printed by mythread. Sleeping for 5 seconds. Main thread will wait till I finish
Thread Execution End Time:  2018-09-09 17:02:51

Process finished with exit code 0

However, when I try to pass a variable to the function, I get below error: import threading import time import datetime

def my_function(one_variable):
    print(one_variable)
    thread_start_time = str(datetime.datetime.now())
    thread_start_time_remove_microseconds = thread_start_time[:19]

    print("\n\nThread Execution Start Time: ", thread_start_time_remove_microseconds)
    print("I am being printed by mythread. Sleeping for 5 seconds. Main thread will wait till I finish")
    time.sleep(5)

    thread_end_time = str(datetime.datetime.now())
    thread_end_time_remove_microseconds = thread_end_time[:19]

    print("Thread Execution End Time: ", thread_end_time_remove_microseconds)


def main():
    mythread= threading.Thread(target=my_function, name="thread1", args=("This is one variable from main"))
    mythread.start()

    print("\n\n","=" * 31,"I am printed by the main thread","=" * 31,"\n\n")


if __name__ == "__main__":
    main()

It results into:

=============================== I am printed by the main thread =============================== 


Exception in thread thread1:
Traceback (most recent call last):
  File "C:\Users\dparvez\AppData\Local\Programs\Python\Python36-32\lib\threading.py", line 916, in _bootstrap_inner
    self.run()
  File "C:\Users\dparvez\AppData\Local\Programs\Python\Python36-32\lib\threading.py", line 864, in run
    self._target(*self._args, **self._kwargs)
TypeError: my_function() takes 1 positional argument but 30 were given


Process finished with exit code 0

Can someone please help as why I am getting this error.

you need a comma to make args a tuple, like this:

mythread= threading.Thread(
    target=my_function
    name="thread1",
    args=("This is one variable from main",))

This is because threading.Thread() expects args to be some iterable and enumerates it to get all args to pass to your function.

The expression ("string") is equal to just "string" - and it IS an iterable, resulting in ("s", "t", "r", "i", "n", "g"). Not what you wanted. To tell Python that ("string") is a one-element tuple and not a parenthesized expression, do ("string",).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM