@@ -268,35 +268,49 @@ def write(self, b: bytes) -> None:
268268 if self .echo :
269269 self .inner_stream .buffer .write (b )
270270
271- def __init__ (self , inner_stream , echo : bool = False ) -> None :
271+ def __init__ (self , inner_stream , echo : bool = False ,
272+ encoding : str = 'utf-8' , errors : str = 'replace' ) -> None :
273+ """
274+ Initializer
275+ :param inner_stream: the emulated stream
276+ :param echo: if True, then all input will be echoed to inner_stream
277+ :param encoding: codec for encoding/decoding strings (defaults to utf-8)
278+ :param errors: how to handle encoding/decoding errors (defaults to replace)
279+ """
272280 self .buffer = self .ByteBuf (inner_stream , echo )
273281 self .inner_stream = inner_stream
282+ self .encoding = encoding
283+ self .errors = errors
274284
275285 def write (self , s : str ) -> None :
276- """Add str to internal bytes buffer and if echo is True, echo contents to inner stream. """
286+ """Add str to internal bytes buffer and if echo is True, echo contents to inner stream"""
277287 if not isinstance (s , str ):
278288 raise TypeError ('write() argument must be str, not {}' .format (type (s )))
279- b = s .encode ()
289+ b = s .encode (encoding = self . encoding , errors = self . errors )
280290 self .buffer .write (b )
281291
282292 def getvalue (self ) -> str :
283- """Get the internal contents as a str.
293+ """Get the internal contents as a str"""
294+ return self .buffer .byte_buf .decode (encoding = self .encoding , errors = self .errors )
284295
285- :return string from the internal contents
286- """
287- return self .buffer .byte_buf . decode ()
296+ def getbytes ( self ) -> bytes :
297+ """Get the internal contents as bytes"""
298+ return self .buffer .byte_buf
288299
289300 def read (self ) -> str :
290- """Read from the internal contents as a str and then clear them out.
291-
292- :return: string from the internal contents
293- """
301+ """Read from the internal contents as a str and then clear them out"""
294302 result = self .getvalue ()
295303 self .clear ()
296304 return result
297305
306+ def readbytes (self ) -> bytes :
307+ """Read from the internal contents as bytes and then clear them out"""
308+ result = self .getbytes ()
309+ self .clear ()
310+ return result
311+
298312 def clear (self ) -> None :
299- """Clear the internal contents. """
313+ """Clear the internal contents"""
300314 self .buffer .byte_buf = b''
301315
302316 def __getattr__ (self , item : str ):
0 commit comments