stdout/err and C extentions

hg hg at nospam.org
Tue Jun 12 23:02:40 CEST 2007


Robert Bauck Hamar wrote:

> hg wrote:
> 
>> 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, thanks,
>> 
>> I understand that sys.stdout and stdout of an extention are two different
>> entities ... correct ?
> 
> Yes. Python's sys.stdout and C's stdout are both objects wrapping the call
> os.write(1, "string") in Python and write(1, "string", strlen("string"))
> in C, or some other function on platforms using other mechanisms for
> output.
> 
> In that way sys.stdout in Python and stdout in C will be portable to many
> more systems.
> 
> --
> Robert Bauck Hamar


Thanks Robert.

hg




More information about the Python-list mailing list