Pus*_*ade 4 c python swig python-c-extension
我写了一个简单的C模块,使用printf打印到stdout.
// sample.c
func_print()
{
printf("Hello World!\n");
}
Run Code Online (Sandbox Code Playgroud)
后来,我使用了这个包装器,SWIG所以我也可以func_print在我的python程序中使用它.在这个程序中,我已将stdout重定向到textctrl小部件.print正如预期的那样,我在textctrl小部件中正确打印的任何东西都能正确打印.
# sample.py
...
sys.stdout = textctrl # textctrl is a TextCtrl widget (wxPython).
print 'Hello from Python!' # prints in the textctrl widget, as expected.
Run Code Online (Sandbox Code Playgroud)
但是,当我调用C函数func_print()(来自sample.py)时,它会打印到终端而不是textctrl小部件.
func_print() # [Problem] prints to the terminal window, instead of the textctrl widget.
Run Code Online (Sandbox Code Playgroud)
不知何故,似乎stdoutC模块中的for函数没有按预期重定向.请帮我解决这个问题.谢谢.
您的问题是sys.stdoutPython对象,而不是实际的C流或文件描述符.从sys.stdout文档:
(更改这些对象不会影响os模块中os.popen(),os.system()或exec*()系列函数执行的标准I/O进程流.)
您的C代码与生成的进程没有什么不同os.system,因为它只能访问传统的Unix文件描述符以进行输出,而不是Python对象.(好吧,无论如何,不是没有一些额外的工作.)
如果您只想将系统级别的stdout重定向到另一个文件或套接字,请参阅os.dup2.
但是如果你真的想从C发送输出到Python对象,请参阅从C调用Python函数.