import iooutput = io.StringIO()output.write('First line.\n')print('Second line.', file=output)# Retrieve file contents -- this will be# 'First line.\nSecond line.\n'contents = output.getvalue()# Close object and discard memory buffer --# .getvalue() will now raise an exception.output.close()
Именованный буфер
from io import StringIOclassNamedStringIO(StringIO):def__init__(self,name,content): self.name = namesuper().__init__(content)named_stream =NamedStringIO("test_stream", "init content")