【问题标题】:How to implement timer in Python如何在 Python 中实现定时器
【发布时间】:2017-05-02 07:03:13
【问题描述】:

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

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

【问题讨论】:

  • 您在什么环境下工作?用户是否通过终端、GUI 或浏览器与您的程序交互?
  • 使用time.tme() ?
  • @tiwo 我目前正在使用终端,但会在烧瓶中升级它以在浏览器中使用它。所以,现在我希望在终端中实现它。

标签: python python-2.7 timer countdown countdowntimer


【解决方案1】:

把它放在你的 /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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-08-03
      • 2013-03-04
      • 1970-01-01
      • 1970-01-01
      • 2018-04-23
      • 1970-01-01
      • 2011-04-29
      相关资源
      最近更新 更多