Skip to content

Don't crash when printing text the terminal cannot encode - #1064

Merged
sebastinas merged 1 commit into
bpython:mainfrom
imeerkhurram:fix/print-unencodable-text
Dec 2, 2026
Merged

sebastinas merged 1 commit into
bpython:mainfrom
imeerkhurram:fix/print-unencodable-text

Conversation

@imeerkhurram

Copy link
Copy Markdown
Contributor

Fixes #747.

print('\udcfc') still ends bpython on current main (Python 3.12, UTF-8 terminal):

  File ".../bpython/curtsies.py", line 131, in process_event_and_paint
    scrolled = self.window.render_to_terminal(array, cursor_pos)
  File ".../curtsies/window.py", line 58, in write
    self.out_stream.write(msg)
UnicodeEncodeError: 'utf-8' codec can't encode character '\udcfc' in position 0: surrogates not allowed

and the terminal is left without a cursor. The standard REPL raises the same UnicodeEncodeError from the print() call and keeps running. print('\udcfc', file=sys.stderr) crashes bpython the same way, while the standard REPL prints \udcfc because stderr uses the backslashreplace error handler.

Cause

FakeOutput.write passes the string on unchanged. It is only encoded later, when curtsies writes the screen to the terminal from the main loop, so the error is raised outside of the user's code and nothing catches it.

Fix

As suggested in the issue discussion, the text is now encoded in the user's code path: FakeOutput.write encodes it with the encoding and error handler of the real stream it stands in for (sys.__stdout__ / sys.__stderr__) and decodes it back before passing it on.

  • stdout (strict): the UnicodeEncodeError is raised by the print() call, so it is shown as a normal traceback and bpython keeps running.
  • stderr (backslashreplace): the characters are escaped, as in the standard REPL.
  • Text that can be encoded comes back unchanged, and nothing changes when there is no real stream (as in the existing tests).

The traceback shows one extra frame for FakeOutput.write, since the error now comes from Python code instead of the C print().

Not covered here: an exception message that contains such a character (for example raise ValueError('\udcfc')) goes through the traceback formatter, not FakeOutput, and still crashes. I kept this PR to the print() case from the issue.

Tests

  • Added three tests to TestFakeOutput: encodable text is unchanged, a strict stream raises UnicodeEncodeError and writes nothing, a backslashreplace stream escapes the character. The last two fail on main.
  • Ran bpython in a pseudo-terminal: before the change print('\udcfc') exits with status 1. After it, the traceback is shown, and 1+1 on the next line still prints 2. print('\udcfc', file=sys.stderr) prints \udcfc.
  • pytest: 337 passed, 14 skipped, 3 xfailed.
  • ruff check, ruff format --check and codespell on the changed files pass. mypy reports the same single error as on main (numpy is not installed here).
  • Added a line to CHANGELOG.rst under 0.27 fixes.

FakeOutput passed the text on unchanged, so it was only encoded when
curtsies redrew the screen. print('\udcfc') then raised
UnicodeEncodeError in the main loop, which ended bpython and left the
terminal without a cursor.

Encode the text with the real stream's encoding and error handler in
FakeOutput.write instead. With the strict handler of stdout the user's
code gets the UnicodeEncodeError, as in the standard REPL, and with the
backslashreplace handler of stderr the characters are escaped.

Fixes bpython#747
@codecov

codecov Bot commented Dec 2, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 75.99%. Comparing base (1a919d3) to head (6394dc5).
⚠️ Report is 86 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #1064      +/-   ##
==========================================
- Coverage   76.51%   75.99%   -0.53%     
==========================================
  Files          62       60       -2     
  Lines        8308     8581     +273     
==========================================
+ Hits         6357     6521     +164     
- Misses       1951     2060     +109     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@sebastinas
sebastinas merged commit bcb9834 into bpython:main Dec 2, 2026
9 of 11 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Gracefully handle errors during print()

2 participants