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