diff --git a/Lib/_pyrepl/simple_interact.py b/Lib/_pyrepl/simple_interact.py index 5564c68e003c45..09bddc385d77f3 100644 --- a/Lib/_pyrepl/simple_interact.py +++ b/Lib/_pyrepl/simple_interact.py @@ -159,7 +159,7 @@ def maybe_run_command(statement: str) -> bool: warnings.warn(f"failed to open the history file for writing: {e}") input_n += 1 - except KeyboardInterrupt: + except KeyboardInterrupt as exc: r = _get_reader() r.cmpltn_reset() if r.input_trans is r.isearch_trans: @@ -167,10 +167,12 @@ def maybe_run_command(statement: str) -> bool: r.pos = len(r.get_unicode()) r.invalidate_full() r.refresh() - console.write("\nKeyboardInterrupt\n") + console.write("\n") + console._excepthook(type(exc), exc, tb=None) # type: ignore[attr-defined] # hides traceback console.resetbuffer() - except MemoryError: - console.write("\nMemoryError\n") + except MemoryError as exc: + console.write("\n") + console._excepthook(type(exc), exc, tb=None) # type: ignore[attr-defined] # hides traceback console.resetbuffer() except SystemExit: raise diff --git a/Lib/test/test_pyrepl/test_pyrepl.py b/Lib/test/test_pyrepl/test_pyrepl.py index c11c759f559aff..e88ecdcec88738 100644 --- a/Lib/test/test_pyrepl/test_pyrepl.py +++ b/Lib/test/test_pyrepl/test_pyrepl.py @@ -2335,6 +2335,39 @@ def check(output, exitcode): output, exit_code = self.run_repl(commands, env=env) check(output, exit_code) + def test_keyboard_interrupt_color(self): + for color in (False, True): + with self.subTest(color=color): + env = os.environ.copy() + env["PYTHON_COLORS"] = str(int(color)) + output, exit_code = self.run_repl( + "unfinished\x03print(42)\nexit()\n", env=env, + ) + self.assertEqual(exit_code, 0) + error = "KeyboardInterrupt" + if color: + theme = get_theme(force_color=True).traceback + error = f"{theme.type}{error}{theme.reset}" + self.assertIn(f"\r\n{error}\r\n", output) + self.assertNotIn("Traceback", output) + self.assertIn("42\r\n", output) + + def test_keyboard_interrupt_preserves_last_exception(self): + commands = ( + "import sys\n" + "1/0\n" + "saved = sys.last_exc\n" + "unfinished\x03" + "print('preserved:', sys.last_exc is saved)\n" + "exit()\n" + ) + env = os.environ.copy() + env["PYTHON_COLORS"] = "0" + output, exit_code = self.run_repl(commands, env=env) + self.assertEqual(exit_code, 0) + self.assertIn("\r\nKeyboardInterrupt\r\n", output) + self.assertIn("preserved: True\r\n", output) + def test_not_wiping_history_file(self): # skip, if readline module is not available import_module('readline') diff --git a/Misc/NEWS.d/next/Library/2026-11-21-01-02-25.gh-issue-162340.4ts3ew.rst b/Misc/NEWS.d/next/Library/2026-11-21-01-02-25.gh-issue-162340.4ts3ew.rst new file mode 100644 index 00000000000000..5101809bc20b68 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2026-11-21-01-02-25.gh-issue-162340.4ts3ew.rst @@ -0,0 +1,2 @@ +Colorize :exc:`KeyboardInterrupt` and :exc:`MemoryError` messages displayed +during input handling in PyREPL. Patch by Bartosz Sławecki.