stdout/err and C extentions

Robert Bauck Hamar roberth+news at ifi.uio.no
Tue Jun 12 15:45:22 EDT 2007


hg wrote:

> Hi,
> 
> I have the following
> 
> ********************* C extention  - redir.c
> 
> 
> #include "Python.h"
> 
> PyObject * test_redir_test(PyObject *self) {
>   fprintf(stdout, "Hello from an extention!\n");
>   Py_INCREF(Py_None);
>   return Py_None;
> }
> 
[...]
> *********************** python test script: test.py:
> import sys
> 
> 
> class My_Stdout:
>     def write(self, p_string):
>         l_file = open('res.txt','a')
>         l_file.write(p_string)
>         l_file.close
> 
> 
> sys.stdout = My_Stdout()
> 
> print 'toto'
> import test_redir
> 
> 
> 
> test_redir.test()
> 
> 
> 
> **************** Question:
>  
> print 'toto' does go to "res.txt" while "Hello from an extention!\n" goes
> to the console.
> 
> Any clue ?

There is no portable way to change the location of stdout during execution
of a program. If you want to print with whatever is sys.stdout from an
extension module, you should call sys.stdout's write method dynamically
from C.

-- 
Robert Bauck Hamar




More information about the Python-list mailing list