Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.rst
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ New features:


Fixes:
* #747: Do not crash when printing text that the terminal encoding cannot
represent
* #1057: Preserve the indentation of pasted code

Changes to dependencies:
Expand Down
10 changes: 10 additions & 0 deletions bpython/curtsiesfrontend/coderunner.py
Original file line number Diff line number Diff line change
Expand Up @@ -233,6 +233,16 @@ def __init__(
self._real_fileobj = real_fileobj

def write(self, s: str) -> str | None:
encoding = getattr(self._real_fileobj, "encoding", None)
if encoding:
# The text is only encoded when the screen is redrawn, outside of
# the user's code, where an encoding error crashes bpython. Apply
# the encoding and error handler of the real stream here instead,
# like the standard REPL does: with "strict" (stdout) the user's
# code gets a UnicodeEncodeError, with "backslashreplace" (stderr)
# the characters are escaped.
errors = getattr(self._real_fileobj, "errors", None) or "strict"
s = s.encode(encoding, errors).decode(encoding, errors)
self.on_write(s)
return self.coderunner.request_from_main_context(force_refresh=True)

Expand Down
25 changes: 25 additions & 0 deletions bpython/test/test_curtsies_coderunner.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import code
import io
import sys
import unittest
from unittest import mock
Expand Down Expand Up @@ -66,3 +67,27 @@ def assert_unicode(self, s):
def test_bytes(self):
out = FakeOutput(mock.Mock(), self.assert_unicode, None)
out.write("native string type")

def real_fileobj(self, errors):
return io.TextIOWrapper(io.BytesIO(), encoding="utf-8", errors=errors)

def test_encodable_text_is_written_unchanged(self):
written = []
out = FakeOutput(mock.Mock(), written.append, self.real_fileobj("strict"))
out.write("ok \u00e9 \u2713\n")
self.assertEqual(written, ["ok \u00e9 \u2713\n"])

def test_unencodable_text_raises_with_strict_errors(self):
written = []
out = FakeOutput(mock.Mock(), written.append, self.real_fileobj("strict"))
with self.assertRaises(UnicodeEncodeError):
out.write("\udcfc")
self.assertEqual(written, [])

def test_unencodable_text_is_escaped_with_backslashreplace(self):
written = []
out = FakeOutput(
mock.Mock(), written.append, self.real_fileobj("backslashreplace")
)
out.write("\udcfc\n")
self.assertEqual(written, ["\\udcfc\n"])
Loading