-
Notifications
You must be signed in to change notification settings - Fork 0
/
countdown
executable file
·73 lines (67 loc) · 2.33 KB
/
countdown
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#!/usr/bin/env python3
import os,re,sys,time
USAGE = """
USAGE: countdown TIME [REASON]
EXAMPLES: timer 5m30s pomodoro
timer "1 minute"
timer "5 hours 3 minute"
""".strip()
class ParseException(Exception): pass
def parse_time(arg): # minute only for now
SPACE = r'[ ,]*'
REGEX = re.compile(
SPACE +
r'(?:(?P<hours>\d+)(?:h|hour|hours))?' + SPACE +
r'(?:(?P<minutes>\d+)(?:m|min|mins|minute|minutes))?' + SPACE +
r'(?:(?P<seconds>\d+)(?:s|sec|secs|second|seconds))?' + SPACE
)
m = REGEX.fullmatch(arg)
if not m: raise ParseException("Unrecognized time format")
hours = int(m.group('hours') or 0)
minutes = int(m.group('minutes') or 0)
seconds = int(m.group('seconds') or 0)
t = seconds + minutes * 60 + hours * 3600
if t <= 0: raise ParseException("Unrecognized time format")
return t
def astime(seconds):
minutes, seconds = seconds // 60, seconds % 60
hours, minutes = minutes // 60, minutes % 60
if hours > 0:
return "{}:{:02}:{:02}".format(hours,minutes,seconds)
else:
return "{:02}:{:02}".format(minutes,seconds)
def print_status(total, elapsed, reason=None):
remaining = total - elapsed
remaining, elapsed = round(remaining), round(elapsed)
sys.stdout.write("\033[F\033[K") # Cursor up one line
if reason:
print("{} remaining, {} elapsed || {}".format(astime(remaining),astime(elapsed), reason))
else:
print("{} remaining, {} elapsed".format(astime(remaining),astime(elapsed)))
return remaining <= 0
def wait(a, reason=None):
try:
seconds = parse_time(a)
except ParseException:
print(USAGE, file=sys.stderr)
print("Unrecognized time format: {}".format(sys.argv[1]), file=sys.stderr)
sys.exit(1)
start_time = float(time.time())
elapsed = float(time.time())-start_time
done = print_status(seconds, elapsed, reason)
try:
while not done:
time.sleep(1)
elapsed = float(time.time())-start_time
done = print_status(seconds, elapsed, reason)
except KeyboardInterrupt:
sys.exit(2)
if __name__ == '__main__':
args = sys.argv[1:]
if len(args) == 1:
wait(args[0])
elif len(args) == 2:
wait(args[0], args[1])
else:
print(USAGE, file=sys.stderr)
sys.exit(1)