我正在尝试运行以下代码。它无法运行5分钟,请您告诉我这里的问题。我试图在后台运行它,保存为.pyw
并在完成1小时后提醒我,根据计时器参数传递的内容。
import time
import ctypes
def timer(minutes):
seconds = minutes * 60
start = time.time()
time.clock()
elapsed = 0
while elapsed < seconds:
elapsed = time.time() - start
time.sleep(1)
timer(5) #would want enter in hours not in seconds
ctypes.windll.user32.MessageBoxA(0,"DoneToday", "Dones", 0)
答案 0 :(得分:1)
您的timer()
函数无限循环。
在while elapsed < seconds:
循环后,两行向下,您已放置timer(5)
。所以,只是再次召唤自己,再次,再次......
删除此行后,它将按预期工作:
timer(5) #would want enter in hours not in seconds
正如@vermillon所提到的那样,你有什么理由不只是做time.sleep(minutes * 60)
?我假设您打算在该循环中做其他事情,而不仅仅是计算时间。
编辑:让OP看到正在运行的代码
>>> def timer(minutes):
... seconds = minutes * 60
... start = time.time()
... time.clock()
... elapsed = 0
... while elapsed < seconds:
... elapsed = time.time() - start
... time.sleep(1)
... ctypes.windll.user32.MessageBoxA(0,"DoneToday", "Dones", 0)
... print 'also printing Done so you can see it'
...
>>> timer(0.1)
also printing Done so you can see it
>>>
答案 1 :(得分:0)
如果您想要一个计时器来显示剩余的分钟和秒,那么这是适合您的代码段:
import time
import sys
def run_timer(seconds):
for remaining in range(seconds, 0, -1):
sys.stdout.write("\r")
minutes = 0
seconds = remaining
if remaining > 60:
minutes = int(seconds/60)
seconds = int(seconds%60)
else:
seconds = remaining
sys.stdout.write("{:2d} minutes {:2d} seconds remaining.".format(minutes,seconds))
sys.stdout.flush()
time.sleep(0.1)
sys.stdout.write("Timer complete")
run_timer(120)