0

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?

1
  • 3
    args expects an iterable. Pass as args=(timer_time_value,) i.e. a tuple with 1 item in it Commented Sep 18, 2017 at 18:31

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

@roganjosh: Thanks for your initial comment. Glad I could help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.