>>> import sys
>>> import StringIO
>>> stdout = sys.stdout # keep a handle on the real standard output
>>> sys.stdout = StringIO.StringIO() # Choose a file-like object to write to
>>> foo()
>>> sys.stdout = stdout
>>> foo()
bar
我已經看到這種情況甚至更好 - 您可以創建一個context manager到標準輸出設置成任何你想要的,當你進入情境,然後有上下文管理器復位標準輸出,當你__exit__
上下文。
下面是使用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'
# Examples with StringIO
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()
# Now with a file object:
with open('new_stdout') as f:
with stdout_redirect(f):
foo()
# Just to prove that we actually did put stdout back as we were supposed to
print "Now calling foo without context"
foo()
注:
在python3.x,StringIO.StringIO
已經轉移到io.StringIO
。此外,在python2.x上,cStringIO.StringIO
可能會稍微更高性能。
Python 3中,我相信? –
爲什麼不簡單地使用自己的打印功能? – phant0m
函數定義給出,我不能函數本身。 – Alex