LoginSignup
1
1

More than 5 years have passed since last update.

メモ:pythonのprintを文字列で受け取る

Posted at

モチベーション

外部ライブラリがprintをしてくるとき,それを文字列として受け取りたいことがあった.

方法

contextlib.redirect_stdoutを使ってio.StringIOに標準出力をつなぎ変えてしまえばよい
https://docs.python.jp/3/library/contextlib.html

import io
from contextlib import redirect_stdout
f = io.StringIO()
with redirect_stdout(f):
    print("hoge")
    print("huga")
f.getvalue()
>>> 'hoge\nhuga\n'

標準入力を全て繋ぎ変えてしまっている点は注意.

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1