有一种比从0开始自己的线程更简单的方法.为您准备的Timer线程:
import threading
timer = None
def wuf ():
global timer
print "Wuf-wuf!"
timer = threading.Timer(5, wuf)
timer.start()
timer = threading.Timer(5, wuf)
timer.start()
input() # Don't exit the program
此代码将等待5秒钟,然后开始打印“Wuf-wuf!”每5秒钟.
如果你想从主线程中停止它:
timer.cancel()
但是如果您使用事件驱动的GUI系统(如wxPython或PyQT)编写GUI应用程序,那么您应该使用他们的事件管理计时器.特别是如果您要从计时器回调更改某些GUI状态.
编辑:
哦,好的,这是你的完整答案:
import threading
seconds = 1 # Initial time must be the time+1 (now 0+1)
timer = None
def tick ():
global seconds, timer
seconds -= 1
if seconds==0:
print("%i seconds left" % seconds)
print("Timer expired!")
return
# printing here will mess up your stdout in conjunction with input()
print("%i second(s) left" % seconds)
timer = threading.Timer(1, tick)
timer.start()
seconds += int(input("Initial countdown interval: "))
tick()
while 1:
seconds += int(input("Add: "))
if not timer.is_alive():
print("Restarting the timer!")
seconds += 1
tick()
或者带有线程的简单版本(但是有点clumsyer然后使用threading.Thread):
from thread import start_new_thread as thread
from time import sleep
seconds = 1 # Initial time+1
alive = 0
def _tick ():
global seconds, alive
try:
alive = 1
while 1:
seconds -= 1
if seconds==0:
print("%i seconds left" % seconds)
print("Timer expired!")
alive = 0
return
# printing here will mess up your stdout in conjunction with input()
print("%i second(s) left" % seconds)
sleep(1)
except: alive = 0
def tick ():
thread(_tick,())
# Then same as above:
seconds += int(input("Initial countdown interval: "))
tick()
while 1:
seconds += int(input("Add: "))
if not alive:
print("Restarting the timer!")
seconds += 1
tick()
您必须意识到在线程中使用stdout将在输入()输出的提示消息之后插入打印的文本.
这将令人困惑.如果你想避免这种情况,那么你将不得不编写另一个线程来获取队列中的消息并输出它们.
如果最后一条消息是提示消息,则必须将其从屏幕中删除,写入新消息,然后返回提示消息,并相应地定位光标.
你可以通过在threading.Thread的子类中实现类似文件的接口,然后用它替换sys.stdout来实现.也许重写input()以指示何时提示消息输出并且stdin被读取.