Skip to content

Instantly share code, notes, and snippets.

@surajRathi
Created March 30, 2023 18:08
Show Gist options
  • Save surajRathi/9314a75619955ee195c27871181aed51 to your computer and use it in GitHub Desktop.
Save surajRathi/9314a75619955ee195c27871181aed51 to your computer and use it in GitHub Desktop.
Blocks printing by remapping sys.stdout and/or sys.stderr.
# Use this as a context manager,
# with NoPrint(stdout=True, stderr=False):
# code_to_run()
class NoPrint:
def __init__(self, stdout=True, stderr=False):
self.stdout = stdout
self.stderr = stderr
def __enter__(self):
if self.stdout:
sys.stdout = open(os.devnull, 'w')
if self.stderr:
sys.stderr = open(os.devnull, 'w')
def __exit__(self, exc_type, exc_val, exc_tb):
if self.stdout:
sys.stdout = sys.__stdout__
if self.stderr:
sys.stderr = sys.__stderr__
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment