Skip to content
Open
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
10 changes: 6 additions & 4 deletions Lib/_pyrepl/simple_interact.py
Original file line number Diff line number Diff line change
Expand Up @@ -159,18 +159,20 @@ 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:
r.do_cmd(("isearch-end", [""]))
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
Expand Down
33 changes: 33 additions & 0 deletions Lib/test/test_pyrepl/test_pyrepl.py
Original file line number Diff line number Diff line change
Expand Up @@ -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')
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Colorize :exc:`KeyboardInterrupt` and :exc:`MemoryError` messages displayed
during input handling in PyREPL. Patch by Bartosz Sławecki.
Loading