Posted By

silviud on 09/25/11


Tagged

python linux


Versions (?)

runWithTimeout


 / Published in: Python
 

runs a given command into a specific time.

  1. import os, time, select, pty
  2.  
  3. if os.environ.get("TEST_VERBOSE"):
  4. verbose = True
  5. else:
  6. verbose = False
  7.  
  8.  
  9. def runWithTimeout(cmd, timeout):
  10. args = cmd.split()
  11. pid, fd = pty.fork();
  12. startTime = time.time()
  13.  
  14. if pid == 0:
  15. os.execvp(args[0], args)
  16. output = ""
  17. while time.time() - startTime < timeout:
  18. i, o, e = select.select([fd], [], [], timeout)
  19. if fd in i:
  20. try:
  21. str = os.read(fd, 1)
  22. output += str
  23. except OSError, e:
  24. exitPid, status = os.waitpid(pid, os.WNOHANG)
  25.  
  26. if exitPid == pid:
  27. if verbose:
  28. print "Child exited with %i" % status
  29. return status, output
  30.  
  31. if verbose:
  32. print "Command timed out: killing pid %i" % pid
  33.  
  34. os.kill(pid, signal.SIGINT)
  35. raise Exception("Command execution time exceeded %i seconds" % timeout,
  36. outputSoFar=output)

Report this snippet  

You need to login to post a comment.