Skip to content

Commit 9e1ec73

Browse files
committed
sleep: Add sleep.py
1 parent c9445a4 commit 9e1ec73

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

src/sleep.py

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
#!/usr/bin/python3
2+
3+
import sys
4+
import time
5+
from decimal import Decimal
6+
from optparse import OptionParser
7+
8+
SUFFIXES = {"s": 1, "m": 60, "h": 60 * 60, "d": 24 * 60 * 60}
9+
10+
11+
def sleep(total_secs: Decimal):
12+
try:
13+
time.sleep(float(total_secs))
14+
except KeyboardInterrupt:
15+
print()
16+
sys.exit(130)
17+
18+
19+
if __name__ == "__main__":
20+
parser = OptionParser(
21+
usage="Usage: %prog DURATION[SUFFIX]...",
22+
description=(
23+
"Delay for the sum of each DURATION."
24+
f" SUFFIX may be one of the following: {", ".join(SUFFIXES.keys())}."
25+
),
26+
add_help_option=False,
27+
)
28+
parser.add_option("--help", action="help", help="show usage information and exit")
29+
30+
_, args = parser.parse_args()
31+
32+
total_secs = Decimal()
33+
34+
for spec in args:
35+
if spec[-1].isdecimal():
36+
total_secs += Decimal(spec)
37+
else:
38+
if not (multiplier := SUFFIXES.get(spec[-1])):
39+
parser.error(f"invalid duration: {spec}")
40+
total_secs += Decimal(spec[:-1]) * multiplier
41+
42+
sleep(total_secs)

0 commit comments

Comments
 (0)