编译(但不运行)一个 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
Compile (but do not run) a Python script
提问by asmeurer
Possible Duplicate:
How can I check the syntax of Python script without executing it?
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
py_compile — Compile Python source files
import py_compile
py_compile.compile('my_script.py')
回答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
回答by Mark Johnson
python -m py_compile script.py

