In python, how to capture the stdout from a c++ shared library to a variable

前端 未结 7 1883
别那么骄傲
别那么骄傲 2020-11-30 04:52

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.

相关标签:
7条回答
  • 2020-11-30 05:41

    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')
    
    0 讨论(0)
提交回复
热议问题