慕哥9229398
试试这个上下文管理器# import StringIO for Python 2 or 3try: from StringIO import StringIOexcept ImportError: from io import StringIOimport sysclass 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)output 现在是一个包含函数调用打印的行的列表。高级用法:可能不明显的是,这可以不止一次完成并且结果连接起来: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']更新:他们还说redirect_stdout()到contextlib在Python 3.4(沿redirect_stderr())。因此,您可以使用io.StringIO它来实现类似的结果(尽管Capturing列表以及上下文管理器可以说更方便)。