对于Python3.4及以上版本,标准库中提供了一个上下文管理器来实现此功能。
with contextlib.redirect_stdout(file_like_object):
...
这个答案的一部分已经更新,但主要是针对仍然停留在python2.x世界中的人
如果您被困在较旧版本的Python上,编写此上下文管理器并不太难。关键是您可以将sys.stdout
更新为任何文件类似对象(这就是print
写入的内容):
>>> import sys
>>> import StringIO
>>> stdout = sys.stdout
>>> sys.stdout = StringIO.StringIO()
>>> foo()
>>> sys.stdout = stdout
>>> foo()
bar
为了创建一个上下文管理器,在进入上下文时将stdout设置为您想要的任何内容,然后在退出上下文时重置stdout。
这里有一个使用contextlib
创建上下文管理器的简单示例:
import contextlib
import sys
@contextlib.contextmanager
def stdout_redirect(where):
sys.stdout = where
try:
yield where
finally:
sys.stdout = sys.__stdout__
def foo():
print 'bar'
import StringIO
with stdout_redirect(StringIO.StringIO()) as new_stdout:
foo()
new_stdout.seek(0)
print "data from new_stdout:",new_stdout.read()
new_stdout1 = StringIO.StringIO()
with stdout_redirect(new_stdout1):
foo()
new_stdout1.seek(0)
print "data from new_stdout1:",new_stdout1.read()
with open('new_stdout') as f:
with stdout_redirect(f):
foo()
print "Now calling foo without context"
foo()
注意:
在Python3.x中,StringIO.StringIO已经移动到io.StringIO。此外,在Python2.x中,cStringIO.StringIO可能略微更加高效。
sys.stdout
以捕获它? - Jon Clementssys.stdout
重定向到StringIO
对象的解决方案。 - David Robinsonprint
... - l4mpi