Reading lines in captured stdout in python
I am trying to capture stdout and then parse it after calling a function.
I am doing so by means of a cStringIO.StringIO object but the readline
call yields nothing. I have created below test to show you what's
happening:
import cStringIO, sys
def readstream(s):
c = s.getvalue()
for i in c.split('\n'):
yield i
old_stdout = sys.stdout
stream = cStringIO.StringIO()
sys.stdout = stream
print ('testing this stuff')
print ('more testing of this')
sys.stdout = old_stdout
print 'getvalue:'
print stream.getvalue()
print 'readlines:'
for line in stream.readlines():
print line
print 'readstream:'
for line in readstream(stream):
print line
The generated output is:
getvalue:
testing this stuff
more testing of this
readlines:
readstream:
testing this stuff
more testing of this
How is it that the stream.readlines() is yielding nothing?
thanks
No comments:
Post a Comment