我只想为我的Python脚本提供最简单的方法来问“是我刚刚生成的语法上有效的Python的Python代码?”如何验证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
。
你可以简单地尝试导入生成的模块并捕获ImportError(如果模块丢失)或SyntaxError(如果模块无效)?或者,'ast.parse'会在解析无效的Python代码时引发异常。 –
无效的Python是什么意思? – Selcuk
如果您只是想解析模块,您可以使用['ast'](https://docs.python.org/2/library/ast.html)模块的['parse'](https:// docs。 python.org/2/library/ast.html#ast.parse)函数。事实上,有一个['compile'](https://docs.python.org/2/library/functions.html#compile)内置函数可以用来做到这一点。 – Bakuriu