Skip to content

Instantly share code, notes, and snippets.

@mauicv
Created March 28, 2021 00:43
Show Gist options
  • Save mauicv/a0ccace42ccfb9491bdbc8ab7ede6538 to your computer and use it in GitHub Desktop.
Save mauicv/a0ccace42ccfb9491bdbc8ab7ede6538 to your computer and use it in GitHub Desktop.
[RedirectStream] Supress unwanted stdout or stderr output from external librarys #hack #stdout #stderr
# taken from https://github.com/bulletphysics/bullet3/issues/3131
import ctypes
import sys
import os
class RedirectStream(object):
@staticmethod
def _flush_c_stream(stream):
streamname = stream.name[1:-1]
libc = ctypes.CDLL(None)
libc.fflush(ctypes.c_void_p.in_dll(libc, streamname))
def __init__(self, stream=sys.stdout, file=os.devnull):
self.stream = stream
self.file = file
def __enter__(self):
self.stream.flush() # ensures python stream unaffected
self.fd = open(self.file, "w+")
self.dup_stream = os.dup(self.stream.fileno())
os.dup2(self.fd.fileno(), self.stream.fileno()) # replaces stream
def __exit__(self, type, value, traceback):
RedirectStream._flush_c_stream(self.stream) # empty C stream buffer
os.dup2(self.dup_stream, self.stream.fileno()) # restores stream
os.close(self.dup_stream)
self.fd.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment