import threading import os from subprocess import Popen, PIPE, STDOUT cmd_to_call=['/usr/bin/grep', '-q', 'localhost', '/etc/hosts'] # variant for nonempty stdout: # cmd_to_call=['/usr/bin/grep', 'localhost', '/etc/hosts'] class AsyncReader(threading.Thread): def __init__(self, channel): super(AsyncReader, self).__init__() self.chan = channel self.output = '' self.start() self.join() def run(self): try: while True: line = self.chan.read(2048) if not line: # Pipe can remain open after output has completed print("EOF received, to break") break self.output = self.output + line except (ValueError, IOError): # pipe has closed, meaning command output is done print("pipe closed") pass def get_contents(self): return self.output p = Popen(cmd_to_call, shell=False, stdout=PIPE, stderr=PIPE, bufsize=-1,# env=os.environ.copy(), close_fds=True) reader = AsyncReader(p.stdout) stdout = reader.get_contents() pollstatus = p.poll() print("output: '%s', return code: %s, pollstatus=%s" % (stdout, p.returncode, pollstatus))