Skip to content

Instantly share code, notes, and snippets.

@zed
Created November 13, 2013 17:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zed/7453163 to your computer and use it in GitHub Desktop.
Save zed/7453163 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
"""
http://stackoverflow.com/questions/19959271/in-python-how-can-i-use-timeout-in-subprocess-and-get-the-output
"""
from subprocess import Popen, PIPE
from threading import Timer
from timeit import default_timer as timer
start = timer()
# start process
process = Popen("echo 'Process started'; sleep 2; echo 'Process finished'",
shell=True, stdout=PIPE, bufsize=1, universal_newlines=True)
# kill process in a second
hitman = Timer(1, process.kill)
hitman.start()
# collect output
output = ''.join(iter(process.stdout.readline, ''))
hitman.cancel()
print("Got %r in %.2f seconds" % (output, timer() - start))
process.stdout.close()
process.wait()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment