尝试此上下文管理器:
from cStringIO import StringIO
import sys
class Capturing(list):
def __enter__(self):
self._stdout = sys.stdout
sys.stdout = self._stringio = StringIO()
return self
def __exit__(self, *args):
self.extend(self._stringio.getvalue().splitlines())
del self._stringio # free up some memory
sys.stdout = self._stdout
用法:
with Capturing() as output:
do_something(my_object)
输出现在是一个包含函数调用打印的行的列表。
高级用法:
可能不明显的是,这可以做不止一次,结果连接:
with Capturing() as output:
print 'hello world'
print 'displays on screen'
with Capturing(output) as output: # note the constructor argument
print 'hello world2'
print 'done'
print 'output:', output
输出:
displays on screen
done
output: ['hello world', 'hello world2']