How to "catch" c printf in python using ctypes?

I hope this is trivial, and I just did not find it in the textbooks. I am writing python code that "controls" c code, since I am running c code with ctypes from python. Now I want to catch printfs to process data that is output using c code. Any idea how to do this?

thank

+5
source share
2 answers

You can intercept stdoutbefore writing from your code C, and then process the output value.

import sys
import StringIO

buffer = StringIO.StringIO()

# redirect stdout to a buffer
sys.stdout = buffer

# call the c code with ctypes
# process the buffer

# recover the old stdout
sys.stdout = sys.__stdout__

C, printf - , .

, , byref a c_char_p, C, , Python. ( ctypes free).

+2

printf , stdout. , C, C stdout , Python.

0

All Articles