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.
| 22 | |
| 23 | |
| 24 | class Tee: |
| 25 | """A class to duplicate an output stream to stdout/err. |
| 26 | |
| 27 | This works in a manner very similar to the Unix 'tee' command. |
| 28 | |
| 29 | When the object is closed or deleted, it closes the original file given to |
| 30 | it for duplication. |
| 31 | """ |
| 32 | # Inspired by: |
| 33 | # http://mail.python.org/pipermail/python-list/2007-May/442737.html |
| 34 | |
| 35 | def __init__(self, file_or_name: Union[str, StringIO], mode: str="w", channel: str='stdout'): |
| 36 | """Construct a new Tee object. |
| 37 | |
| 38 | Parameters |
| 39 | ---------- |
| 40 | file_or_name : filename or open filehandle (writable) |
| 41 | File that will be duplicated |
| 42 | mode : optional, valid mode for open(). |
| 43 | If a filename was give, open with this mode. |
| 44 | channel : str, one of ['stdout', 'stderr'] |
| 45 | """ |
| 46 | if channel not in ['stdout', 'stderr']: |
| 47 | raise ValueError('Invalid channel spec %s' % channel) |
| 48 | |
| 49 | if hasattr(file_or_name, 'write') and hasattr(file_or_name, 'seek'): |
| 50 | self.file = file_or_name |
| 51 | else: |
| 52 | encoding = None if "b" in mode else "utf-8" |
| 53 | self.file = open(file_or_name, mode, encoding=encoding) |
| 54 | self.channel = channel |
| 55 | self.ostream = getattr(sys, channel) |
| 56 | setattr(sys, channel, self) |
| 57 | self._closed = False |
| 58 | |
| 59 | def close(self): |
| 60 | """Close the file and restore the channel.""" |
| 61 | self.flush() |
| 62 | setattr(sys, self.channel, self.ostream) |
| 63 | self.file.close() |
| 64 | self._closed = True |
| 65 | |
| 66 | def write(self, data): |
| 67 | """Write data to both channels.""" |
| 68 | self.file.write(data) |
| 69 | self.ostream.write(data) |
| 70 | self.ostream.flush() |
| 71 | |
| 72 | def flush(self): |
| 73 | """Flush both channels.""" |
| 74 | self.file.flush() |
| 75 | self.ostream.flush() |
| 76 | |
| 77 | def __del__(self): |
| 78 | if not self._closed: |
| 79 | self.close() |
| 80 | |
| 81 | def isatty(self): |
no outgoing calls