Skip to content

Instantly share code, notes, and snippets.

@Alexhuszagh
Created March 7, 2018 01:11
Show Gist options
  • Save Alexhuszagh/e49b25aca79d737ad83a4a6fe9bf0e17 to your computer and use it in GitHub Desktop.
Save Alexhuszagh/e49b25aca79d737ad83a4a6fe9bf0e17 to your computer and use it in GitHub Desktop.
Redirect stderr
import contextlib
@contextlib.contextmanager
def redirect_stderr():
'''Redirect stderr across processes temporarily.'''
stderr = None
try:
stderr = os.dup(sys.stderr.fileno())
with open(os.devnull, 'w') as devnull:
os.dup2(devnull.fileno(), sys.stderr.fileno())
yield
finally:
if stderr is not None:
os.dup2(stderr, sys.stderr.fileno())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment