Created
July 14, 2011 19:58
-
-
Save cofi/1083302 to your computer and use it in GitHub Desktop.
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
import sys | |
import types | |
class Tee(object): | |
""" | |
Contextmanager for writing simulaniously to multiple files. | |
""" | |
def __init__(self, *args, **kwargs): | |
""" | |
args -- file names or open file-like objects | |
kwargs['mode'] -- mode for opening file names; see open. | |
""" | |
self.files = args | |
self.mode = kwargs.get('mode', 'w') | |
self.handles = list() | |
def _open(self, f): | |
""" | |
Open argument if it is a file name. | |
f -- file name or file like object. | |
""" | |
if isinstance(f, types.StringTypes): | |
return open(f, self.mode) | |
else: | |
return f | |
def __enter__(self): | |
return self.open_() | |
def __exit__(self, type, value, traceback): | |
self.close() | |
def write(self, s): | |
""" | |
Write `s' to all handles. | |
See file.write. | |
""" | |
for handle in self.handles: | |
handle.write(s) | |
def writelines(self, strings): | |
""" | |
Write `strings' to all handles. | |
See file.writelines. | |
""" | |
for handle in self.handles: | |
handle.writelines(strings) | |
def open_(self): | |
"""Open all files.""" | |
self.handles = map(self._open, self.files) | |
return self | |
def close(self): | |
"""Close all files.""" | |
for handle in self.handles: | |
if handle not in (sys.stderr, sys.stdout, sys.stdin): | |
handle.close() | |
@property | |
def closed(self): | |
"""Return if any file handle is closed.""" | |
return any(handle.closed for handle in self.handles) | |
def flush(self): | |
"""Flush all handles.""" | |
for handle in self.handles: | |
handle.flush() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment