-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstopwatch.py
More file actions
48 lines (39 loc) · 1.41 KB
/
Copy pathstopwatch.py
File metadata and controls
48 lines (39 loc) · 1.41 KB
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
"""Run an interactive terminal stopwatch.
Usage: python3.14 stopwatch.py
Press Enter for a lap, :t for total time, :s to pause, or :q to quit.
"""
from __future__ import annotations
import time
def format_duration(seconds: float) -> str:
"""Format a duration as an English hours/minutes/seconds string."""
total = int(seconds)
hours, remainder = divmod(total, 3600)
minutes, secs = divmod(remainder, 60)
return f"{hours} hours {minutes} minutes {secs} seconds"
def main() -> int:
started = lap_started = time.monotonic()
paused_total = 0.0
print("Stopwatch\n")
print("Commands: :q quit, :s pause, :t show total time")
while True:
try:
command = input("Press Enter or enter a command: ").strip()
except (EOFError, KeyboardInterrupt):
print()
return 0
now = time.monotonic()
if command == ":q":
return 0
if command == ":t":
print(f"Elapsed: {format_duration(now - started - paused_total)}")
elif command == ":s":
paused_at = time.monotonic()
input("Press Enter to resume the stopwatch")
pause = time.monotonic() - paused_at
paused_total += pause
lap_started += pause
else:
print(f"Lap: {format_duration(now - lap_started)}")
lap_started = now
if __name__ == "__main__":
raise SystemExit(main())