redirect stdout

Fredrik Lundh fredrik at pythonware.com
Fri Apr 8 13:11:37 EDT 2005


Neal Becker wrote:

> I'd like to build a module that would redirect stdout to send it to a logging
> module.  I want to be able to use a python module that expects to print
> results using "print" or "sys.stdout.write()" and without modifying that
> module, be able to redirect it's stdout to a logger which will send the
> messages via datagrams to a server.

if you want to redirect sys.stdout, replace sys.stdout with an object that
does the redirection.  all it needs is a "write" method:

    import sys

    class myredirector:
        def write(self, x):
            sys.stderr.write("*** " + repr(x) + "\n")

    sys.stdout = myredirector()

    print "hello"
    sys.stdout.write("world")

prints

    *** 'hello'
    *** '\n'
    *** 'world'

</F> 






More information about the Python-list mailing list