ryochack
6/23/2012 - 2:51 PM

python timer

python timer

#!/usr/local/bin/python3

import sys
import re
import threading


# CountDownTimer
def countdown(count):
    print(count)
    if count > 0:
        count -= 1
        # Timerハンドラ設定。1s後にcountdown起動。引数はリスト指定。
        t = threading.Timer(1, countdown, [count])
        t.start()
    else:
        print("complete!")


if __name__ == '__main__':
    argv = sys.argv
    argc = len(argv)
    if argc != 2:
        print("too few argments. set XXmXXs.")
        quit()

    # searchは繰り返し検索。matchは先頭からのマッチを探す。
    m = re.search(r'(\d{1,2})m', argv[1])
    s = re.search(r'(\d{1,3})s?\Z', argv[1])

    # search/matchは一致しない場合、Noneを返す。
    # Noneとの比較はisを使う
    minutes = 0 if m is None else int(m.group(1))
    seconds = 0 if s is None else int(s.group(1))

    count = minutes * 60 + seconds
    countdown(count)