-1

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?

pythonic metaphor
  • 10,296
  • 18
  • 68
  • 110

2 Answers2

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)
abarnert
  • 354,177
  • 51
  • 601
  • 671
0

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

Community
  • 1
  • 1
ErlVolton
  • 6,714
  • 2
  • 15
  • 26
  • No, you still have `stderr` to write to the screen. (Not to mention `sys.__stdout__` and `sys.__stderr__`.) and of course you can always save the original `stdout` before redirecting it. – abarnert Oct 13 '14 at 19:17
  • He wants to redirect stderr as well. You're right about sys.stdout vs sys.__stdout__, I'll update my answer to include that – ErlVolton Oct 13 '14 at 19:22
  • Yes, he wants to redirect stderr so that it writes to a file and to real `stderr`. And there's absolutely nothing stopping him from doing so; I don't know why you think this will be a problem. Meanwhile, he doesn't want `stdout` to go to the screen, just to a file, so why are you explaining how to do that? – abarnert Oct 13 '14 at 19:38