Capturing print output from shared library called from python with ctypes module

后端 未结 2 1130
清歌不尽
清歌不尽 2020-12-30 12:47

I am working with a shared library that is being called through the ctypes module. I would like to redirect the stdout associated with this module to a variable or a file t

2条回答
  •  春和景丽
    2020-12-30 13:02

    Simplest example, because this question in google top.

    import os
    from ctypes import CDLL
    
    libc = CDLL(None)
    stdout = os.dup(1)
    silent = os.open(os.devnull, os.O_WRONLY)
    os.dup2(silent, 1)
    libc.printf(b"Hate this text")
    os.dup2(stdout, 1)
    

提交回复
热议问题