Hello,

I was wondering how to go about having a redirect of stdout with Python take effect in a C extension. My python script redirects sys.stdout into a file handle created with open(...), but within the function in my compiled C-extension, any output (printf, puts, etc) is still given to the screen, and not the file object that the Python script invoking the extension is using.

Is there any good way to do this? The first thought in my head was to define a Python function that is passed a string and writes it to the file, and then pass that function into the C-extension as an argument. Then any output in C would be done via the passed-in function. Are there any proper ways of doing this?

Thanks!

I would try something like this

sys = PyImport_ImportModule( "sys");
s_out = PyObject_GetAttrString(sys, "stdout"); // new reference
result = PyObject_CallMethod(s_out, "write", "s", "your data goes here"); //new ref

that is to say, you execute sys.stdout.write("your data goes here") , but in C :). Don't forget to decref what must be decrefed. The pointer to sys can be computed only once, but if you intend to change sys.stdout, you should compute the attribute each time you want to print.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.