Skip to content

Instantly share code, notes, and snippets.

@CodeByAidan
Created March 4, 2024 19:09
Show Gist options
  • Save CodeByAidan/ae0bed7a8f7eda6b4a3a4a5f44431053 to your computer and use it in GitHub Desktop.
Save CodeByAidan/ae0bed7a8f7eda6b4a3a4a5f44431053 to your computer and use it in GitHub Desktop.
A context manager that suppresses stdout and stderr using contextlib in Python.
import contextlib
from typing import Any, Generator
@contextlib.contextmanager
def suppress_stdout_stderr() -> Generator[None, Any, None]:
"""
A context manager that redirects stdout and stderr to /dev/null
"""
with open("/dev/null", "w", encoding="utf-8") as null:
with contextlib.redirect_stdout(null), contextlib.redirect_stderr(null):
yield
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment