I hope this is trivial and I just didn't find it in the tutorials. I am writing python code that 'supervises' c code, aka I run the c code with ctypes from python. Now I want to 'catch' the c 'printfs' to process the data that is output by the c code. Any idea how one would do this?
Thanks
You could intercept stdout
before being written to from your C
code, 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__
However, it would be easier and nicer to pass a buffer to the C code, and instead of printf
-ing the output values you would write them in the provided buffer.
Or, better yet, you could pass byref
a c_char_p
, allocate memory for it inside the C
code, update the buffer with the output value then use the buffer in Python
. Don't forget to deallocate the memory (you should make a ctypes
wrapper for the free
function).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With