Python 用于创建计时器函数的线程与进程
Python threading vs. process for creating a timer function
我想在后台 运行 一个定义,并向其中传递一个参数(它应该 运行 多长时间),但是下面的代码不起作用:
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!")
如果我使用进程,我将第一段代码替换为:
p = Process(target= run_timer, args=timer_time_value)
p.start()
p.join()
然而,return:
TypeError: 'int' object is not iterable
我的问题是,我应该使用哪个模块,正确的设置方法是什么?
正如@roganjosh 指出的那样,您需要传递一个列表或一个元组(参见 Thread)。这是工作示例:
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()
有关进程和线程之间的差异,请参阅 this answers。
顺便说一句:如示例所示,在线程外解析用户输入可能会更好。
我想在后台 运行 一个定义,并向其中传递一个参数(它应该 运行 多长时间),但是下面的代码不起作用:
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!")
如果我使用进程,我将第一段代码替换为:
p = Process(target= run_timer, args=timer_time_value)
p.start()
p.join()
然而,return:
TypeError: 'int' object is not iterable
我的问题是,我应该使用哪个模块,正确的设置方法是什么?
正如@roganjosh 指出的那样,您需要传递一个列表或一个元组(参见 Thread)。这是工作示例:
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()
有关进程和线程之间的差异,请参阅 this answers。
顺便说一句:如示例所示,在线程外解析用户输入可能会更好。