开发者

problem redirecting stdout of C functions when imported in python

开发者 https://www.devze.com 2023-03-19 06:12 出处:网络
I wrote a simple C module which prints to stdout using printf. // sample.c func_print() { printf(\"Hello World!\\n\");

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. I开发者_如何转开发n 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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号