Skip to content

Instantly share code, notes, and snippets.

@korakot
Created February 19, 2024 09:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save korakot/79396e2ca298b06adb447a1019cdbe7a to your computer and use it in GitHub Desktop.
Save korakot/79396e2ca298b06adb447a1019cdbe7a to your computer and use it in GitHub Desktop.
Suppress stdout
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()
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