Pushpak Dagade
Pushpak Dagade

Reputation: 6450

problem redirecting stdout of C functions when imported in python

I wrote a simple C module which prints to stdout using printf.

// sample.c
func_print()
{
    printf("Hello World!\n");
}

Later, I made a wrapper around this using SWIG so that I could use func_print in my python program too. In this program, I have redirected the stdout to a textctrl widget. Anything I print using print prints correctly in the textctrl widget, as expected.

# sample.py
...
sys.stdout = textctrl          # textctrl is a TextCtrl widget (wxPython).
print 'Hello from Python!'     # prints in the textctrl widget, as expected.

However, when I call the C function func_print() (from sample.py), it prints to the terminal instead of the textctrl widget.

func_print()                   # [Problem] prints to the terminal window, instead of the textctrl widget.  

Somehow, it seems that the stdout for functions in the C module do not get redirected as expected. Please help me fix this. Thank you.

Upvotes: 4

Views: 1438

Answers (1)

Nemo
Nemo

Reputation: 71525

Your problem is that sys.stdout is a Python object, not an actual C stream or file descriptor. From the sys.stdout documentation:

(Changing these objects doesn’t affect the standard I/O streams of processes executed by os.popen(), os.system() or the exec*() family of functions in the os module.)

Your C code is not unlike a process spawned by os.system, in that it only has access to traditional Unix file descriptors for output, not Python objects. (Well, not without some extra work, anyway.)

If you just want to redirect stdout at the system level to another file or socket, see os.dup2.

But if you really want to send output to a Python object from C, see Calling Python Functions From C.

Upvotes: 5

Related Questions