Created
December 7, 2011 20:35
-
-
Save astrofrog/1444524 to your computer and use it in GitHub Desktop.
How to redirect stdout and stderr to file for a block of code
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class log_to_file(): | |
| def __init__(self, filename): | |
| self.f = open(filename, 'wb') | |
| def __enter__(self): | |
| self.stdout = sys.stdout | |
| self.stderr = sys.stderr | |
| sys.stdout = self.f | |
| sys.stderr = self.f | |
| def __exit__(self, type, value, traceback): | |
| sys.stdout = self.stdout | |
| sys.stderr = self.stderr | |
| self.f.close() | |
| with log_to_file('log_1'): | |
| # do something | |
| with log_to_file('log_2'): | |
| # do something else |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This looks nice. A while back I did a variation on this theme to capture stdout and stderr into StringIO objects (see code below). Not clear if using the contextmanager really helped things out, but there you go. In your version maybe you could check if the passed argument is filelike and just use it directly in that case. This would allow logging into a StringIO object or whatever, not just a disk file.