From 5c72506135c17455e477b47855e5b18c88cb9410 Mon Sep 17 00:00:00 2001 From: Wirawan Purwanto Date: Mon, 14 May 2012 15:48:43 -0400 Subject: [PATCH] * New module: wpylib.file.tee * Added class tee_output for splitting text output to multiple destinations. --- file/tee.py | 62 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 file/tee.py diff --git a/file/tee.py b/file/tee.py new file mode 100644 index 0000000..74c2c7b --- /dev/null +++ b/file/tee.py @@ -0,0 +1,62 @@ +# +# wpylib.file.tee module +# File-manipulation utilities: tee output splitter +# +# Wirawan Purwanto +# Created: 20120514 +# +# Routines put here are commonly used in my own scripts. +# They are not necessarily suitable for general-purpose uses; evaluate +# your needs and see if they can them as well. +# +# +""" +wpylib.file.tee module +File-manipulation utilities: tee output splitter + +This module is part of wpylib project. +""" + +class tee_output(object): + """ + Tee class for output file streams. + Supports file-like objects and auto-opened files (if the argument + is a string). + + See also: http://shallowsky.com/blog/programming/python-tee.html + """ + def __init__(self, *files, **opts): + fd = [] + auto_close = [] + mode = opts.get("mode", "w") + for f in files: + if isinstance(f, basestring): + F = open(f, mode=mode) + fd.append(F) + auto_close.append(True) + else: + fd.append(f) + auto_close.append(False) + self.fd = fd + self.auto_close = auto_close + + def __del__(self): + self.close() + + def close(self): + for (auto,f) in zip(self.auto_close,self.fd): + if auto: + f.close() + else: + f.flush() + self.fd = [] + self.auto_close = [] + + def write(self, s): + for f in self.fd: + f.write(s) + + def flush(self): + for f in self.fd: + f.flush() +