add a prefix to each line written to a file
| 54 | |
| 55 | # just used for logging purposes |
| 56 | class PrefixedFile: |
| 57 | "add a prefix to each line written to a file" |
| 58 | |
| 59 | def __init__(self, file, prefix): |
| 60 | self.file = file |
| 61 | self.prefix = prefix |
| 62 | self.on_newline = True |
| 63 | |
| 64 | def write(self, s: str): |
| 65 | if not s: |
| 66 | return |
| 67 | if self.on_newline: |
| 68 | s = self.prefix + s |
| 69 | ends_with_newline = s[-1] == "\n" |
| 70 | if ends_with_newline: |
| 71 | s = s[:-1] |
| 72 | s = s.replace("\n", f"\n{self.prefix}") |
| 73 | self.file.write(s) |
| 74 | if ends_with_newline: |
| 75 | self.file.write("\n") |
| 76 | self.on_newline = ends_with_newline |
| 77 | |
| 78 | def flush(self): |
| 79 | self.file.flush() |
| 80 | |
| 81 | |
| 82 | # used for logging and output capture |