Created
December 9, 2011 05:11
-
-
Save alexras/1450276 to your computer and use it in GitHub Desktop.
Execute a child process, redirecting its output and error to files. If it's not done after a predetermined number of seconds, KILL IT WITH FIRE. Tested on Python 2.4+
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
""" | |
Execute a child process, redirecting its output and error to files. If it's not | |
done after a predetermined number of seconds, KILL IT WITH FIRE | |
""" | |
from optparse import OptionParser | |
import shlex, subprocess, time, os, sys | |
def timed_kill(program, stdout_file, stderr_file, timeout): | |
stdout_fp = open(stdout_file, 'w+') | |
stderr_fp = open(stderr_file, 'w+') | |
# Spawn the child process | |
child_process = subprocess.Popen(program, stdout=stdout_fp, | |
stderr=stderr_fp) | |
# Poll the process every half a second until it either finishes or time runs out | |
max_poll_loops = timeout * 2 | |
poll_loops = 0 | |
while child_process.returncode == None and poll_loops < max_poll_loops: | |
child_process.poll() | |
time.sleep(0.5) | |
poll_loops += 1 | |
# Process still isn't done, time to kill it | |
if child_process.returncode == None: | |
os.system("kill %d" % (child_process.pid)) | |
for fp in [stdout_fp, stderr_fp]: | |
fp.write("\n\n*** Timed out after %d seconds, killed ***\n" % | |
(timeout)) | |
for fp in [stdout_fp, stderr_fp]: | |
fp.flush() | |
fp.close() | |
def main(): | |
parser = OptionParser(usage="%prog [options] " | |
"<child program and its arguments>") | |
parser.add_option("-o", "--output", help="file to which to output stdout " | |
"from child process") | |
parser.add_option("-e", "--error", help="file to which to output stderr " | |
"from child process") | |
parser.add_option("-t", "--timeout", help="number of seconds to wait " | |
"before timing out and killing the child process", | |
type=int) | |
(options, args) = parser.parse_args() | |
program = shlex.split(' '.join(args)) | |
timed_kill(program = program, | |
stdout_file = options.output, | |
stderr_file = options.error, | |
timeout = options.timeout) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
KILL ALL THE THINGS WITH FIRE.