Replacement for writable io.StringIO that behaves more like real file Unlike StringIO, provides a buffer attribute that holds the underlying binary data, allowing it to replace sys.stdout/sys.stderr in more contexts.
| 35 | |
| 36 | |
| 37 | class StdIOBuffer(io.TextIOWrapper): |
| 38 | '''Replacement for writable io.StringIO that behaves more like real file |
| 39 | |
| 40 | Unlike StringIO, provides a buffer attribute that holds the underlying |
| 41 | binary data, allowing it to replace sys.stdout/sys.stderr in more |
| 42 | contexts. |
| 43 | ''' |
| 44 | |
| 45 | def __init__(self, initial_value='', newline='\n'): |
| 46 | initial_value = initial_value.encode('utf-8') |
| 47 | super().__init__(io.BufferedWriter(io.BytesIO(initial_value)), |
| 48 | 'utf-8', newline=newline) |
| 49 | |
| 50 | def getvalue(self): |
| 51 | self.flush() |
| 52 | return self.buffer.raw.getvalue().decode('utf-8') |
| 53 | |
| 54 | |
| 55 | class StdStreamTest(unittest.TestCase): |
no outgoing calls