正如标题所说,有没有更好的方法可以在不使用外部模块的情况下检查 Python 源代码中的语法错误?
我的意思是,在某种意义上更 Pythonic 风格或更高效的方式。
def CheckSyntax(source, raw = False):
lines = source.count("\n")
source += "\nThis is a SyntaxError" # add a syntax error to source, it shouldn't be executed at all
try:
exec source in {}, {}
except SyntaxError, e:
if e.lineno != lines + 2:
if raw:
return e
else:
return e.lineno, e.offset, e.text
编辑:理想情况下,它对于实时语法检查来说足够高效。