- 
          
 - 
                Notifications
    
You must be signed in to change notification settings  - Fork 33.3k
 
          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
      
      
            bswck
  wants to merge
  18
  commits into
  python:main
  
    
      
        
          
  
    
      Choose a base branch
      
     
    
      
        
      
      
        
          
          
        
        
          
            
              
              
              
  
           
        
        
          
            
              
              
           
        
       
     
  
        
          
            
          
            
          
        
       
    
      
from
bswck: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.
          
          
      
        
          +72
        
        
          −83
        
        
          
        
      
    
  
  
     Draft
                    Changes from all commits
      Commits
    
    
            Show all changes
          
          
            18 commits
          
        
        Select commit
          Hold shift + click to select a range
      
      faa22f4
              
                Handle `PYTHONSTARTUP` script exceptions
              
              
                bswck 5b3ad2c
              
                Add blurb
              
              
                bswck 00edac4
              
                Use `console.showtraceback()` instead of `sys.excepthook()`
              
              
                bswck e396622
              
                Properly run asyncio REPL in REPL tests
              
              
                bswck 4079074
              
                Move comment to a better place
              
              
                bswck 0440d0e
              
                Add tests
              
              
                bswck af6f657
              
                Merge branch 'properly-run-asyncio-repl-in-repl-tests' into asyncio-r…
              
              
                bswck 848638d
              
                Merge branch 'main' into asyncio-repl-handle-python-startup
              
              
                bswck d158dbf
              
                Improve test structure
              
              
                bswck 9355da7
              
                Use `SHORT_TIMEOUT`
              
              
                bswck 3dc4cac
              
                Revert "Use `SHORT_TIMEOUT`"
              
              
                bswck c786584
              
                Force no colorization
              
              
                bswck b76db67
              
                Linecache doesn't matter and shouldn't break tests
              
              
                bswck cad1748
              
                Don't rely on line numbering on Windows...
              
              
                bswck d114ed5
              
                Different names
              
              
                bswck e6e10ad
              
                Idiomatize and simplify
              
              
                bswck ac6cd83
              
                Merge branch 'main' into asyncio-repl-handle-python-startup
              
              
                bswck 149740a
              
                Purifying `sys.path` is implied by `-P`
              
              
                bswck 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
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 | ||
| 
        
          
        
         | 
    @@ -28,7 +29,7 @@ | |
| raise unittest.SkipTest("test module requires subprocess") | ||
| 
     | 
||
| 
     | 
||
| def spawn_repl(*args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, custom=False, **kw): | ||
| def spawn_repl(*args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, custom=False, isolated=True, **kw): | ||
| """Run the Python REPL with the given arguments. | ||
| 
     | 
||
| kw is extra keyword args to pass to subprocess.Popen. Returns a Popen | ||
| 
        
          
        
         | 
    @@ -42,7 +43,10 @@ def spawn_repl(*args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, custom=F | |
| # path may be used by PyConfig_Get("module_search_paths") to build the | ||
| # default module search path. | ||
| stdin_fname = os.path.join(os.path.dirname(sys.executable), "<stdin>") | ||
| cmd_line = [stdin_fname, '-I'] | ||
| cmd_line = [stdin_fname] | ||
| # Isolated mode implies -EPs and ignores PYTHON* variables. | ||
| if isolated: | ||
| cmd_line.append('-I') | ||
| # Don't re-run the built-in REPL from interactive mode | ||
| # if we're testing a custom REPL (such as the asyncio REPL). | ||
| if not custom: | ||
| 
          
            
          
           | 
    @@ -197,68 +201,6 @@ def foo(x): | |
| ] | ||
| self.assertEqual(traceback_lines, expected_lines) | ||
| 
     | 
||
| def test_pythonstartup_error_reporting(self): | ||
| # errors based on https://github.com/python/cpython/issues/137576 | ||
| 
     | 
||
| def make_repl(env): | ||
| return subprocess.Popen( | ||
| [os.path.join(os.path.dirname(sys.executable), '<stdin>'), "-i"], | ||
| executable=sys.executable, | ||
| text=True, | ||
| stdin=subprocess.PIPE, | ||
| stdout=subprocess.PIPE, | ||
| stderr=subprocess.STDOUT, | ||
| env=env, | ||
| ) | ||
| 
     | 
||
| # case 1: error in user input, but PYTHONSTARTUP is fine | ||
| with os_helper.temp_dir() as tmpdir: | ||
| script = os.path.join(tmpdir, "pythonstartup.py") | ||
| with open(script, "w") as f: | ||
| f.write("print('from pythonstartup')" + os.linesep) | ||
| 
     | 
||
| env = os.environ.copy() | ||
| env['PYTHONSTARTUP'] = script | ||
| env["PYTHON_HISTORY"] = os.path.join(tmpdir, ".pythonhist") | ||
| p = make_repl(env) | ||
| p.stdin.write("1/0") | ||
| output = kill_python(p) | ||
| expected = dedent(""" | ||
| Traceback (most recent call last): | ||
| File "<stdin>", line 1, in <module> | ||
| 1/0 | ||
| ~^~ | ||
| ZeroDivisionError: division by zero | ||
| """) | ||
| self.assertIn("from pythonstartup", output) | ||
| self.assertIn(expected, output) | ||
| 
     | 
||
| # case 2: error in PYTHONSTARTUP triggered by user input | ||
| with os_helper.temp_dir() as tmpdir: | ||
| script = os.path.join(tmpdir, "pythonstartup.py") | ||
| with open(script, "w") as f: | ||
| f.write("def foo():\n 1/0\n") | ||
| 
     | 
||
| env = os.environ.copy() | ||
| env['PYTHONSTARTUP'] = script | ||
| env["PYTHON_HISTORY"] = os.path.join(tmpdir, ".pythonhist") | ||
| p = make_repl(env) | ||
| p.stdin.write('foo()') | ||
| output = kill_python(p) | ||
| expected = dedent(""" | ||
| Traceback (most recent call last): | ||
| File "<stdin>", line 1, in <module> | ||
| foo() | ||
| ~~~^^ | ||
| File "%s", line 2, in foo | ||
| 1/0 | ||
| ~^~ | ||
| ZeroDivisionError: division by zero | ||
| """) % script | ||
| self.assertIn(expected, output) | ||
| 
     | 
||
| 
     | 
||
| 
     | 
||
| def test_runsource_show_syntax_error_location(self): | ||
| user_input = dedent("""def f(x, x): ... | ||
| """) | ||
| 
          
            
          
           | 
    @@ -292,24 +234,6 @@ def bar(x): | |
| expected = "(30, None, [\'def foo(x):\\n\', \' return x + 1\\n\', \'\\n\'], \'<stdin>\')" | ||
| self.assertIn(expected, output, expected) | ||
| 
     | 
||
| def test_asyncio_repl_reaches_python_startup_script(self): | ||
| with os_helper.temp_dir() as tmpdir: | ||
| script = os.path.join(tmpdir, "pythonstartup.py") | ||
| with open(script, "w") as f: | ||
| f.write("print('pythonstartup done!')" + os.linesep) | ||
| f.write("exit(0)" + os.linesep) | ||
| 
     | 
||
| env = os.environ.copy() | ||
| env["PYTHON_HISTORY"] = os.path.join(tmpdir, ".asyncio_history") | ||
| env["PYTHONSTARTUP"] = script | ||
| subprocess.check_call( | ||
| [sys.executable, "-m", "asyncio"], | ||
| stdout=subprocess.PIPE, | ||
| stderr=subprocess.PIPE, | ||
| env=env, | ||
| timeout=SHORT_TIMEOUT, | ||
| ) | ||
| 
         
      Comment on lines
    
      -295
     to 
      -311
    
   
  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. Covered by   | 
||
| 
     | 
||
| @unittest.skipUnless(pty, "requires pty") | ||
| def test_asyncio_repl_is_ok(self): | ||
| m, s = pty.openpty() | ||
| 
          
            
          
           | 
    @@ -346,6 +270,64 @@ def test_asyncio_repl_is_ok(self): | |
| self.assertEqual(exit_code, 0, "".join(output)) | ||
| 
     | 
||
| 
     | 
||
| @contextmanager | ||
| def new_startup_env(*, code: str, histfile: str = ".pythonhist"): | ||
| with os_helper.temp_dir() as tmpdir: | ||
| filename = os.path.join(tmpdir, "pythonstartup.py") | ||
| with open(filename, "w") as f: | ||
| f.write(os.linesep.join(code.splitlines())) | ||
| yield {"PYTHONSTARTUP": filename, "PYTHON_HISTORY": os.path.join(tmpdir, histfile)} | ||
| 
     | 
||
| 
     | 
||
| @support.force_not_colorized_test_class | ||
| class TestPythonStartup(unittest.TestCase): | ||
| REPLS = [ | ||
| ("REPL", spawn_repl, ".pythonhist"), | ||
| ("asyncio REPL", spawn_asyncio_repl, ".asyncio_history"), | ||
| ] | ||
| 
     | 
||
| 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('from pythonstartup')" | ||
| for repl_name, repl_factory, histfile in self.REPLS: | ||
| with ( | ||
| self.subTest(repl_name), | ||
| new_startup_env(code=startup_code, histfile=histfile) as startup_env | ||
| ): | ||
| p = repl_factory(env=os.environ | startup_env, isolated=False) | ||
| p.stdin.write("1/0") | ||
| output = kill_python(p) | ||
| 
     | 
||
| for expected in ( | ||
| "from pythonstartup", | ||
| "Traceback (most recent call last):", | ||
| 'File "<stdin>", line 1, in <module>', | ||
| "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" | ||
| for repl_name, repl_factory, histfile in self.REPLS: | ||
| with ( | ||
| self.subTest(repl_name), | ||
| new_startup_env(code=startup_code, histfile=histfile) as startup_env | ||
| ): | ||
| p = repl_factory(env=os.environ | startup_env, isolated=False) | ||
| p.stdin.write('foo()') | ||
| output = kill_python(p) | ||
| 
     | 
||
| for expected in ( | ||
| "Traceback (most recent call last):", | ||
| 'File "<stdin>", line 1, in <module>', | ||
| f'File "{startup_env['PYTHONSTARTUP']}", line ', | ||
| 
         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 need to understand why line number 2 fails specifically on Windows and 3 is expected.  | 
||
| "ZeroDivisionError: division by zero", | ||
| ): | ||
| self.assertIn(expected, output) | ||
| 
     | 
||
| 
     | 
||
| @support.force_not_colorized_test_class | ||
| class TestInteractiveModeSyntaxErrors(unittest.TestCase): | ||
| 
     | 
||
| 
          
            
          
           | 
    ||
        
          
          
            2 changes: 2 additions & 0 deletions
          
          2 
        
  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,2 @@ | ||
| The asyncio REPL now properly handles exceptions in ``PYTHONSTARTUP`` | ||
| scripts. 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.
  
    
  
    
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.
To reuse this routine and
spawn_asyncio_replbelow, we need to have a knob to not pass-Isince that ignoresPYTHONSTARTUPcompletely.The asyncio REPL currently doesn't comply to that, which is a separate issue I'll report having learnt 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.
Tracking the
-Iedge case in #140648.