Created
February 19, 2024 09:27
-
-
Save korakot/79396e2ca298b06adb447a1019cdbe7a to your computer and use it in GitHub Desktop.
Suppress stdout
This file contains hidden or 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
import os | |
import sys | |
from contextlib import contextmanager | |
@contextmanager | |
def suppress_stdout(): | |
with open(os.devnull, 'w') as devnull: | |
original_stdout = sys.stdout | |
sys.stdout = devnull | |
try: | |
yield | |
finally: | |
sys.stdout = original_stdout | |
# Example usage | |
with suppress_stdout(): | |
# Call the function from the other library here | |
library_function() |
This file contains hidden or 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
import os | |
import sys | |
from functools import wraps | |
# Define the decorator | |
def no_out(func): | |
@wraps(func) | |
def wrapper(*args, **kwargs): | |
with open(os.devnull, 'w') as devnull: | |
original_stdout = sys.stdout | |
sys.stdout = devnull | |
try: | |
return func(*args, **kwargs) | |
finally: | |
sys.stdout = original_stdout | |
return wrapper | |
# Example usage of the decorator | |
@no_out | |
def library_function(): | |
# Function call that you want to suppress stdout for | |
print("This will not be printed to stdout") | |
library_function() # Calling this function will now suppress its stdout output |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment