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
|
from __future__ import print_function
import sys
import os
import threading
import subprocess
try:
timeout = int(sys.argv[1])
cmd = sys.argv[2:]
if len(cmd) == 0:
raise ValueError()
except:
print("usage: timeout-run.py TIMEOUT COMMAND...", file=sys.stderr)
exit(1)
proc = subprocess.Popen(cmd)
def trap():
print("timeout of {}s expired, aborting".format(timeout), file=sys.stderr)
try:
proc.terminate()
except:
pass
timer = threading.Timer(timeout, trap)
timer.start()
try:
ret = proc.wait()
if ret >= 0:
os._exit(ret)
else:
os.kill(os.getpid(), -ret)
except:
proc.terminate()
os._exit(127)
|