-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
ContextManagers: Add retrieve_stdout()
Fixes #544
- Loading branch information
Showing
2 changed files
with
44 additions
and
9 deletions.
There are no files selected for viewing
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,14 +1,42 @@ | ||
from contextlib import contextmanager | ||
from contextlib import contextmanager, closing | ||
import sys | ||
import os | ||
from io import StringIO | ||
|
||
This comment has been minimized.
Sorry, something went wrong. |
||
@contextmanager | ||
def replace_stdout(replacement): | ||
""" | ||
Replaces stdout with the replacement, yields back to the caller and then | ||
reverts everything back. | ||
""" | ||
_stdout = sys.stdout | ||
sys.stdout = replacement | ||
try: | ||
yield | ||
finally: | ||
sys.stdout = _stdout | ||
|
||
|
||
@contextmanager | ||
def suppress_stdout(): | ||
with open(os.devnull, "w") as devnull: | ||
old_stdout = sys.stdout | ||
sys.stdout = devnull | ||
try: | ||
yield | ||
finally: | ||
sys.stdout = old_stdout | ||
""" | ||
Suppresses everything going to stdout. | ||
""" | ||
with open(os.devnull, "w") as devnull, replace_stdout(devnull): | ||
yield | ||
|
||
|
||
@contextmanager | ||
def retrieve_stdout(): | ||
""" | ||
Yields a StringIO object from which one can read everything that was | ||
printed to stdout. (It won't be printed to the real stdout!) | ||
Example usage: | ||
with retrieve_stdout() as stdout: | ||
print("something") # Won't print to the console | ||
what_was_printed = stdout.getvalue() # Save the value | ||
""" | ||
with closing(StringIO()) as sio, replace_stdout(sio): | ||
yield sio |
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
Two new lines needed here