Created
June 11, 2015 21:23
-
-
Save thejohnfreeman/448f924edea8a7f7f7a0 to your computer and use it in GitHub Desktop.
Python Popen with timeout
This file contains hidden or 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
| import os | |
| import signal | |
| import subprocess | |
| import threading | |
| class AsyncPopen(threading.Thread): | |
| def __init__(self, command, stdin=None, **kwargs): | |
| self.command = command | |
| self.stdin = stdin | |
| self.stdout = None | |
| self.stderr = None | |
| kwargs['stdin'] = subprocess.PIPE | |
| kwargs['stdout'] = subprocess.PIPE | |
| kwargs['stderr'] = subprocess.PIPE | |
| kwargs['preexec_fn'] = os.setpgrp | |
| self.kwargs = kwargs | |
| threading.Thread.__init__(self) | |
| def run(self): | |
| self.proc = subprocess.Popen(self.command, **self.kwargs) | |
| self.stdout, self.stderr = self.proc.communicate(self.stdin) | |
| def wait(self, timeout): | |
| self.join(timeout) | |
| if self.proc.returncode is None: | |
| os.killpg(self.proc.pid, signal.SIGTERM) | |
| self.proc.wait() | |
| ap = AsyncPopen(['bash', '-c', 'echo bar; sleep 2; echo foo']) | |
| ap.start() | |
| ap.wait(1) | |
| assert ap.stdout == 'bar\n' | |
| assert ap.stderr == '' | |
| assert not ap.is_alive() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment