Python 抽象语法:检测语法错误的' [英] Python Abstract Syntax: Detect syntax error's'

查看:38
本文介绍了Python 抽象语法:检测语法错误的'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以通过一次迭代检测多个 python 语法错误?

Is it possible to detect multiple python syntax errors with one iteration?

有 2 个语法错误的 Python 文件 test.py:

Python file with 2 syntax errors test.py:

print 'hello'
test =-
b = 1 + 1
test =+
print 'world'

这段代码只处理第 2 行的第一个语法错误,而不处理第 4 行的错误:

This code only gets to the first syntax error on line 2, not to the error on line 4:

import parser
parser.suite(open('test.py').read())
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 2
    test =-

如何检测 *.py 文件的所有语法错误?(不仅是第一个)

How could I detect all syntax errors of a *.py file? (not only the first)

谢谢!

推荐答案

不,你不能,因为在一次语法错误之后,其余的代码结构将不再可恢复.

No, you cannot, because after one syntax error the rest of the code structure is no longer recoverable.

以缺少括号为例;那是缺少括号还是逗号?下一行的函数调用是否是带有错误的表达式的一部分?如果缺少逗号,则下一行可能缺少括号.如果缺少括号,则下一行的括号可能过多.这将是两个非常不同的语法错误,取决于之前的语法错误的真正含义.

Take a missing parenthesis for example; was that a parenthesis that was missing, or a comma? Is the function call on the next line therefor part of the expression with the error, or not? If the comma was missing, there might be a parenthesis missing on the next line. If the parenthesis was missing, there might be a parenthesis too many on the next line. That'd be two very different syntax errors that depend on what the previous syntax error really was meant to be.

一处语法错误会使其余代码无效,继续解析没有意义,至少对于需要生成有效字节码的 Python 而言如此.

A syntax error in one place invalidates the rest of the code and there is no point in continuing parsing, at least not for Python which needs to produce valid bytecode.

您可以使用 Python linter;许多可以与您选择的文本编辑器集成.Python IDE 或 linter 不必生成字节码,并且可以更灵活地处理语法错误(继续检查后续行),并且还可以告诉您其他问题,例如缺少或未使用的导入和变量.

You can use a Python linter; many can be integrated with your text editor of choice. A Python IDE or linter does not have to produce bytecode and can be more flexible in handling syntax errors (continueing checking on subsequent lines), and can tell you about other problems too, like missing or unused imports and variables.

这篇关于Python 抽象语法:检测语法错误的'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆