diff --git a/Lib/_pyrepl/simple_interact.py b/Lib/_pyrepl/simple_interact.py index 5564c68e003c45..c1604cd7dba8ed 100644 --- a/Lib/_pyrepl/simple_interact.py +++ b/Lib/_pyrepl/simple_interact.py @@ -33,6 +33,11 @@ from .readline import _get_reader, multiline_input, append_history_file +# Called with submitted input before execution, except for REPL commands. +# Exceptions (not KeyboardInterrupt or SystemExit) raised in the hook are displayed but do not prevent execution. +input_submitted_hook = None + + _error: tuple[type[Exception], ...] | type[Exception] try: from .unix_console import _error @@ -150,8 +155,17 @@ def maybe_run_command(statement: str) -> bool: if maybe_run_command(statement): continue + statement = _strip_final_indent(statement) + + if input_submitted_hook is not None: + try: + input_submitted_hook(statement) + except Exception as exc: + console.write("Error in input_submitted_hook:\n") + console._excepthook(type(exc), exc, exc.__traceback__) + input_name = f"" - more = console.push(_strip_final_indent(statement), filename=input_name, _symbol="single") # type: ignore[call-arg] + more = console.push(statement, filename=input_name, _symbol="single") # type: ignore[call-arg] assert not more try: append_history_file() diff --git a/Lib/test/test_pyrepl/support.py b/Lib/test/test_pyrepl/support.py index c879a2f93b6313..f79de1e105f9c6 100644 --- a/Lib/test/test_pyrepl/support.py +++ b/Lib/test/test_pyrepl/support.py @@ -1,3 +1,4 @@ +import sys from code import InteractiveConsole from functools import partial from typing import Iterable @@ -10,6 +11,39 @@ from _pyrepl.utils import unbracket, ANSI_ESCAPE_SEQUENCE +INPUT_SUBMITTED_HOOK_MARKER = "\x1b]633;C\x07" +_LAST_EXCEPTION_ATTRIBUTES = ( + "last_exc", "last_type", "last_value", "last_traceback", +) + + +def report_submitted_input(source): + print(INPUT_SUBMITTED_HOOK_MARKER + repr(source), flush=True) + + +def fail_submitted_input(source): + raise RuntimeError("hook failed") + + +def last_exception_attributes(): + return { + name: getattr(sys, name) + for name in _LAST_EXCEPTION_ATTRIBUTES + if hasattr(sys, name) + } + + +def last_exception_attributes_preserved(previous): + return ( + len(previous) == len(_LAST_EXCEPTION_ATTRIBUTES) + and isinstance(previous["last_exc"], ZeroDivisionError) + and all( + hasattr(sys, name) and getattr(sys, name) is value + for name, value in previous.items() + ) + ) + + class ScreenEqualMixin: def assert_screen_equal( self, reader: ReadlineAlikeReader, expected: str, clean: bool = False diff --git a/Lib/test/test_pyrepl/test_pyrepl.py b/Lib/test/test_pyrepl/test_pyrepl.py index c11c759f559aff..f62f72c9b699a4 100644 --- a/Lib/test/test_pyrepl/test_pyrepl.py +++ b/Lib/test/test_pyrepl/test_pyrepl.py @@ -29,6 +29,7 @@ from .support import ( FakeConsole, + INPUT_SUBMITTED_HOOK_MARKER, ScreenEqualMixin, handle_all_events, handle_events_narrow_console, @@ -2112,6 +2113,58 @@ def setUp(self): self.addCleanup(patcher.stop) patcher.start() + def test_input_submitted_hook(self): + env = os.environ.copy() + env["PYTHON_COLORS"] = "0" + output, exit_code = self.run_repl( + [ + "from _pyrepl import simple_interact as si", + "from test.test_pyrepl import support", + "si.input_submitted_hook = support.report_submitted_input", + "if True:", + "print('block executed')", + "", + "exit", + ], + env=env, + skip=True, + ) + output = output.replace("\r\n", "\n") + self.assertEqual(exit_code, 0) + submitted_input = "if True:\n print('block executed')\n" + hook_output = f"{INPUT_SUBMITTED_HOOK_MARKER}{submitted_input!r}" + self.assertEqual(output.count(INPUT_SUBMITTED_HOOK_MARKER), 1) + self.assertIn(hook_output, output) + self.assertIn("block executed\n", output) + self.assertLess(output.index(hook_output), output.index("block executed\n")) + + def test_input_submitted_hook_exception(self): + env = make_clean_env() + env["NO_COLOR"] = "1" + output, exit_code = self.run_repl( + [ + "from _pyrepl import simple_interact as si", + "from test.test_pyrepl import support", + "print('initially unset:', not support.last_exception_attributes())", + "si.input_submitted_hook = support.fail_submitted_input", + "print('still unset:', not support.last_exception_attributes())", + "1 / 0", + "previous = support.last_exception_attributes()", + "print('last preserved:', support.last_exception_attributes_preserved(previous))", + "exit", + ], + env=env, + skip=True, + ) + output = output.replace("\r\n", "\n") + self.assertEqual(exit_code, 0) + self.assertEqual(output.count("Error in input_submitted_hook:\n"), 4) + self.assertEqual(output.count("RuntimeError: hook failed"), 4) + self.assertIn("initially unset: True\n", output) + self.assertIn("still unset: True\n", output) + self.assertIn("ZeroDivisionError: division by zero\n", output) + self.assertIn("last preserved: True\n", output) + @force_not_colorized def test_exposed_globals_in_repl(self): pre = "['__builtins__'" diff --git a/Misc/NEWS.d/next/Library/2026-09-09-23-15-03.gh-issue-122622.YfSSrl.rst b/Misc/NEWS.d/next/Library/2026-09-09-23-15-03.gh-issue-122622.YfSSrl.rst new file mode 100644 index 00000000000000..5d5d2a4eab0327 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2026-09-09-23-15-03.gh-issue-122622.YfSSrl.rst @@ -0,0 +1,3 @@ +Add an optional ``_pyrepl.simple_interact.input_submitted_hook`` callback +that runs after input is submitted and before it is executed, +allowing external tools to implement features such as shell integration.