Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
29 commits
Select commit Hold shift + click to select a range
4c18d3b
gh-122622: Add PyREPL pre-execution hook
edvilme Sep 9, 2026
b988e6f
Add empty pre_execution_hook for feature detection
edvilme Sep 9, 2026
7d9ddbf
Update tests to verify no interference
edvilme Sep 9, 2026
ad17396
📜🤖 Added by blurb_it.
blurb-it[bot] Sep 9, 2026
0ef602c
Update NEWS
edvilme Sep 9, 2026
8ede9b2
Address feedback
edvilme Sep 18, 2026
6d7dfe0
Address feedback
edvilme Sep 19, 2026
d45c1d3
Merge branch 'main' into pyrepl-hook
edvilme Sep 19, 2026
e1186d5
Show tracebakcs
edvilme Sep 21, 2026
f615af2
Add tests to make sure hook runs before exception
edvilme Sep 23, 2026
f766b48
Update comment
edvilme Oct 13, 2026
a81c71a
Fix incorrect comment
edvilme Oct 13, 2026
a98d37a
Merge branch 'main' into pyrepl-hook
edvilme Oct 28, 2026
d948c28
Merge branch 'main' into pyrepl-hook
brettcannon Oct 29, 2026
ce55702
Strip final indent from submitted hook
edvilme Nov 3, 2026
8665769
Show traceback as a hook failure without modifying sys.last_*
edvilme Nov 3, 2026
b7e9986
Simplify comment to remove example
edvilme Nov 3, 2026
753ed83
Add tests for KeyboardInterrupt and SystemExit
edvilme Nov 3, 2026
d2a7a45
Add test for strip indentation
edvilme Nov 3, 2026
ac8d177
Remove weak return value test
edvilme Nov 3, 2026
e28071a
Add PTY test
edvilme Nov 3, 2026
d6cd848
Update tests
edvilme Nov 3, 2026
7be412f
Update News entry
edvilme Nov 17, 2026
0ea14cd
Do not call _strip_final_indent twice
edvilme Nov 17, 2026
8ea46f3
Rename to input_submitted_hook
edvilme Nov 17, 2026
c385c46
Added Exception clarification to comment
edvilme Nov 17, 2026
9d4fe71
Merge branch 'main' into pyrepl-hook
edvilme Nov 17, 2026
49cf4a6
Update tests
edvilme Nov 18, 2026
84bb0b6
Fix variable name
edvilme Nov 24, 2026
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
16 changes: 15 additions & 1 deletion Lib/_pyrepl/simple_interact.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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"<python-input-{input_n}>"
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()
Expand Down
34 changes: 34 additions & 0 deletions Lib/test/test_pyrepl/support.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import sys
from code import InteractiveConsole
from functools import partial
from typing import Iterable
Expand All @@ -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
Expand Down
53 changes: 53 additions & 0 deletions Lib/test/test_pyrepl/test_pyrepl.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@

from .support import (
FakeConsole,
INPUT_SUBMITTED_HOOK_MARKER,
ScreenEqualMixin,
handle_all_events,
handle_events_narrow_console,
Expand Down Expand Up @@ -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__'"
Expand Down
Original file line number Diff line number Diff line change
@@ -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.
Loading