私はこの出力をキャプチャするのにcontext managerを使用します。それは最終的にはsys.stdout
を一時的に置き換えることによって、他のいくつかの回答と同じテクニックを使用します。私はコンテクストマネージャーを好んでいます。なぜなら、すべての簿記を単一の関数にまとめているから、try-finallyコードを書き直す必要はなく、セットアップとティアダウンの関数を書く必要はありません。
import sys
from contextlib import contextmanager
from StringIO import StringIO
@contextmanager
def captured_output():
new_out, new_err = StringIO(), StringIO()
old_out, old_err = sys.stdout, sys.stderr
try:
sys.stdout, sys.stderr = new_out, new_err
yield sys.stdout, sys.stderr
finally:
sys.stdout, sys.stderr = old_out, old_err
このようにそれを使用する:元の出力状態がwith
ブロックを出る時に復元されるので
with captured_output() as (out, err):
foo()
# This can go inside or outside the `with` block
output = out.getvalue().strip()
self.assertEqual(output, 'hello world!')
さらに、我々は最初のものと同じ機能で第二キャプチャブロックを設定することができこれはsetupとteardown関数を使っては不可能で、try-finallyブロックを手動で書くときにはwordyになります。その能力は、テストの目的が、いくつかの事前計算された値ではなく、2つの関数の結果を互いに比較することだった場合に便利でした。
[ 'mock.patchと( 'sys.stdoutの'、new_callable = StringIO.StringIO):'](HTTP: //www.voidspace.org.uk/python/mock/patch.html#patch)https://pypi.python.org/pypi/mock/ – n611x007