我正在创建一个程序,它会在一段时间后倒计时,并要求输入秒数以添加到倒计时中。 (不是真的,只是一个例子)。 有点像这样:
mytime = 10
while True:
print(time)
mytime -= 1
time.sleep(1)
mytime += int(input('add > '))
有两个问题。
我希望时间在一秒后仍然滴答作响,但不想在输入之前必须等待一秒。类似于 this .我想我需要使用线程。
我也不想等待输入!我只希望它在不等待输入的情况下打勾,并且在我需要的时候可以输入内容。
感谢您的帮助。
请您参考如下方法:
有一种比从 0 开始创建自己的线程更简单的方法。为您准备的计时器线程:
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()
或者带线程的简单版本(但比使用 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 将在input() 输出的提示信息之后插入打印的文本。
这会令人困惑。如果你想避免这种情况,那么你将不得不编写另一个线程来从队列中获取消息并输出它们。
如果最后一条消息是提示消息,那么您必须将其从屏幕上移除,写入新消息,然后返回提示消息,并相应地定位光标。
您可以通过在 threading.Thread 的子类中实现类似文件的接口(interface),然后用它替换 sys.stdout 来实现。也许重写 input() 以及指示何时发出提示消息并读取标准输入。
