没有外部模块,有没有更好的方法来检查Python代码的语法错误?

时间:2011-07-29 12:30:46

标签: python syntax-error syntax-checking

正如标题所说,有没有更好的方法来检查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

编辑:理想情况下,它的性能足以进行实时语法检查。

1 个答案:

答案 0 :(得分:6)

exec听起来不是一个特别好的主意。如果相关脚本有副作用(例如创建或修改文件)或需要很长时间才能运行,该怎么办?

查看compile函数和parser模块。