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?
Asked
Active
Viewed 737 times
-1
-
You mean within the current program, or for a subprocess? – abarnert Oct 13 '14 at 19:12
-
@abarnert yes, the current program, not a subprocess – pythonic metaphor Oct 13 '14 at 19:24
2 Answers
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 realstderr
.
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
-
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