Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
28 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
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_with_final_indent = _strip_final_indent(statement)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

More like without it

Mby just reassign in-place?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry, I am not sure I follow. You mean like not call _strip_final_indent for the value passed to the function?


if input_submitted_hook is not None:
try:
input_submitted_hook(statement_with_final_indent)
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_with_final_indent, filename=input_name, _symbol="single") # type: ignore[call-arg]
assert not more
try:
append_history_file()
Expand Down
95 changes: 95 additions & 0 deletions Lib/test/test_pyrepl/test_pyrepl.py
Original file line number Diff line number Diff line change
Expand Up @@ -2112,6 +2112,101 @@ def setUp(self):
self.addCleanup(patcher.stop)
patcher.start()

def test_input_submitted_hook(self):
env = os.environ.copy()
env["PYTHON_COLORS"] = "0"
marker = "\x1b]633;C\x07"
output, exit_code = self.run_repl(
[
"from _pyrepl import simple_interact as si",
f"def hook(source): print({marker!r} + repr(source), flush=True)",
"",
"si.input_submitted_hook = hook",
"print('single executed')",
"if True:",
"print('block executed')",
"",
"a b c",
"clear",
"exit",
],
env=env,
skip=True,
)
output = output.replace("\r\n", "\n")
self.assertEqual(exit_code, 0)
self.assertEqual(output.count(marker), 3)
for submitted_input, result in (
("print('single executed')", "single executed\n"),
("if True:\n print('block executed')\n", "block executed\n"),
("a b c", "SyntaxError: invalid syntax"),
):
with self.subTest(submitted_input=submitted_input):
hook_output = f"{marker}{submitted_input!r}"
self.assertIn(hook_output, output)
self.assertIn(result, output)
self.assertLess(output.index(hook_output), output.index(result))

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",
"def hook(statement): raise RuntimeError('hook failed')",
"",
"si.input_submitted_hook = hook",
"x = 1",
"print('executed:', x)",
"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"), 2
)
self.assertEqual(output.count("RuntimeError: hook failed"), 2)
self.assertIn("\nexecuted: 1\n", output)

def test_input_submitted_hook_exception_preserves_sys_last(self):
env = os.environ.copy()
env["PYTHON_COLORS"] = "0"
output, exit_code = self.run_repl(
[
"import sys",
"from _pyrepl import simple_interact as si",
"names = ('last_exc', 'last_type', 'last_value', 'last_traceback')",
"print('initially unset:', all(not hasattr(sys, name) for name in names))",
"def hook(statement):",
"if statement in ('x = 1', 'y = 2'):",
"raise RuntimeError('hook failed')",
"",
"si.input_submitted_hook = hook",
"x = 1",
"print('still unset:', all(not hasattr(sys, name) for name in names))",
"si.input_submitted_hook = None",
"1 / 0",
"previous = tuple(getattr(sys, name) for name in names)",
"si.input_submitted_hook = hook",
"y = 2",
"print('last preserved:', isinstance(previous[0], ZeroDivisionError), "
"all(getattr(sys, name) is value for name, value in zip(names, 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"), 2)
self.assertIn("initially unset: True\n", output)
self.assertIn("still unset: True\n", output)
self.assertIn("last preserved: True 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