]> git.sthu.org Git - shutils.git/blob - timer.py
Add iptables systemd units
[shutils.git] / timer.py
1 #!/usr/bin/python3
2
3 import sys
4 import time
5 import datetime
6
7 units = {"s" : 1, "m" : 60, "h" : 60*60, "d" : 24*60*69 }
8
9 def reprint(value, file=sys.stdout, end=""):
10 print("\r" + value, file=file, end=end)
11
12
13 def usage():
14 print("""Usage: {0} [--reverse] [--offset <time>] [--update <time>] [--round <int>]
15 {0} -h
16 {0} --help
17
18 Options:
19 --reverse count backwards
20 --offset <time> start counting from specified offset
21 --update <time> interval between two screen updates
22 --round <int> round seconds by specified number of digits
23
24 <time> is an integer specifing the number of seconds or a string
25 of the format "<int>(Undefined, Undefined, Undefined, Undefined)" with the suffixes d(ay), h(our),
26 m(inute), s(econd).
27 """.format(sys.argv[0]))
28
29 def parseTime(value):
30
31 factor = 1
32
33 if value[-1] in units:
34 factor = units[value[-1]]
35 value = value[:-1]
36
37 return float(value)*factor
38
39
40 def formatTime(secs, digits=0):
41
42 sign = ""
43 if secs < 0:
44 sign = "-"
45 secs = -secs
46
47 days = int(secs/units["d"])
48 secs -= days * units["d"]
49
50 hours = int(secs/units["h"])
51 secs -= hours * units["h"]
52
53 mins = int(secs/units["m"])
54 secs -= mins * units["m"]
55
56 s = "%.{0}f".format(digits) % (round(secs, digits) ) + "s"
57 if days>0:
58 s = " %dd %dh %dm %s" %(days, hours, mins, s)
59 elif hours>0:
60 s = " %dh %dm %s" %(hours, mins, s)
61 elif mins>0:
62 s = " %dm %s" %(mins, s)
63
64 s = sign + s
65 return s
66
67
68 def parseArgs():
69 opts = {"help" : False, "reverse" : False, "offset" : 0.0, "update" : 1,
70 "round" : 0}
71 i=1
72 while i<len(sys.argv):
73
74 if sys.argv[i] in ["-h", "--help"]:
75 opts["help"] = True
76 elif sys.argv[i] in ["--reverse"]:
77 opts["reverse"] = True
78 elif sys.argv[i] in ["--offset"]:
79 i = i+1
80 opts["offset"] = parseTime(sys.argv[i])
81 elif sys.argv[i] in ["--update"]:
82 i = i+1
83 opts["update"] = parseTime(sys.argv[i])
84 elif sys.argv[i] in ["--round"]:
85 i = i+1
86 opts["round"] = int(sys.argv[i])
87 else:
88 raise "Unknown option '{0}'".format(sys.argv[i])
89
90 i = i+1
91 return opts
92
93
94 if __name__ == "__main__":
95
96 opts = parseArgs()
97
98 if opts["help"]:
99 usage()
100 sys.exit(0)
101
102 start=time.time()
103
104 print("started at " + str(datetime.datetime.now()))
105
106 while True:
107
108 diff=time.time()-start
109 if opts["reverse"]:
110 diff = -diff
111 diff += opts["offset"]
112
113 reprint(formatTime(diff, opts["round"]) + " ")
114 time.sleep(opts["update"])
115
116
117
118