Skip to content

Instantly share code, notes, and snippets.

@junetech
Forked from djsmith42/gist:3956189
Last active June 13, 2023 02:43
Show Gist options
  • Save junetech/b6b374ce5ca20c34feb18ad58399d027 to your computer and use it in GitHub Desktop.
Save junetech/b6b374ce5ca20c34feb18ad58399d027 to your computer and use it in GitHub Desktop.
Console output suppressor for Python code
"""http://thesmithfam.org/blog/2012/10/25/temporarily-suppress-console-output-in-python/
https://stackoverflow.com/questions/36956083/how-can-the-terminal-output-of-executables-run-by-python-functions-be-silenced-i
"""
import os
import sys
from contextlib import contextmanager
@contextmanager
def suppress_stdout():
"""
with suppress_stdout():
lines_you_want_to_suppress_python_stdouts()
"""
with open(os.devnull, "w") as devnull:
old_stdout = sys.stdout
sys.stdout = devnull
try:
yield
finally:
sys.stdout = old_stdout
@contextmanager
def suppress_cffi_out():
"""
with suppress_cffi_out():
lines_you_want_to_suppress_FFI_stdouts()
"""
devnull = os.open(os.devnull, os.O_WRONLY)
old_stdout = os.dup(1)
sys.stdout.flush()
os.dup2(devnull, 1)
os.close(devnull)
try:
yield
finally:
os.dup2(old_stdout, 1)
os.close(old_stdout)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment