Skip to content Skip to sidebar Skip to footer

Redirecting Stdout, Stderror To File While Stderr Still Prints To Screen

I would like stdout and stderr to be redirected to the same file, while stderr still writes to the screen. What's the most pythonic way to do this?

Solution 1:

I'm assuming you want to redirect the current script's stdout and stderr, not some subprocess you're running.

This doesn't sound like a very Pythonic thing to do in the first place, but if you need to, the Pythonic solution would be:

  • Redirect stdout to a file.
  • Redirect stderr to a custom file-like object that writes to the file and also writes to the real stderr.

Something like this:

class Tee(object):
    def __init__(self, f1, f2):
        self.f1, self.f2 = f1, f2
    def write(self, msg):
        self.f1.write(msg)
        self.f2.write(msg)

outfile = open('outfile', 'w')

sys.stdout = outfile
sys.stderr = Tee(sys.stderr, outfile)

Solution 2:

Your best bet is to use the python logging framework to send your messages to both places, instead of actually redirecting stdout / stderr. As a less-pythonic alternative, you could make a custom file-like object that's write method will write to both sys.__stdout__ and your file, and assign sys.stdout to your custom object. You would then do the same for stderr. Please see the documentation for the sys module

Post a Comment for "Redirecting Stdout, Stderror To File While Stderr Still Prints To Screen"