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

时间:2010-11-26 10:12:51

标签: python syntax-checking

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

8 个答案:

答案 0 :(得分:511)

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

python -m py_compile script.py

答案 1 :(得分:54)

您可以使用以下工具:

答案 2 :(得分:16)

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

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

答案 3 :(得分:4)

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

python -c "import ast; ast.parse(open('programfile').read())"

要从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)

答案 4 :(得分:2)

Pyflakes会执行您所要求的操作,它只会检查语法。从文档中:

Pyflakes做出了一个简单的承诺:它永远不会抱怨样式,并且会非常非常努力地避免产生误报。

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

要安装和使用:

$ pip install pyflakes
$ pyflakes yourPyFile.py

答案 5 :(得分:1)

python -m compileall -q .

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

$ 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.

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

感谢 C2H5OH。

答案 6 :(得分:0)

出于某种原因(我是一个新手......)-m电话没有用......

所以这里是一个bash包装器函数...

# ---------------------------------------------------------
# check the python synax for all the *.py files under the
# <<product_version_dir/sfw/python
# ---------------------------------------------------------
doCheckPythonSyntax(){

    doLog "DEBUG START doCheckPythonSyntax"

    test -z "$sleep_interval" || sleep "$sleep_interval"
    cd $product_version_dir/sfw/python
    # python3 -m compileall "$product_version_dir/sfw/python"

    # foreach *.py file ...
    while read -r f ; do \

        py_name_ext=$(basename $f)
        py_name=${py_name_ext%.*}

        doLog "python3 -c \"import $py_name\""
        # doLog "python3 -m py_compile $f"

        python3 -c "import $py_name"
        # python3 -m py_compile "$f"
        test $! -ne 0 && sleep 5

    done < <(find "$product_version_dir/sfw/python" -type f -name "*.py")

    doLog "DEBUG STOP  doCheckPythonSyntax"
}
# eof func doCheckPythonSyntax

答案 7 :(得分:0)

感谢以上回答@Rosh Oxymoron。我改进了脚本以扫描dir目录中的所有文件,这些文件是python文件。因此,对我们来说,懒惰的人只要给它一个目录,它就会扫描该目录中所有的python文件。

import sys
import glob, os

os.chdir(sys.argv[1])
for file in glob.glob("*.py"):
    source = open(file, 'r').read() + '\n'
    compile(source, file, 'exec')

Save this as checker.py and run python checker.py ~/YOURDirectoryTOCHECK

相关问题