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

Tatsujin tatsujin at despammed.com
Sun Dec 22 15:51:35 EST 2002


Peter Hansen wrote:
> Tatsujin wrote:
> 
>>Donn Cave wrote:
>>
>>>That isn't precisely the way to go.  The key point here is that unlike C++,
>>>Python doesn't care if stdout is subclass of the builtin file object type -
>>>doesn't make any difference at all.  So maybe it is indeed easier - you
>>>only need an object that supports the functions that stdout going to use.
>>>
>>>If you have the Python source, cStringIO does that (much more than you
>>>need, though.)
>>
>>Ah! So it's that easy?  (but then again, it's python we're talking here, no big
>>surprise  :-)
>>
>>Shouldn't be much trouble then, I suppose. Thanks a bunch!
> 
> 
> It can actually be as easy as this (or easier, I suppose):
> 
> class Logger:
>     def __init__(self, filename):
>         self.filename = filename
>     def write(self, data):
>         f = open(self.filename, 'a')
>         f.write(data)
>         f.close()
> 
> import sys
> sys.stdout = Logger('/var/log/myapp.log')
> 
> print 'This is a test'

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.


/André






More information about the Python-list mailing list