Created
March 30, 2023 18:08
-
-
Save surajRathi/9314a75619955ee195c27871181aed51 to your computer and use it in GitHub Desktop.
Blocks printing by remapping sys.stdout and/or sys.stderr.
This file contains 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
# 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