问题描述
我正在尝试在我的程序顶部编写一个代码块,如果程序意外地在 Python 2.x 中运行,它将给出错误消息并退出,但如果在 Python 3.x 中运行会正常运行:
I'm trying to write a block of code at the top of my programs that, if the program is accidentally run in Python 2.x, it will give an error message and quit, but if run in Python 3.x will run normally:
try:
print "Error: This program should only be run in Python 3."
raw_input('>')
exit()
except SyntaxError:
pass
print("I see you're running Python 3.")
# rest of program
这在 Python 2.7 中正常工作(即,它显示错误并退出),但是当我在 Python 3.3 中运行它时,我得到一个 SyntaxError,即使我告诉它有一个异常.
This works correctly in Python 2.7 (i.e., it displays the error and quits), but when I run it in Python 3.3, I get a SyntaxError, even though I told it to have an exception.
File "version.py", line 2
print "This program should only be run in Python 3"
^
SyntaxError: invalid syntax
我错过了什么?
推荐答案
SyntaxError
在编译时抛出.你不能像运行时异常一样捕获它们.
SyntaxError
s are thrown at compile-time. You cannot catch them like runtime exceptions.
如果要查看python版本,查看sys.version_info
.
If you want to check python version, look at sys.version_info
.
即
import sys
if sys.version_info.major < 3:
sys.exit('This program should only be run in Python 3')
这篇关于SyntaxError 在 Python 3 中不例外的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!