Reputation: 405
I would like to run a definition in the background, and pass an argument into it (how long it should run for), but the following code isn't working:
thread = threading.Thread(target= run_timer, args=timer_time_value) # Where timer_time_value is taken from user input, and converted into an integer.
thread.daemon = True
thread.start()
def run_timer(time_to_sleep_For):
time_to_sleep_For = int(time_to_sleep_For)
time.sleep(time_to_sleep_For)
Speak("Timer done!")
If I use process, I replace the first chunk of code with:
p = Process(target= run_timer, args=timer_time_value)
p.start()
p.join()
However, both return:
TypeError: 'int' object is not iterable
My question is, which module should I use, and what is the correct way to set it up?
Upvotes: 0
Views: 59
Reputation: 16624
As @roganjosh pointed out you need to pass a list or a tuple (see Thread). This is working example:
import threading
import time
def run_timer(time_to_sleep_for):
time.sleep(time_to_sleep_for)
print("Timer done!")
user_time = "3"
try:
user_time = int(user_time)
except ValueError:
user_time = 0 # default sleep
thread = threading.Thread(target=run_timer,
args=(user_time,))
thread.daemon = True
thread.start()
thread.join()
For the differences between processes and threads see this answers.
BTW: It is maybe better to parse the user input outside the thread as shown in the example.
Upvotes: 3