如何在Python中实现计时器

时间:2017-05-02 07:03:14

标签: python python-2.7 timer countdown countdowntimer

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

`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`

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

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

将它放入/ 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
相关问题