我正在尝试捕获标准输出,然后在调用函数后对其进行解析。我通过 cStringIO.StringIO 对象这样做,但 readline 调用没有产生任何结果。我创建了以下测试来向您展示发生了什么:
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
生成的输出是:
getvalue:
testing this stuff
more testing of this
readlines:
readstream:
testing this stuff
more testing of this
stream.readlines() 怎么没有产生任何结果?
谢谢