Allows each thread to output to different File objects (with optional prefix). Based on https://stackoverflow.com/a/57996986
| 81 | |
| 82 | # used for logging and output capture |
| 83 | class OutputTee: |
| 84 | """ |
| 85 | Allows each thread to output to different File objects (with optional prefix). |
| 86 | Based on https://stackoverflow.com/a/57996986 |
| 87 | """ |
| 88 | |
| 89 | def __init__(self, default_file): |
| 90 | self.which_files = {} |
| 91 | self.default = default_file |
| 92 | |
| 93 | def set_outputs(self, files): |
| 94 | self.which_files[get_thread_id()] = files |
| 95 | |
| 96 | def write(self, message: str): |
| 97 | files = self.which_files.get(get_thread_id(), [self.default]) |
| 98 | for file in files: |
| 99 | try: |
| 100 | file.write(message) |
| 101 | except: # noqa: E722 |
| 102 | pass |
| 103 | |
| 104 | def flush(self): |
| 105 | "required for compatibility" |
| 106 | files = self.which_files.get(get_thread_id(), [self.default]) |
| 107 | for file in files: |
| 108 | try: |
| 109 | file.flush() |
| 110 | except: # noqa: E722 |
| 111 | pass |
| 112 | |
| 113 | |
| 114 | stdout = sys.stdout = OutputTee(real_stdout) |