| 1 |
|
| 2 |
|
| 3 |
import argparse |
| 4 |
import re |
| 5 |
import signal |
| 6 |
import subprocess |
| 7 |
import sys |
| 8 |
import threading |
| 9 |
|
| 10 |
|
| 11 |
def main(): |
| 12 |
p = argparse.ArgumentParser( |
| 13 |
description='Run a program, and kill it if it is silent for too long.' |
| 14 |
'After the arguments, specify the program to run prefixed ' |
| 15 |
'with -- .') |
| 16 |
p.add_argument('--timeout', type=parse_timeout, |
| 17 |
help='Timeout (in seconds, if no unit specified') |
| 18 |
|
| 19 |
our_args = sys.argv[1:] |
| 20 |
cmd = [] |
| 21 |
if '--' in our_args: |
| 22 |
index = our_args.index('--') |
| 23 |
cmd = our_args[index + 1:] |
| 24 |
our_args = our_args[:index] |
| 25 |
|
| 26 |
args = p.parse_args(our_args) |
| 27 |
if not cmd: |
| 28 |
p.error('No command specified') |
| 29 |
|
| 30 |
run_cmd(cmd, args.timeout) |
| 31 |
|
| 32 |
|
| 33 |
def parse_timeout(arg): |
| 34 |
m = re.match(r'(\d+) *(s(ec(ond)?s?)?|m(in(ute)?s?)?|h((ou)?rs?)?)?', arg) |
| 35 |
if not m: |
| 36 |
raise argparse.ArgumentTypeError('Un-parseable time') |
| 37 |
value = int(m.group(1)) |
| 38 |
unit = m.group(2) |
| 39 |
if unit: |
| 40 |
unit = unit[0] |
| 41 |
if unit == 'm': |
| 42 |
return value * 60 |
| 43 |
if unit == 'h': |
| 44 |
return value * 60 * 60 |
| 45 |
return value |
| 46 |
|
| 47 |
|
| 48 |
def run_cmd(cmd, timeout): |
| 49 |
p = subprocess.Popen(cmd, encoding='UTF-8', bufsize=1, |
| 50 |
stdout=subprocess.PIPE) |
| 51 |
watchdog = Watchdog(timeout, p) |
| 52 |
watchdog.start() |
| 53 |
while True: |
| 54 |
line = p.stdout.readline() |
| 55 |
watchdog.event.set() |
| 56 |
sys.stdout.write(line) |
| 57 |
sys.stdout.flush() |
| 58 |
if p.poll() != None: |
| 59 |
sys.exit(p.returncode) |
| 60 |
|
| 61 |
|
| 62 |
class Watchdog(threading.Thread): |
| 63 |
def __init__(self, timeout, process): |
| 64 |
super(Watchdog, self).__init__() |
| 65 |
self.daemon = True |
| 66 |
self.timeout = timeout |
| 67 |
self.process = process |
| 68 |
self.event = threading.Event() |
| 69 |
|
| 70 |
def run(self): |
| 71 |
while True: |
| 72 |
ev = self.event.wait(self.timeout) |
| 73 |
if ev is True: |
| 74 |
self.event.clear() |
| 75 |
else: |
| 76 |
sys.stderr.write( |
| 77 |
'\nTimed out after {} seconds of inactivity...\n' |
| 78 |
.format(self.timeout)) |
| 79 |
sys.stderr.flush() |
| 80 |
self.process.send_signal(signal.SIGINT) |
| 81 |
return |
| 82 |
|
| 83 |
|
| 84 |
if __name__ == '__main__': |
| 85 |
main() |