For some other reasons, the c++ shared library I used outputs some texts to standard output. In python, I want to capture the output and save to a variable.
For anyone who came here from google to find how to suppress stderr/stdout output from shared library (dll), just as me, I post next simple context manager based on Adam's answer:
class SuppressStream(object):
def __init__(self, stream=sys.stderr):
self.orig_stream_fileno = stream.fileno()
def __enter__(self):
self.orig_stream_dup = os.dup(self.orig_stream_fileno)
self.devnull = open(os.devnull, 'w')
os.dup2(self.devnull.fileno(), self.orig_stream_fileno)
def __exit__(self, type, value, traceback):
os.close(self.orig_stream_fileno)
os.dup2(self.orig_stream_dup, self.orig_stream_fileno)
os.close(self.orig_stream_dup)
self.devnull.close()
Usage (adapted Adam's example):
import ctypes
import sys
print('Start')
liba = ctypes.cdll.LoadLibrary('libtest.so')
with SuppressStream(sys.stdout):
liba.hello() # Call into the shared library
print('End')