Python redirect_stdoutの使い方|print出力を文字列・ファイルに取り込む方法と、捕まらない出力
Pythonのcontextlib.redirect_stdout()は、withブロックの間だけsys.stdoutを別の書き込み先に差し替える関数です。with redirect_stdout(io.StringIO()) as f:の中でprint()すると、画面には出ずにf.getvalue()で文字列として取り出せます。
ただし、捕まえられるのはsys.stdout経由の出力だけです。os.system()やsubprocess、C拡張が直接書く出力、別スレッドの出力では、思ったとおりにならないことがあります。この記事では、基本の書き方から「捕まらない出力」までを、Python 3.12.15で実行した結果つきで説明します。
redirect_stdoutの基本:printの出力を文字列で受け取る
import io
from contextlib import redirect_stdout
with redirect_stdout(io.StringIO()) as f:
print("捕まえた")
print("2行目")
s = f.getvalue()
print("取得:", repr(s))
実行結果:
取得: '捕まえた\n2行目\n'
withの中のprint()は画面に出ず、すべてio.StringIO()(メモリ上の書き込み先)にたまります。公式ドキュメントにあるとおり、redirect_stdout()は差し替え先のオブジェクトを__enter__()で返すので、as fで受け取れます(contextlib.redirect_stdout – Python公式ドキュメント)。redirect_stdout()はPython 3.4、redirect_stderr()は3.5で追加された標準ライブラリなので、インストールは不要です。
help()の出力を文字列にする
公式ドキュメントの例と同じく、画面に出力するしかない関数の結果を文字列にできます。
import io
from contextlib import redirect_stdout
with redirect_stdout(io.StringIO()) as f:
help(len)
text = f.getvalue()
print(text.splitlines()[0])
print(len(text), "文字")
実行結果:
Help on built-in function len in module builtins:
111 文字
例外が起きても元に戻る(手で差し替えない理由)
import io
from contextlib import redirect_stdout
buf = io.StringIO()
try:
with redirect_stdout(buf):
print("A")
raise ValueError()
except ValueError:
pass
print("戻っている / bufの中身:", repr(buf.getvalue()))
実行結果:
戻っている / bufの中身: 'A\n'
withを抜けると、例外で抜けた場合でもsys.stdoutは元に戻ります。次のように手で差し替える書き方は、途中で例外が起きるとsys.stdout = oldまで到達せず、以降の出力がすべて消える原因になります。
import sys, io
buf = io.StringIO()
old = sys.stdout
sys.stdout = buf
print("捕まえた")
sys.stdout = old # 例外が起きるとここに到達しない
入れ子にしても正しく戻る
import io
from contextlib import redirect_stdout
a, b = io.StringIO(), io.StringIO()
with redirect_stdout(a):
print("外側")
with redirect_stdout(b):
print("内側")
print("外側に戻る")
print(repr(a.getvalue()), repr(b.getvalue()))
実行結果:
'外側\n外側に戻る\n' '内側\n'
内側のwithを抜けると、1つ外側の差し替え先に戻ります。
ファイルへ書き出す・出力を捨てる
from contextlib import redirect_stdout
with open("out.txt", "w", encoding="utf-8") as f:
with redirect_stdout(f):
print("ファイルへ")
print(repr(open("out.txt", encoding="utf-8").read()))
実行結果:
'ファイルへ\n'
渡せるのはwrite()を持つオブジェクトです。ファイル、io.StringIO、sys.stderrのほか、write()を実装した自作クラスでも構いません。
ライブラリが出す大量のメッセージを黙らせたいときは、書き込んだ内容が捨てられるos.devnullを使います。WindowsでもmacOS・Linuxでも同じ書き方で動きます。
import os
from contextlib import redirect_stdout
with open(os.devnull, "w") as f, redirect_stdout(f):
print("この行は表示されない")
print("ここは表示される")
実行結果:
ここは表示される
redirect_stderr:エラー出力も一緒に取り込む
import io, sys
from contextlib import redirect_stdout, redirect_stderr
buf = io.StringIO()
with redirect_stdout(buf), redirect_stderr(buf):
print("標準出力")
print("エラー出力", file=sys.stderr)
print(repr(buf.getvalue()))
実行結果:
'標準出力\nエラー出力\n'
redirect_stderr()の使い方はredirect_stdout()と同じです。同じStringIOを両方に渡せば、出力された順に1つの文字列にまとまります。
redirect_stdoutで捕まらない出力
ここが一番つまずきやすい点です。redirect_stdout()はPythonの変数sys.stdoutを差し替えるだけなので、それを経由しない出力は取り込めません。
os.system()とsubprocessの出力
import io, os, subprocess, sys
from contextlib import redirect_stdout
buf = io.StringIO()
with redirect_stdout(buf):
print("printの出力")
sys.stdout.write("writeの出力\n")
os.system("echo os.systemの出力")
subprocess.run(["echo", "subprocessの出力"])
print("bufの中身:", repr(buf.getvalue()))
実行結果:
os.systemの出力
subprocessの出力
bufの中身: 'printの出力\nwriteの出力\n'
外部コマンドの出力は画面にそのまま出て、bufには入りませんでした。公式ドキュメントにも「サブプロセスの出力には効果がない」と書かれています。外部コマンドの出力が欲しいなら、subprocess.run(..., capture_output=True, text=True)を使います。詳しくは「Python subprocess.run()とは?外部コマンドを実行する方法」で解説しています。
loggingの出力(redirect_stderrで取れない)
import io, logging, sys
from contextlib import redirect_stderr
logging.basicConfig(level=logging.INFO)
log = logging.getLogger("app")
buf = io.StringIO()
with redirect_stderr(buf):
log.warning("ログの出力")
print("print(file=sys.stderr)の出力", file=sys.stderr)
print("bufの中身:", repr(buf.getvalue()))
実行結果:
WARNING:app:ログの出力
bufの中身: 'print(file=sys.stderr)の出力\n'
logging.basicConfig()が作るハンドラーは、作られた時点のsys.stderrを覚えています。そのため、あとからsys.stderrを差し替えても、ログは元の画面に出ます。ログを取り込みたいなら、logging.StreamHandler(buf)のように取り込み先を指定したハンドラーを追加するほうが確実です。print()のように呼び出すたびにsys.stdoutを見に行く出力だけが対象、と覚えておくと判断しやすくなります。
別スレッドの出力(巻き込まれる)
import io, threading, time
from contextlib import redirect_stdout
def worker():
for i in range(3):
print(f"別スレッド {i}")
time.sleep( 0.01)
t = threading.Thread(target=worker)
buf = io.StringIO()
t.start()
with redirect_stdout(buf):
time.sleep( 0.05)
t.join()
print("bufの中身:", repr(buf.getvalue()))
実行結果:
別スレッド 0
bufの中身: '別スレッド 1\n別スレッド 2\n'
sys.stdoutは全スレッドで共有されているので、withの間に別スレッドが出した出力まで取り込まれました。公式ドキュメントも、この全体への副作用があるため、ライブラリのコードやほとんどのマルチスレッドのアプリには向かないと注意しています。asyncioで同時に動くタスクの出力も同じ理由で巻き込まれます。
C拡張や外部コマンドも含めて全部取りたい場合
OSレベルの標準出力(ファイルディスクリプタ1番)ごと差し替えれば、os.system()の出力も取り込めます。
import os, sys, tempfile
def run_and_capture_fd1(func):
sys.stdout.flush()
saved = os.dup(1) # 元の標準出力(fd 1)を退避
with tempfile.TemporaryFile() as tmp:
os.dup2(tmp.fileno(), 1) # fd 1 を一時ファイルへ向ける
try:
func()
sys.stdout.flush()
finally:
os.dup2(saved, 1) # 必ず戻す
os.close(saved)
tmp.seek(0)
return tmp.read().decode()
out = run_and_capture_fd1(lambda: (print("print", flush=True), os.system("echo os.system")))
print("取得:", repr(out))
実行結果:
取得: 'print\nos.system\n'
print()の内容はバッファにたまるため、flush=Trueを付けないと順番が入れ替わることがあります。プロセス全体に影響する操作なので、必要な場面に限って使ってください。
まとめ:何で取り込めるか
| 出力の種類 | redirect_stdout / redirect_stderr | 代わりの方法 |
|---|---|---|
print()、sys.stdout.write() |
取り込める | – |
help()など、画面に出すだけの関数 |
取り込める | – |
os.system()、subprocess |
取り込めない | subprocess.run(capture_output=True) |
logging.basicConfig()のログ |
取り込めない(設定時の出力先を保持) | 取り込み先を指定したハンドラーを追加 |
| C拡張が直接書く出力 | 取り込めない | ファイルディスクリプタごと差し替える |
別スレッドのprint() |
意図せず巻き込む | スレッドでは使わない |
実践例:printする関数をテストする
import io
from contextlib import redirect_stdout
def report(items):
print(f"件数: {len(items)}")
for i in items:
print(f"- {i}")
buf = io.StringIO()
with redirect_stdout(buf):
report(["A", "B"])
assert buf.getvalue() == "件数: 2\n- A\n- B\n"
print("検証OK")
実行結果:
検証OK
戻り値がなくprint()するだけの関数も、書き換えずに表示内容を検証できます。pytestを使っているなら、標準出力を取り込む仕組み(capsysフィクスチャ)が用意されているので、そちらのほうが簡単です(pytest公式:How to capture stdout/stderr output)。
新しく書くコードなら、「文字列を作る関数」と「表示する関数」を分けると、リダイレクトなしでテストできます。redirect_stdout()が役立つのは、自分では変更できない既存コードや外部ライブラリが相手のときです。
def format_report(items) -> str:
lines = [f"件数: {len(items)}"] + [f"- {i}" for i in items]
return "\n".join(lines)
def report(items) -> None:
print(format_report(items))
よくある質問
Q. redirect_stdoutで取り込んだ内容を文字列にするには?
io.StringIO()を渡し、with redirect_stdout(io.StringIO()) as f: のように受け取ってから、withを抜けたあとにf.getvalue()を呼びます。改行もそのまま含まれます。
Q. os.system()やsubprocessの出力が取り込めないのはなぜですか?
redirect_stdoutはPythonの変数sys.stdoutを差し替えるだけで、OSレベルの標準出力は変えないためです。外部コマンドの出力はsubprocess.run(capture_output=True, text=True)で受け取ってください。
Q. loggingの出力をredirect_stderrで取り込めないのはなぜですか?
logging.basicConfig()などで作られたハンドラーは、作成時点のsys.stderrを保持しているためです。取り込みたい場合は、logging.StreamHandler(バッファ)のように出力先を指定したハンドラーを追加します。
Q. マルチスレッドやasyncioで使ってもよいですか?
おすすめしません。sys.stdoutはプロセス全体で共有されているため、withの間にほかのスレッドやタスクが出した出力まで取り込んでしまいます。公式ドキュメントでも、ほとんどのマルチスレッドのアプリには向かないとされています。
redirect_stdoutのまとめ
with redirect_stdout(io.StringIO()) as f:で、print()の出力をf.getvalue()で受け取れるwithを抜けると、例外が起きてもsys.stdoutは元に戻る(手で差し替えない)- ファイルにも書き出せる。捨てるなら
os.devnull - エラー出力は
redirect_stderr()。同じバッファを渡せば1つにまとまる os.system()・subprocess・設定済みのlogging・C拡張の出力は取り込めないsys.stdoutは全スレッド共有なので、マルチスレッドでは使わない








