如何在不执行的情况下检查Python脚本的语法?

Eug*_*ash 334 python syntax-checking

我曾经用来perl -c programfile检查Perl程序的语法,然后退出而不执行它.是否有相同的方法为Python脚本执行此操作?

Mar*_*son 550

您可以通过编译来检查语法:

python -m py_compile script.py
Run Code Online (Sandbox Code Playgroud)

  • `python -m compileall`也可以递归地执行目录并具有更好的命令行界面. (47认同)
  • 很好的答案,但我怎么能阻止它创建".pyc"文件?顺便说一下".pyc"文件的用途是什么? (9认同)
  • `import script`,但所有代码都必须在函数中.无论如何,这是一个好习惯.我甚至采用了这个shell脚本.从这里开始,这是单元测试的一小步. (8认同)
  • 对于Python 2.7.9,当存在`-m py_compile`时,我发现`-B`和'PYTHONDONTWRITEBYTECODE`都不会禁止创建**.pyc**文件. (4认同)
  • 我运行脚本“python -m py_compile src/nike_run.py”,它完成时没有错误消息,但代码将在运行时崩溃,并显示消息“TypeError:run_test_in_batch()缺少1个必需的位置参数:'total_test_rownum'” ,似乎无法检测到此类错误。如有错误请指正。 (2认同)

use*_*312 55

您可以使用这些工具:

  • 所有这些都检查语法,所以答案是正确的.其他检查是(非常有用的)奖励. (18认同)
  • 所有这些都不仅仅是检查语法.真的,这不是答案. (9认同)
  • PyChecker 自 2011 年以来就没有更新过,并且不支持 Python 3。 (2认同)

Ros*_*ron 17

import sys
filename = sys.argv[1]
source = open(filename, 'r').read() + '\n'
compile(source, filename, 'exec')
Run Code Online (Sandbox Code Playgroud)

将其保存为checker.py并运行python checker.py yourpyfile.py.

  • 多谢。有用。只有一条评论,代码是否正确没有答案。否则会显示带有行号的错误消息。 (2认同)

jmd*_*_dk 16

这是使用ast模块的另一种解决方案:

python -c "import ast; ast.parse(open('programfile').read())"
Run Code Online (Sandbox Code Playgroud)

要从 Python 脚本中干净地执行此操作:

import ast, traceback

filename = 'programfile'
with open(filename) as f:
    source = f.read()
valid = True
try:
    ast.parse(source)
except SyntaxError:
    valid = False
    traceback.print_exc()  # Remove to silence any errros
print(valid)
Run Code Online (Sandbox Code Playgroud)

  • 很棒的一行代码,不需要所有导入的库或生成 .pyc 文件。谢谢! (3认同)

use*_*062 15

python -m compileall -q .
Run Code Online (Sandbox Code Playgroud)

将递归编译当前目录下的所有内容,并仅打印错误。

$ python -m compileall --help
usage: compileall.py [-h] [-l] [-r RECURSION] [-f] [-q] [-b] [-d DESTDIR] [-x REGEXP] [-i FILE] [-j WORKERS] [--invalidation-mode {checked-hash,timestamp,unchecked-hash}] [FILE|DIR [FILE|DIR ...]]

Utilities to support installing Python libraries.

positional arguments:
  FILE|DIR              zero or more file and directory names to compile; if no arguments given, defaults to the equivalent of -l sys.path

optional arguments:
  -h, --help            show this help message and exit
  -l                    don't recurse into subdirectories
  -r RECURSION          control the maximum recursion level. if `-l` and `-r` options are specified, then `-r` takes precedence.
  -f                    force rebuild even if timestamps are up to date
  -q                    output only error messages; -qq will suppress the error messages as well.
  -b                    use legacy (pre-PEP3147) compiled file locations
  -d DESTDIR            directory to prepend to file paths for use in compile-time tracebacks and in runtime tracebacks in cases where the source file is unavailable
  -x REGEXP             skip files matching the regular expression; the regexp is searched for in the full path of each file considered for compilation
  -i FILE               add all the files and directories listed in FILE to the list considered for compilation; if "-", names are read from stdin
  -j WORKERS, --workers WORKERS
                        Run compileall concurrently
  --invalidation-mode {checked-hash,timestamp,unchecked-hash}
                        set .pyc invalidation mode; defaults to "checked-hash" if the SOURCE_DATE_EPOCH environment variable is set, and "timestamp" otherwise.
Run Code Online (Sandbox Code Playgroud)

当发现语法错误时,退出值为 1。

谢谢C2H5OH


Bri*_* C. 8

Pyflakes 会按照您的要求进行操作,它只是检查语法。从文档:

Pyflakes 做出了一个简单的承诺:它永远不会抱怨风格,并且会非常非常努力地永远不会发出误报。

Pyflakes 也比 Pylint 或 Pychecker 快。这主要是因为 Pyflakes 只单独检查每个文件的语法树。

安装和使用:

$ pip install pyflakes
$ pyflakes yourPyFile.py
Run Code Online (Sandbox Code Playgroud)