我曾经使用 perl -c programfile
来检查 Perl 程序的语法,并在不执行它的情况下退出。是否有类似的方法可以用来检查 Python 脚本的语法?
我曾经使用 perl -c programfile
来检查 Perl 程序的语法,并在不执行它的情况下退出。是否有类似的方法可以用来检查 Python 脚本的语法?
你可以通过编译来检查语法:
python -m py_compile script.py
import sys
filename = sys.argv[1]
source = open(filename, 'r').read() + '\n'
compile(source, filename, 'exec')
将此内容保存为checker.py并运行python checker.py yourpyfile.py
。
这里是另一种解决方案,使用 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)
ast.parse(string)
等同于compile(string, filename='<unknown>', mode='exec', flags=ast.PyCF_ONLY_AST)
。参考链接。 - Nils Lindemanndef
语句”是Python创建函数对象的方式,然后这些对象成为模块对象的属性。 - Karl KnechtelPyflakes执行你的要求,它只检查语法。根据文档:
Pyflakes有一个简单的承诺:它永远不会抱怨风格,并且将尝试非常非常努力地永远不发出错误警报。
Pyflakes比Pylint或Pychecker更快。这主要是因为Pyflakes仅独立地检查每个文件的语法树。
安装和使用:
$ pip install pyflakes
$ pyflakes yourPyFile.py
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。
多亏了@Rosh Oxymoron提供的答案。我改进了脚本,扫描目录中所有的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')
将此保存为checker.py并运行python checker.py ~/YOURDirectoryTOCHECK
# ---------------------------------------------------------
# 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
python -m compileall
命令可以递归地编译整个目录,并且它还具有更好的命令行界面。 - C2H5OHpython -m py_compile src/nike_run.py
,它没有出现错误信息,但是在运行时代码会崩溃,并提示消息“TypeError: run_test_in_batch() missing 1 required positional argument: 'total_test_rownum'”,似乎它无法检测到这种错误。如果有误,请纠正我。 - Ninja