繁体   English   中英

如何在Python中实现计时器

[英]How to implement timer in Python

我希望在python中实现timer,但是找不到任何有用的文章。 我的主要目的是实现以下逻辑:

`timer -> 60 seconds to zero
     #do stuff
     if the user selects to manually reset the timer -> start the time loop again
     if user exits -> exit the time loop
 reset the timer and again do above steps`

我正在寻找文章/语法信息以实现上述逻辑。

通常要在多线程环境中开发计时器,我使用stopit软件包。 您可以定义一个计时器->创建一个在计时器上调用.cancel()的函数,以防用户按下取消按钮->捕获超时异常以重新启动计时器。

将其放在/ usr / bin / stopwatch中并给予适当的许可(chmod + x脚本)

eg: sudo chmod +x /usr/bin/stopwatch

这是代码

#!/usr/bin/python

from __future__ import print_function

import sys
import time


if len(sys.argv) != 2:
    print("Needs seconds as argument, Eg: stopwatch 10")
else:
    seconds = sys.argv[1]
    for i in range(int(seconds), 0, -1):
        print(str(" "*50), end='\r')
        print(str(i), end='\r')
        sys.stdout.flush()
        time.sleep(1)
    print("Time over {}".format(seconds))

用法

stopwatch 10

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM