编译(但不运行)一个 Python 脚本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4537411/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 16:13:39  来源:igfitidea点击:

Compile (but do not run) a Python script

pythonsyntax-checking

提问by asmeurer

Possible Duplicate:
How can I check the syntax of Python script without executing it?

可能的重复:
如何在不执行 Python 脚本的情况下检查它的语法?

How do I compile a Python script without running it? I just want to check the script for syntax errors. I was hoping for a simple command line switch, but I didn't see anything in python --help. I'd like an answer for both Python 2 and Python 3.

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

采纳答案by yurymik

回答by Greg Hewgill

One way is to do something like this (for test.py):

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

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

This works for Python 2.x.

这适用于 Python 2.x。

回答by pafcu

You can use pylintto find syntax errors as well as more subtle errors, such as accessing undefined variables in some rarely-used conditional branch.

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

回答by Mark Johnson

python -m py_compile script.py