My solution that supports stdout.readline() and stdout.readlines():
import os
import subprocess
class MockStdout():
def __init__(self, output):
self.output = output.split('\n')
self.ix = 0
def readlines(self):
return '\n'.join(self.output)
def readline(self):
value = None
if self.ix < len(self.output):
value = self.output[self.ix]
self.ix += 1
return value
class MockSubprocess:
def __init__(self, output):
self.stdout = MockStdout(output)
real_popen = getattr(subprocess, 'Popen')
try:
setattr(subprocess, 'Popen', lambda *args, **kwargs: MockSubprocess('''First Line
Hello
there
from a stranger
standing here
Last Line
''' ))
cmd = [ 'a_command',
'--a_switch',
'--a_parameter=a_value' ]
listen_subprocess = subprocess.Popen(cmd,
cwd=os.getcwd(),
stdout=subprocess.PIPE,
universal_newlines=True)
while True:
line = listen_subprocess.stdout.readline()
if not line:
break
else:
print(line)
finally:
setattr(subprocess.Popen, '__call__', real_popen)