[How to change redirect stderr?]

M

Moretti

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

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

Thanks
 
F

Fredrik Lundh

Moretti said:
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):
pass

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

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

hope this helps!

</F>
 
M

Moretti

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


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):
pass

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

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

hope this helps!

</F>

Thanks
It's exactly what I seek for.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top