如何验证 Python 脚本的语法?

How to validate the syntax of a Python script?

我只想让我的 Python 脚本以最简单的方式询问 "is the Python code which I just generated syntactically valid Python?"

我试过:

try:  
    import py_compile  
    x = py_compile.compile(generatedScriptPath, doraise=True)  
    pass  

except py_compile.PyCompileError, e:
    print str(e)
    pass

但即使文件包含无效 Python,也不会抛出异常,之后 x == None.

不需要使用py_compile。它的预期用途是从给定的源文件写一个字节码文件。事实上,如果您没有在目录中写入的权限,它将失败,因此您最终可能会出现一些漏报。

要仅解析并验证语法,您可以使用 ast module to parse the contents of the file, or directly call the compile 内置函数。

import ast

def is_valid_python_file(fname):
    with open(fname) as f:
        contents = f.read()
    try:
        ast.parse(contents)
        #or compile(contents, fname, 'exec', ast.PyCF_ONLY_AST)
        return True
    except SyntaxError:
        return False

一定要不要执行文件,因为如果你不能相信它的内容(如果你甚至不知道文件是否包含有效的语法,我怀疑你真的可以信任内容,即使它们是您生成的)您最终可能会执行恶意代码。