0

CPython completely parses a file and begins to run it afterwards(?). Is it also possible get every line executed before the parser continues or run the whole program line by line to get something like this running:

print('not yet')
exit()
print('but here is a SyntaxError incoming'

My goal would be to make a vanilla module that tries to fix SyntaxErrors of the file it is imported into in some way like:

import SyntaxFixer from SyntaxFixer
SyntaxFixer.run() #this line would have to be executed

print( #before this line to fix it, or terminate the program befor a SyntaxError could be thrown

I know that the C reference is quite extensive about the definitions of its behaviour, or when the behaviour is undefined, but I couldn't find a similar definition for Python that would make my project impossible. I want to get it to work with CPython, as this is the default and most used implementation.

Sebig3000
  • 13
  • 4
  • Related/possible duplicate: [Parse a .py file, read the AST, modify it, then write back the modified source code](https://stackoverflow.com/q/768634/11082165) – Brian61354270 Feb 13 '23 at 15:54
  • 2
    The problem with running the script line by line is that there are multi-line statements: block statements like `def` and `if`, continuation lines with escaped newlines, multiple lines in brackets. So it needs to parse each of these groups before it can execute. – Barmar Feb 13 '23 at 15:56
  • @Brian getting [ast.parse](https://docs.python.org/3/library/ast.html#ast.parse) running on a file with a syntax error should not be the problem. I could parse it in a try block, if it fails get the responsible line number, and then run it on the file truncated to the working first part. But it would still need to execute the parse method first. – Sebig3000 Feb 13 '23 at 16:08
  • 1
    @Barmar To add to that, it's doubly not possible to execute a function line-by-line because [the scope of its variables is set when it's defined](https://docs.python.org/3/faq/programming.html#why-am-i-getting-an-unboundlocalerror-when-the-variable-has-a-value). – wjandrea Feb 13 '23 at 18:21

0 Answers0