-
-
Notifications
You must be signed in to change notification settings - Fork 33.9k
gh-140287: Handle PYTHONSTARTUP script exceptions in the asyncio REPL
#140288
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
johnslavik
wants to merge
43
commits into
python:main
Choose a base branch
from
johnslavik:asyncio-repl-handle-python-startup
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+110
−3
Draft
Changes from all commits
Commits
Show all changes
43 commits
Select commit
Hold shift + click to select a range
faa22f4
Handle `PYTHONSTARTUP` script exceptions
johnslavik 5b3ad2c
Add blurb
johnslavik 00edac4
Use `console.showtraceback()` instead of `sys.excepthook()`
johnslavik e396622
Properly run asyncio REPL in REPL tests
johnslavik 4079074
Move comment to a better place
johnslavik 0440d0e
Add tests
johnslavik af6f657
Merge branch 'properly-run-asyncio-repl-in-repl-tests' into asyncio-r…
johnslavik 848638d
Merge branch 'main' into asyncio-repl-handle-python-startup
johnslavik d158dbf
Improve test structure
johnslavik 9355da7
Use `SHORT_TIMEOUT`
johnslavik 3dc4cac
Revert "Use `SHORT_TIMEOUT`"
johnslavik c786584
Force no colorization
johnslavik b76db67
Linecache doesn't matter and shouldn't break tests
johnslavik cad1748
Don't rely on line numbering on Windows...
johnslavik d114ed5
Different names
johnslavik e6e10ad
Idiomatize and simplify
johnslavik ac6cd83
Merge branch 'main' into asyncio-repl-handle-python-startup
johnslavik 149740a
Purifying `sys.path` is implied by `-P`
johnslavik bffac1c
Merge branch 'main' into asyncio-repl-handle-python-startup
johnslavik a4c307e
Separate tests for regular and asyncio REPL
johnslavik a774da5
Remove duplicate assertion
johnslavik b3ed3d4
Document `new_startup_env`
johnslavik df6dfd8
Fix `new_startup_env` docs
johnslavik b004839
More meaningful line breaks
johnslavik ce03cce
Better variables
johnslavik 9e92510
Use default histfile
johnslavik 0a50a50
Fix newline
johnslavik f8b8d53
Use `TestCase.enterContext`
johnslavik 5701fef
Remove lines with ps1
johnslavik 393aaad
Merge branch 'main' into asyncio-repl-handle-python-startup
johnslavik 875fd2a
Employ `asyncio.Runner` in the asyncio REPL
johnslavik 4377d82
Revert "Employ `asyncio.Runner` in the asyncio REPL"
johnslavik c4e488e
Merge branch 'main' into asyncio-repl-handle-python-startup
johnslavik b9ffea7
Add a todo for future
johnslavik ab799e6
Merge branch 'main' into asyncio-repl-handle-python-startup
johnslavik 2f8f99b
Merge branch 'main' into asyncio-repl-handle-python-startup
johnslavik 6020996
Rename the decorator
johnslavik 125efa6
Colorize the news entry
johnslavik cc624d1
Simplify `new_pythonstartup_env`
johnslavik 812d22f
Simplify tests by a gazillion procent 🚀🚀🚀
johnslavik 6749b83
Simplify the tests further 🚀
johnslavik e76426d
And even further
johnslavik 376c7a4
Rephrase the news entry
johnslavik File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -5,6 +5,7 @@ | |
| import subprocess | ||
| import sys | ||
| import unittest | ||
| from contextlib import contextmanager | ||
| from functools import partial | ||
| from textwrap import dedent | ||
| from test import support | ||
|
|
@@ -67,6 +68,19 @@ def spawn_repl(*args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, custom=F | |
| spawn_asyncio_repl = partial(spawn_repl, "-m", "asyncio", custom=True) | ||
|
|
||
|
|
||
| @contextmanager | ||
| def new_pythonstartup_env(*, code: str, histfile: str = ".pythonhist"): | ||
| """Create environment variables for a PYTHONSTARTUP script in a temporary directory.""" | ||
| with os_helper.temp_dir() as tmpdir: | ||
| filename = os.path.join(tmpdir, "pythonstartup.py") | ||
| with open(filename, "w") as f: | ||
| f.write(code) | ||
| yield { | ||
| "PYTHONSTARTUP": filename, | ||
| "PYTHON_HISTORY": os.path.join(tmpdir, histfile) | ||
| } | ||
|
|
||
|
|
||
| def run_on_interactive_mode(source): | ||
| """Spawn a new Python interpreter, pass the given | ||
| input source code from the stdin and return the | ||
|
|
@@ -260,8 +274,6 @@ def make_repl(env): | |
| """) % script | ||
| self.assertIn(expected, output) | ||
|
|
||
|
|
||
|
|
||
| def test_runsource_show_syntax_error_location(self): | ||
| user_input = dedent("""def f(x, x): ... | ||
| """) | ||
|
|
@@ -356,6 +368,45 @@ def test_asyncio_repl_is_ok(self): | |
|
|
||
| self.assertEqual(exit_code, 0, "".join(output)) | ||
|
|
||
| def test_pythonstartup_success(self): | ||
| # errors based on https://github.com/python/cpython/issues/137576 | ||
| # case 1: error in user input, but PYTHONSTARTUP is fine | ||
| startup_code = "print('notice from pythonstartup')" | ||
| startup_env = self.enterContext(new_pythonstartup_env(code=startup_code)) | ||
|
|
||
| p = spawn_repl("-q", env=os.environ | startup_env, isolated=False) | ||
| p.stdin.write("1/0") | ||
| output = kill_python(p) | ||
| self.assertStartsWith(output, 'notice from pythonstartup') | ||
| expected = dedent("""\ | ||
| Traceback (most recent call last): | ||
| File "<stdin>", line 1, in <module> | ||
| 1/0 | ||
| ~^~ | ||
| ZeroDivisionError: division by zero | ||
| """) | ||
| self.assertIn(expected, output) | ||
|
|
||
| def test_pythonstartup_failure(self): | ||
| # case 2: error in PYTHONSTARTUP triggered by user input | ||
| startup_code = "def foo():\n 1/0\n" | ||
| startup_env = self.enterContext(new_pythonstartup_env(code=startup_code)) | ||
|
|
||
| p = spawn_repl("-q", env=os.environ | startup_env, isolated=False) | ||
| p.stdin.write("foo()") | ||
| output = kill_python(p) | ||
| expected = dedent(f"""\ | ||
| Traceback (most recent call last): | ||
| File "<stdin>", line 1, in <module> | ||
| foo() | ||
| ~~~^^ | ||
| File "{startup_env['PYTHONSTARTUP']}", line 2, in foo | ||
| 1/0 | ||
| ~^~ | ||
| ZeroDivisionError: division by zero | ||
| """) | ||
| self.assertIn(expected, output) | ||
|
|
||
|
|
||
| @support.force_not_colorized_test_class | ||
| class TestInteractiveModeSyntaxErrors(unittest.TestCase): | ||
|
|
@@ -376,6 +427,7 @@ def f(): | |
| self.assertEqual(traceback_lines, expected_lines) | ||
|
|
||
|
|
||
| @support.force_not_colorized_test_class | ||
|
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I'm not sure this is needed, but I think it's OK to keep it as is. |
||
| class TestAsyncioREPL(unittest.TestCase): | ||
| def test_multiple_statements_fail_early(self): | ||
| user_input = "1 / 0; print(f'afterwards: {1+1}')" | ||
|
|
@@ -426,6 +478,50 @@ def test_quiet_mode(self): | |
| self.assertEqual(p.returncode, 0) | ||
| self.assertEqual(output[:3], ">>>") | ||
|
|
||
| def test_pythonstartup_success(self): | ||
| startup_code = dedent("print('notice from pythonstartup in asyncio repl')") | ||
| startup_env = self.enterContext( | ||
| new_pythonstartup_env(code=startup_code, histfile=".asyncio_history")) | ||
|
|
||
| p = spawn_repl( | ||
| "-qm", "asyncio", | ||
| env=os.environ | startup_env, | ||
| isolated=False, | ||
| custom=True) | ||
| p.stdin.write("1/0") | ||
| output = kill_python(p) | ||
| self.assertStartsWith(output, 'notice from pythonstartup in asyncio repl') | ||
|
|
||
| expected = dedent("""\ | ||
| File "<stdin>", line 1, in <module> | ||
| 1/0 | ||
| ~^~ | ||
| ZeroDivisionError: division by zero | ||
| """) | ||
| self.assertIn(expected, output) | ||
|
|
||
| def test_pythonstartup_failure(self): | ||
| startup_code = "def foo():\n 1/0\n" | ||
| startup_env = self.enterContext( | ||
| new_pythonstartup_env(code=startup_code, histfile=".asyncio_history")) | ||
|
|
||
| p = spawn_repl( | ||
| "-qm", "asyncio", | ||
| env=os.environ | startup_env, | ||
| isolated=False, | ||
| custom=True) | ||
| p.stdin.write("foo()") | ||
| output = kill_python(p) | ||
| expected = dedent(f"""\ | ||
| File "<stdin>", line 1, in <module> | ||
| foo() | ||
| ~~~^^ | ||
| File "{startup_env['PYTHONSTARTUP']}", line 2, in foo | ||
| 1/0 | ||
| ~^~ | ||
| ZeroDivisionError: division by zero | ||
| """) | ||
| self.assertIn(expected, output) | ||
|
|
||
| if __name__ == "__main__": | ||
| unittest.main() | ||
5 changes: 5 additions & 0 deletions
5
Misc/NEWS.d/next/Library/2025-10-18-12-13-39.gh-issue-140287.49iU-4.rst
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| The :mod:`asyncio` REPL now properly handles exceptions in :envvar:`PYTHONSTARTUP` scripts. | ||
| Previously, any startup exception could prevent the REPL from starting or even cause | ||
| a fatal error. | ||
|
|
||
| Patch by Bartosz Sławecki in :gh:`140287`. |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I really don't like this, but it resembles the original behavior of the REPLs -- see GH-143023.
I don't think this is correct, but it's not super clear to me, so please chime in to GH-143023 to put your two cents in.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
GH-143023 is also why I didn't add a test for this.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
We've got some good news, this is not bad! I'll add a test shortly.