[despammed] Re: redirect sys.stdout to C++ ?

André Jonsson tatsujin at despammed.com
Fri Dec 27 20:52:33 EST 2002


Tatsujin wrote:
> Gr8!
> I sorta figured that out for myself... though with a small variation:
> 
> import selfmademodule     // a module created by my application
> class Logger:
>     def __init__(self, source):
>         self.source=source
>     def write(self, data):
>         selfmademodule.logwrite(self.source, data)
> 
> import sys
> sys.stdout = Logger('stdout')
> sys.stderr = Logger('stderr')
> 
> This is because the final destination of the output is not known from 
> the python side of things.

I got this working quite well... except for one snag I'm having diffculty in 
understanding. It seems that only the first "output" has a trailing newline 
character. This screws up the buffering in my application and I am unable to handle it.

A small example. If I write:

    >>> print '1'

I get these calls back to my application:

    logwrite("1")
    logwrite("\n")

It seem to split it up into two calls, but this is fine by me as I buffer the data 
and flushes it on newline.

But if I then, in the same session, again type:

    >>> print '1'

This time all that is called to my application is:

    logwrite("1")

...hm?

My application get these calls solely from the above callback of the over-ridden 
write() method. I've over-ridden all methods that a file object has, but they never 
seem to be called by the interactive shell.

Also this is not limited to just the 'print' command, also just forcing an error 
produces the same effect, the newline character is missing the second attempt.

The strange thing is that the behaviour is diffrent from the first outputs to the 
following ones. Does anyone know why it is this way?

/André






More information about the Python-list mailing list