簡體   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