Created
December 30, 2020 15:25
-
-
Save kauplan/64c6f24187dd6f7602f289cd993f4146 to your computer and use it in GitHub Desktop.
[python] stdoutをStringIOで置き換える
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- 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