正如标题所说,有没有更好的方法来检查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
编辑:理想情况下,它的性能足以进行实时语法检查。