[How to change redirect stderr?]

Fredrik Lundh fredrik at pythonware.com
Fri Mar 10 17:43:10 CET 2006

"Moretti" wrote:

> I would like to be able to change the standard error path.

(I'm not sure path is the right word here, really, but never mind...)

> How can I do this in a script if I want to send error messages to /dev/null
> by example ?

if you're talking about things that Python prints to stderr, all you need
to do is to replace sys.stderr with something more suitable:

    import sys
    sys.stderr = open("/dev/null", "w")

or, more portable:

    class NullDevice:
        def write(self, s):

    sys.stderr = NullDevice()

if you want to redirect both things printed via sys.stderr and things
printed to stderr at the C level, you need to redirect the STDERR file
handle.  here's one way to do that:

    import os, sys

    err = open('/dev/null', 'a+', 0)
    os.dup2(err.fileno(), sys.stderr.fileno())

hope this helps!


More information about the Python-list mailing list