[IPython-user] Modifying stdout

Dan Yamins dyamins@gmail....
Sun Feb 8 11:43:05 CST 2009


I'd like to redirect stdout for my own custom purposes while in an ipython
session.  To do this, I would like to issue the command:

     >  sys.stdout = multicaster(,'LogFile.txt', sys.__stdout__)

before going on do my business.    The multicaster class (the code of which
I provide below after this short explanation) is used to both log stdout
output to a logfile ('Log.txt' in the example above) as _well_ as print to
the screen.  Basically when multicaster does is create a new object whose
"write" method is like that of sys.__stdout__ but also includes writing to
the log file.

When I do this at a regular python interpreter, it works fine as far as I
can tell.   However, in ipython it wrecks havoc on ipython's interactive
before:  the up, back, right, and left arrow keys produce output ('[[A' or
the like) instead of their usual functions, the interactive warning after
typing "quit()" fails, etc....   Before getting it to act normally, I have
to issue the command:

    > sys.stdout = sys.__stdout__

and once I do this, all is normal again (though of course I've lost my
special logging feature).

It seems to me that the reason this is happening is probably that ipython
has already replaced sys.stdout with an object having some special methods
to achieve some of ipython's special interactive functionality, and my
Multicaster class definition is overwriting those methods.  (since after all
I'm not subclassing anything, the object I create just has one "write"
method.)   So I have two questions:

1) Is this explanation basically right? If so, how do I properly "subclass"
ipython's object to simply modify the write method without killing the other

2) If this explanation is not basically right, what is the reason, and how
do I get around it?


class multicaster():
    def __init__(self,filename,OldObject,New=False):
        self.file = filename
        self.old = OldObject
        if New:
            F = open(filename,'w')

            F.write('STARTING LOG: ' + time.strftime('%c %Z') + '\n')


    def write(self,s):
        F = open(self.file,'a')
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://lists.ipython.scipy.org/pipermail/ipython-user/attachments/20090208/9eaa4b38/attachment.html 

More information about the IPython-user mailing list