Skip to content
Advertisement

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

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 that I can access in my program. However ctypes uses a separate stdout from sys.stdout.

I’ll demonstrate the problem I am having with libc. If anyone is copying and pasting the code they might have to change the filename on line 2.

JavaScript

Is there any way I can capture the stdout that is associated with the ctypes loaded shared library?

Advertisement

Answer

We can use os.dup2() and os.pipe() to replace the entire stdout file descriptor (fd 1) with a pipe we can read from ourselves. You can do the same thing with stderr (fd 2).

This example uses select.select() to see if the pipe (our fake stdout) has data waiting to be written, so we can print it safely without blocking execution of our script.

As we are completely replacing the stdout file descriptor for this process and any subprocesses, this example can even capture output from child processes.

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement