如何在 Python 中制作计时器程序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15802554/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to make a timer program in Python
提问by Erich Von Hinken
Here is my goal: To make a small program (text based) that will start with a greeting, print out a timer for how long it has been since the last event, and then a timer for the event. I have used this code to start out with trying to figure out a timer, but my first problem is that the timer keeps repeating on a new line with each new second. How do I get that to stop? Also, this timer seems to lag behind actual seconds on the clock.
这是我的目标:制作一个以问候语开头的小程序(基于文本),打印出自上次事件以来已经过去了多长时间的计时器,然后打印出事件的计时器。我已经使用此代码开始尝试找出一个计时器,但我的第一个问题是计时器每增加一秒就会在新行上不断重复。我怎样才能让它停止?此外,这个计时器似乎落后于时钟上的实际秒数。
import os
import time
s=0
m=0
while s<=60:
os.system('cls')
print (m, 'Minutes', s, 'Seconds')
time.sleep(1)
s+=1
if s==60:
m+=1
s=0
回答by sberry
I would go with something like this:
我会用这样的东西:
import time
import sys
time_start = time.time()
seconds = 0
minutes = 0
while True:
try:
sys.stdout.write("\r{minutes} Minutes {seconds} Seconds".format(minutes=minutes, seconds=seconds))
sys.stdout.flush()
time.sleep(1)
seconds = int(time.time() - time_start) - minutes * 60
if seconds >= 60:
minutes += 1
seconds = 0
except KeyboardInterrupt, e:
break
Here I am relying on actual time module rather than just sleep incrementer since sleep won't be exactly 1 second.
在这里,我依赖于实际时间模块,而不仅仅是睡眠增量器,因为睡眠不会正好是 1 秒。
Also, you can probably use printinstead of sys.stdout.write, but you will almost certainly need sys.stdout.flushstill.
此外,您可能可以使用print而不是sys.stdout.write,但您几乎肯定会需要sys.stdout.flush仍然。
Like:
喜欢:
print ("\r{minutes} Minutes {seconds} Seconds".format(minutes=minutes, seconds=seconds)),
Note the trailing comma so a new line is not printed.
请注意尾随逗号,因此不会打印新行。
回答by Simon
On my PC (Windows 7) when run in a cmdwindow, this program works almost exactly as you say it should. If the timer is repeating on a new line with each second, that suggests to me that os.system ('cls')is not working for you -- perhaps because you're running on an OS other than Windows?
在我的 PC (Windows 7) 上,在cmd窗口中运行时,该程序几乎完全按照您说的那样工作。如果计时器每秒在新行上重复一次,这向我表明这os.system ('cls')对您不起作用 - 可能是因为您在 Windows 以外的操作系统上运行?
The statement while s<=60:appears to be incorrect because swill never be equal to 60 in that test -- anytime it gets to 60, it is reset to 0 and mis incremented. Perhaps the test should be while m<60:?
该语句while s<=60:似乎不正确,因为s在该测试中永远不会等于 60 —— 任何时候达到 60,它都会重置为 0 并m递增。也许测试应该是while m<60:?
Finally, on my PC, the timer does not appear to lag behind actual seconds on the clock by much. Inevitably, this code will lag seconds on the clock by a little -- i.e. however long it takes to run all the lines of code in the whileloop apart from time.sleep(1), plus any delay in returning the process from the sleeping state. In my case, that isn't very long at all but, if running that code took (for some reason) 0.1 seconds (for instance), the timer would end up running 10% slow compared to wall clock time. @sberry's answer provides one way to deal with this problem.
最后,在我的 PC 上,计时器似乎并没有落后于时钟上的实际秒数。不可避免地,这段代码会在时钟上稍微滞后几秒——即,运行while循环中除 之外的所有代码行需要多长时间time.sleep(1),加上从睡眠状态返回进程的任何延迟。就我而言,这根本不是很长,但是,如果运行该代码需要(出于某种原因)0.1 秒(例如),则与挂钟时间相比,计时器的运行速度最终会慢 10%。@sberry 的回答提供了一种处理这个问题的方法。
回答by TheMerovingian
Ok, I'll start with why your timer is lagging.
好的,我将从为什么您的计时器滞后开始。
What happens in your program is that the time.sleep()call "sleeps" the program's operation for 1 second, once that second has elapsed your program begins execution again. But your program still needs time to execute all the other commands you've told it to do, so it takes 1s + Xsto actually perform all the operations. Although this is a very basic explanation, it's fundamentally why your timer isn't synchronous.
在您的程序中发生的情况是time.sleep()调用“休眠”了程序的操作 1 秒,一旦该秒过去,您的程序将再次开始执行。但是您的程序仍然需要时间来执行您告诉它执行的所有其他命令,因此需要1s + Xs实际执行所有操作。尽管这是一个非常基本的解释,但从根本上说,这就是您的计时器不同步的原因。
As for why you're constantly printing on a new line, the print()function has a pre-defined end of line character that it appends to any string it is given.
至于为什么你不断地在新行上打印,该print()函数有一个预定义的行尾字符,它附加到它给定的任何字符串。
print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
You can overwrite this with anything by putting end="YourThing"in your print statement like so
您可以通过end="YourThing"像这样放入打印语句来用任何内容覆盖它
for x in range(3):
print("Test", end="")
The above example appends an empty string to the end of the line, so the output of the loop would be
上面的例子在行尾附加了一个空字符串,所以循环的输出将是
"TestTestTest"
As for solving your timer problem, you should use something similar to
至于解决您的计时器问题,您应该使用类似于
timePoint = time.time()
while True:
#Convert time in seconds to a gmtime struct
currentTime = time.gmtime(time.time() - timePoint))
#Convert the gmtime struct to a string
timeStr = time.strftime("%M minutes, %S seconds", currentTime)
#Print the time string
print(timeStr, end="")
回答by PyGuy
Use the timeit module to time your code. Then adjust the time.sleep(x) accordingly. For example, you could use one of the following:
使用 timeit 模块为您的代码计时。然后相应地调整 time.sleep(x)。例如,您可以使用以下方法之一:
import timeit
#Do all your code and time stuff and while loop
#Store that time in a variable named timedLoop
timer = 1- timedLoop
#Inside while loop:
time.sleep(timer)
This will time the code you have other than the time.sleep, and subtract that from 1 second and will sleep for that amount of time. This will give an accurate representation of 1 second. Another way is less work, but may not be as accurate:
这将对 time.sleep 以外的代码进行计时,并将其从 1 秒中减去,然后睡眠该时间。这将给出 1 秒的准确表示。另一种方法是更少的工作,但可能不那么准确:
#set up timeit module in another program and time your code, then do this:
#In new program:
timer = 1 - timerLoop
print timerLoop
Run your program, then copy the printed time and paste it into program two, the one you have now. Use timerLoop in your time.sleep():
运行您的程序,然后复制打印的时间并将其粘贴到程序二中,即您现在拥有的程序。在 time.sleep() 中使用 timerLoop:
time.sleep(timerLoop)
That should fix your problem.
那应该可以解决您的问题。
回答by user5556486
This is my version. It's great for beginners.
这是我的版本。这对初学者来说很棒。
# Timer
import time
print("This is the timer")
# Ask to Begin
start = input("Would you like to begin Timing? (y/n): ")
if start == "y":
timeLoop = True
# Variables to keep track and display
Sec = 0
Min = 0
# Begin Process
timeLoop = start
while timeLoop:
Sec += 1
print(str(Min) + " Mins " + str(Sec) + " Sec ")
time.sleep(1)
if Sec == 60:
Sec = 0
Min += 1
print(str(Min) + " Minute")
# Program will cancel when user presses X button
回答by Kurt Peters
This seems like it would be MUCH easier:
这似乎会容易得多:
#!/usr/bin/env python
from datetime import datetime as dt
starttime = dt.now()
input("Mark end time")
endtime = dt.now()
print("Total time passed is {}.".format(endtime-starttime))
回答by Force Fighter
a simple timer program that has sound to remind you would be:
一个有声音提醒你的简单定时器程序是:
from time import sleep
import winsound
m = 0
print("""**************************
Welcome To FASTIMER?
**************************""")
while True:
try:
countdown = int(input("How many seconds: "))
break
except ValueError:
print("ERROR, TRY AGAIN")
original = countdown
while countdown >= 60:
countdown -= 60
m += 1
for i in range (original,0,-1):
if m < 0:
break
for i in range(countdown,-2,-1):
if i % 60 == 0:
m-=1
if i == 0:
break
print(m," minutes and ",i," seconds")
sleep(1)
if m < 0:
break
for j in range(59,-1,-1):
if j % 60 == 0:
m-=1
print(m," minutes and ",j," seconds")
sleep(1)
print("TIMER FINISHED")
winsound.PlaySound('sound.wav', winsound.SND_FILENAME)
this program uses time.sleep() to wait a second. It converts every 60 seconds to a minute. the sound only works with Windows or you can install pygame to add sounds.
该程序使用 time.sleep() 等待一秒钟。它每 60 秒转换为一分钟。声音仅适用于 Windows,或者您可以安装 pygame 来添加声音。
回答by TMagnetB
# Timer
import time
import winsound
print " TIMER"
#Ask for Duration
Dur1 = input("How many hours? : ")
Dur2 = input("How many minutes?: ")
Dur3 = input("How many seconds?: ")
TDur = Dur1 * 60 * 60 + Dur2 * 60 + Dur3
# Ask to Begin
start = raw_input("Would you like to begin Timing? (y/n): ")
if start == "y":
timeLoop = True
# Variables to keep track and display
CSec = 0
Sec = 0
Min = 0
Hour = 0
# Begin Process
timeLoop = start
while timeLoop:
CSec += 1
Sec += 1
print(str(Hour) + " Hours " + str(Min) + " Mins " + str(Sec) + " Sec ")
time.sleep(1)
if Sec == 60:
Sec = 0
Min += 1
Hour = 0
print(str(Min) + " Minute(s)")
if Min == 60:
Sec = 0
Min = 0
Hour += 1
print(str(Hour) + " Hour(s)")
elif CSec == TDur:
timeLoop = False
print("time\'s up")
input("")
while 1 == 1:
frequency = 1900 # Set Frequency To 2500 Hertz
duration = 1000 # Set Duration To 1000 ms == 1 second
winsound.Beep(frequency, duration)
I based my timer on user5556486's version. You can set the duration, and it will beep after said duration ended, similar to Force Fighter's version
我的计时器基于 user5556486 的版本。您可以设置持续时间,持续时间结束后会发出哔哔声,类似于Force Fighter的版本
回答by Hoàng Minh Anh
I have a better way:
我有一个更好的方法:
import time
s=0
m=0
while True:
print(m, 'minutes,', s, 'seconds')
time.sleep(0.999999999999999999999) # the more 9s the better
s += 1
if s == 60:
s=0
m += 1
回答by LumberFizz
# This Is the Perfect Timer!(PS: This One Really Works!)
import sys
import time
import os
counter=0
s = 0
m = 0
n = int(input("Till How Many Seconds do you want the timer to be?: "))
print("")
while counter <= n:
sys.stdout.write("\x1b[1A\x1b[2k")
print(m, 'Minutes', s, 'Seconds')
time.sleep(1)
s += 1
counter+=1
if s == 60:
m += 1
s = 0
print("\nTime Is Over Sir! Timer Complete!\n")

