Created
November 13, 2013 17:41
-
-
Save zed/7453163 to your computer and use it in GitHub Desktop.
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 | |
""" | |
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