views:

71

answers:

2

Hi there,

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

A: 

Well printf simply writes its output to whatever the stdout file pointer refers to. Im not sure how you're executing the C program, but it should be possible to redirect the C program's stdout to something that you can read in Python.

torak
+1  A: 

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).

the_void
The interception of 'stdout' is what I had in mind. But it does not work for me. The code does not change the output behavior.
Framester
I don't really understand what you mean by *the code does not change the output behaviour*. Providing a more detailed explanation of what you are trying to achieve and the problems you encounter with `stdout` redirection might give us a hint on how we could help you.
the_void
Sorry for not having made myself clear enough. I added the lines of code to intercept the 'stdout', but the 'printfs' of the c functions I call with ctypes in Python is still outputted in the terminal. I will add a more concrete description of my problem in the answer.
Framester