如何在 Python 中实现计时器

How to implement timer in Python

我希望在 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`

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

通常在多线程环境中开发定时器我使用 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