Skip to content

Instantly share code, notes, and snippets.

@excalamus
Forked from natedileas/redirect.py
Last active June 18, 2021 16:09
Show Gist options
  • Save excalamus/b40a6e1d5452cc2a2e3ba28b7a456730 to your computer and use it in GitHub Desktop.
Save excalamus/b40a6e1d5452cc2a2e3ba28b7a456730 to your computer and use it in GitHub Desktop.
c-level stdout redirection on windows
# Redirect stdout at every level to /dev/null
import os
import io
import sys
import ctypes
from contextlib import contextmanager
@contextmanager
def stdout_redirector(stream):
original_stdout_fd = sys.stdout.fileno()
saved_stdout_fd = os.dup(original_stdout_fd)
def _redirect_stdout(to_fd):
"""Redirect stdout to the given file descriptor."""
# Flush the C-level buffer stdout
ctypes.CDLL('api-ms-win-crt-stdio-l1-1-0').fflush(None)
# Flush and close sys.stdout - also closes the file descriptor (fd)
sys.stdout.close()
# Make original_stdout_fd point to to_fd
os.dup2(to_fd, original_stdout_fd)
# Create a new sys.stdout that points to the redirected (original) fd
sys.stdout = io.TextIOWrapper(os.fdopen(original_stdout_fd, 'wb'))
try:
devnull = open(os.devnull, 'w')
_redirect_stdout(devnull.fileno())
yield
_redirect_stdout(saved_stdout_fd)
except:
os.close(saved_stdout_fd)
print('About to redirect to devnull...')
with stdout_redirector(io.BytesIO()):
print('Python print statement')
ctypes.CDLL('api-ms-win-crt-stdio-l1-1-0').puts(b'Some noisy C function')
os.system('echo Even system echoes')
print('See? It ate everything. :)')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment