Skip to content

Instantly share code, notes, and snippets.

@kauplan
Created December 30, 2020 15:25
Show Gist options
  • Save kauplan/64c6f24187dd6f7602f289cd993f4146 to your computer and use it in GitHub Desktop.
Save kauplan/64c6f24187dd6f7602f289cd993f4146 to your computer and use it in GitHub Desktop.
[python] stdoutをStringIOで置き換える
# -*- coding: utf-8 -*-
import sys
from io import StringIO
from contextlib import contextmanager
@contextmanager
def dummy_stdout():
sout = sys.stdout
sys.stdout = StringIO()
try:
yield sys.stdout
finally:
sys.stdout = sout
with dummy_stdout():
print("ABC")
output = sys.stdout.getvalue()
print(f"output={output!r}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment