Skip to content

Instantly share code, notes, and snippets.

@cofi
Created July 14, 2011 19:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cofi/1083302 to your computer and use it in GitHub Desktop.
Save cofi/1083302 to your computer and use it in GitHub Desktop.
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