编译(但不要运行)Python脚本

时间:2010-12-27 08:15:41

标签: python syntax-checking

  

可能重复:
  How can I check the syntax of Python script without executing it?

如何在不运行Python脚本的情况下编译它?我只是想检查脚本的语法错误。我希望有一个简单的命令行开关,但我在python --help中没有看到任何内容。我想要Python 2和Python 3的答案。

4 个答案:

答案 0 :(得分:344)

python -m py_compile script.py

答案 1 :(得分:45)

py_compile — Compile Python source files

import py_compile
py_compile.compile('my_script.py')

答案 2 :(得分:13)

您可以使用pylint查找语法错误以及更微妙的错误,例如在一些很少使用的条件分支中访问未定义的变量。

答案 3 :(得分:7)

一种方法是做这样的事情(对于test.py):

python -c "__import__('compiler').parse(open('test.py').read())"

这适用于Python 2.x。