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
|
#!/usr/bin/python
"""Run a command until it succeeds.
Lars Wirzenius <liw@liw.fi>
"""
import optparse
import subprocess
import sys
import time
def do_until(options, argv):
while True:
if options.verbose:
sys.stderr.write("do-until: executing: %s\n" % " ".join(argv))
if options.no_act:
sys.stderr.write("do-until: not running command, pretending it "
"works anyway\n")
break
else:
p = subprocess.Popen(argv)
p.communicate()
if p.returncode == 0:
break
sys.stderr.write("do-until: command failed, "
"trying again in %d second(s)\n" % options.sleep)
time.sleep(options.sleep)
def parse_args(args):
parser = optparse.OptionParser()
parser.add_option("-n", "--no-act", action="store_true",
help="Do not run command, just pretend to do it, and "
"pretend that it succeeds.")
parser.add_option("-v", "--verbose", action="store_true",
help="Print command before executing it.")
parser.add_option("--sleep", type="int", default=1, metavar="SECS",
help="Wait SECS seconds before re-trying a command. "
"(Default is %default.)")
options, argv = parser.parse_args(args)
return options, argv
def main():
try:
options, argv = parse_args(sys.argv[1:])
if argv:
do_until(options, argv)
except KeyboardInterrupt:
sys.exit(1)
if __name__ == "__main__":
main()
|