このコンテキストマネージャーを試してください:
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
関数呼び出しによって出力された行を含むリストになりました。
高度な使い方:
明らかではないかもしれないことは、これが複数回実行され、結果が連結される可能性があるということです:
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']
更新: Python 3.4 に追加さredirect_stdout()
れましcontextlib
た (とともにredirect_stderr()
)。したがって、それを使用io.StringIO
して同様の結果を得ることができます (ただしCapturing
、コンテキスト マネージャーと同様にリストであることは間違いなくより便利です)。