/ Published in: Python
runs a given command into a specific time.
Expand |
Embed | Plain Text
import os, time, select, pty if os.environ.get("TEST_VERBOSE"): verbose = True else: verbose = False def runWithTimeout(cmd, timeout): args = cmd.split() pid, fd = pty.fork(); startTime = time.time() if pid == 0: os.execvp(args[0], args) output = "" while time.time() - startTime < timeout: i, o, e = select.select([fd], [], [], timeout) if fd in i: try: str = os.read(fd, 1) output += str except OSError, e: exitPid, status = os.waitpid(pid, os.WNOHANG) if exitPid == pid: if verbose: print "Child exited with %i" % status return status, output if verbose: print "Command timed out: killing pid %i" % pid os.kill(pid, signal.SIGINT) raise Exception("Command execution time exceeded %i seconds" % timeout, outputSoFar=output)
You need to login to post a comment.
