Skip to content

Instantly share code, notes, and snippets.

@michaelmendoza
Last active March 16, 2023 17:08
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 michaelmendoza/5be28ee699a794701be32ecc74284f68 to your computer and use it in GitHub Desktop.
Save michaelmendoza/5be28ee699a794701be32ecc74284f68 to your computer and use it in GitHub Desktop.
A contextmanager to block output from print()
from contextlib import contextmanager
import sys, os
@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
@contextmanager
def suppress_stdout_c(to=os.devnull):
'''
import os
with stdout_redirected(to=filename):
print("from Python")
os.system("echo non-Python applications are also supported")
'''
fd = sys.stdout.fileno()
##### assert that Python and C stdio write using the same file descriptor
####assert libc.fileno(ctypes.c_void_p.in_dll(libc, "stdout")) == fd == 1
def _redirect_stdout(to):
sys.stdout.close() # + implicit flush()
os.dup2(to.fileno(), fd) # fd writes to 'to' file
sys.stdout = os.fdopen(fd, 'w') # Python writes to fd
with os.fdopen(os.dup(fd), 'w') as old_stdout:
with open(to, 'w') as file:
_redirect_stdout(to=file)
try:
yield # allow code to be run with the redirected stdout
finally:
_redirect_stdout(to=old_stdout) # restore stdout.
# buffering and flags such as
# CLOEXEC may be different
from io import supress_stdout
print "You can see this"
with suppress_stdout():
print "You cannot see this"
print "And you can see this again"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment