stdout/err and C extentions

hg hg at nospam.org
Tue Jun 12 15:52:41 EDT 2007


Robert Bauck Hamar wrote:

> 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


Robert, thanks,

I understand that sys.stdout and stdout of an extention are two different
entities ... correct ?


hg





More information about the Python-list mailing list