A class to duplicate an output stream to stdout/err. This works in a manner very similar to the Unix 'tee' command. When the object is closed or deleted, it closes the original file given to it for duplication.
| 96 | stderr = IOStream(sys.stderr, fallback=devnull) |
| 97 | |
| 98 | class Tee(object): |
| 99 | """A class to duplicate an output stream to stdout/err. |
| 100 | |
| 101 | This works in a manner very similar to the Unix 'tee' command. |
| 102 | |
| 103 | When the object is closed or deleted, it closes the original file given to |
| 104 | it for duplication. |
| 105 | """ |
| 106 | # Inspired by: |
| 107 | # http://mail.python.org/pipermail/python-list/2007-May/442737.html |
| 108 | |
| 109 | def __init__(self, file_or_name, mode="w", channel='stdout'): |
| 110 | """Construct a new Tee object. |
| 111 | |
| 112 | Parameters |
| 113 | ---------- |
| 114 | file_or_name : filename or open filehandle (writable) |
| 115 | File that will be duplicated |
| 116 | |
| 117 | mode : optional, valid mode for open(). |
| 118 | If a filename was give, open with this mode. |
| 119 | |
| 120 | channel : str, one of ['stdout', 'stderr'] |
| 121 | """ |
| 122 | if channel not in ['stdout', 'stderr']: |
| 123 | raise ValueError('Invalid channel spec %s' % channel) |
| 124 | |
| 125 | if hasattr(file_or_name, 'write') and hasattr(file_or_name, 'seek'): |
| 126 | self.file = file_or_name |
| 127 | else: |
| 128 | self.file = open(file_or_name, mode) |
| 129 | self.channel = channel |
| 130 | self.ostream = getattr(sys, channel) |
| 131 | setattr(sys, channel, self) |
| 132 | self._closed = False |
| 133 | |
| 134 | def close(self): |
| 135 | """Close the file and restore the channel.""" |
| 136 | self.flush() |
| 137 | setattr(sys, self.channel, self.ostream) |
| 138 | self.file.close() |
| 139 | self._closed = True |
| 140 | |
| 141 | def write(self, data): |
| 142 | """Write data to both channels.""" |
| 143 | self.file.write(data) |
| 144 | self.ostream.write(data) |
| 145 | self.ostream.flush() |
| 146 | |
| 147 | def flush(self): |
| 148 | """Flush both channels.""" |
| 149 | self.file.flush() |
| 150 | self.ostream.flush() |
| 151 | |
| 152 | def __del__(self): |
| 153 | if not self._closed: |
| 154 | self.close() |
| 155 |
no outgoing calls