2 回答

TA貢獻1877條經(jīng)驗 獲得超6個贊
試試這個上下文管理器
# import StringIO for Python 2 or 3
try:
from StringIO import StringIO
except ImportError:
from io 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)
output 現(xiàn)在是一個包含函數(shù)調(diào)用打印的行的列表。
高級用法:
可能不明顯的是,這可以不止一次完成并且結(jié)果連接起來:
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它來實現(xiàn)類似的結(jié)果(盡管Capturing列表以及上下文管理器可以說更方便)。

TA貢獻1788條經(jīng)驗 獲得超4個贊
在python> = 3.4中,contextlib包含一個redirect_stdout裝飾器。它可以用來回答你的問題:
import io
from contextlib import redirect_stdout
f = io.StringIO()
with redirect_stdout(f):
do_something(my_object)
out = f.getvalue()
來自文檔:
用于臨時將sys.stdout重定向到另一個文件或類文件對象的上下文管理器。
此工具為輸出硬連線到stdout的現(xiàn)有函數(shù)或類增加了靈活性。
例如,help()的輸出通常發(fā)送到sys.stdout。您可以通過將輸出重定向到io.StringIO對象來捕獲字符串中的輸出:
f = io.StringIO()
with redirect_stdout(f):
help(pow)
s = f.getvalue()
要將help()的輸出發(fā)送到磁盤上的文件,請將輸出重定向到常規(guī)文件:
with open('help.txt', 'w') as f:
with redirect_stdout(f):
help(pow)
要將help()的輸出發(fā)送到sys.stderr:
with redirect_stdout(sys.stderr):
help(pow)
請注意,sys.stdout的全局副作用意味著此上下文管理器不適合在庫代碼和大多數(shù)線程應用程序中使用。它對子進程的輸出也沒有影響。但是,它仍然是許多實用程序腳本的有用方法。
此上下文管理器是可重入的。
添加回答
舉報