Skip to content

Commit 8c47a4a

Browse files
committed
Fixed error where binary data was crashing getvalue. Added accessor methods for retrieving StdSim contents as bytes.
1 parent b99c094 commit 8c47a4a

File tree

1 file changed

+27
-13
lines changed

1 file changed

+27
-13
lines changed

cmd2/utils.py

Lines changed: 27 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -272,31 +272,45 @@ def __init__(self, inner_stream, echo: bool = False) -> None:
272272
self.buffer = self.ByteBuf(inner_stream, echo)
273273
self.inner_stream = inner_stream
274274

275-
def write(self, s: str) -> None:
276-
"""Add str to internal bytes buffer and if echo is True, echo contents to inner stream."""
275+
def write(self, s: str, encoding: str = 'utf-8') -> None:
276+
"""
277+
Add str to internal bytes buffer and if echo is True, echo contents to inner stream.
278+
:param: s: string to write
279+
:param encoding: how to encode the string (defaults to utf-8)
280+
"""
277281
if not isinstance(s, str):
278282
raise TypeError('write() argument must be str, not {}'.format(type(s)))
279-
b = s.encode()
283+
b = s.encode(encoding=encoding)
280284
self.buffer.write(b)
281285

282-
def getvalue(self) -> str:
283-
"""Get the internal contents as a str.
284-
285-
:return string from the internal contents
286+
def getvalue(self, encoding: str = 'utf-8') -> str:
287+
"""
288+
Get the internal contents as a str
289+
:param encoding: how to decode the bytes (defaults to utf-8)
286290
"""
287-
return self.buffer.byte_buf.decode()
291+
return self.buffer.byte_buf.decode(encoding=encoding, errors='replace')
288292

289-
def read(self) -> str:
290-
"""Read from the internal contents as a str and then clear them out.
293+
def getbytes(self) -> bytes:
294+
"""Get the internal contents as bytes"""
295+
return self.buffer.byte_buf
291296

292-
:return: string from the internal contents
297+
def read(self, encoding: str = 'utf-8') -> str:
293298
"""
294-
result = self.getvalue()
299+
Read from the internal contents as a str and then clear them out
300+
:param encoding: how to decode the bytes (defaults to utf-8)
301+
"""
302+
result = self.getvalue(encoding)
303+
self.clear()
304+
return result
305+
306+
def readbytes(self) -> bytes:
307+
"""Read from the internal contents as bytes and then clear them out"""
308+
result = self.getbytes()
295309
self.clear()
296310
return result
297311

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

Comments
 (0)