Swapping out sys.stdout globally

brueckd at tbye.com brueckd at tbye.com
Fri Mar 1 12:21:04 EST 2002


On 1 Mar 2002, Kevin Smith wrote:

> I am working on a command-line utility written in Python which daemonizes
> itself.  In the process of daemonizing, sys.stdout and sys.stderr are
> redirected to now file-like objects as follows:
>
> sys.stdout = NewFile()
> sys.stderr = NewFile()
>
> However, I have some logging routines in a separate package that already
> have their own references to sys.stdout and sys.stderr which are
> unaffected by this.  Is there a way to chonge where sys.stdout and
> sys.stderr print their output to and have this change affect all existing
> references?

Nope - there's nothing magical about sys.stdout/err - they're just
variables that reference objects. By rebinding them they lose knowledge of
what they referenced previously, just as with any other variable.

You need to rebind stdout/err as soon as your program starts, before any
other modules load. Then as the others load they'll refer to your
replacement objects.

-Dave





More information about the Python-list mailing list