如何在 Python 中制作计时器程序 [英] How to make a timer program in Python

查看:29
本文介绍了如何在 Python 中制作计时器程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的目标:制作一个以问候语开头的小程序(基于文本),打印出自上次事件以来已经过去了多长时间的计时器,然后打印出事件的计时器.我已经使用此代码开始尝试找出一个计时器,但我的第一个问题是计时器每增加一秒就会在新行上不断重复.我怎样才能让它停止?此外,这个计时器似乎落后于时钟上的实际秒数.

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

推荐答案

我会选择这样的:

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

这里我依赖于实际时间模块,而不仅仅是睡眠增量器,因为睡眠不会正好是 1 秒.

Here I am relying on actual time module rather than just sleep incrementer since sleep won't be exactly 1 second.

此外,您可能可以使用 print 而不是 sys.stdout.write,但您几乎肯定需要 sys.stdout.flush仍然.

Also, you can probably use print instead of sys.stdout.write, but you will almost certainly need sys.stdout.flush still.

喜欢:

print ("\r{minutes} Minutes {seconds} Seconds".format(minutes=minutes, seconds=seconds)),

注意结尾的逗号,以免打印新行.

Note the trailing comma so a new line is not printed.

这篇关于如何在 Python 中制作计时器程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆