python - SyntaxError 在 Python 3 中不异常(exception)

标签 python python-2.7 python-3.x syntax-error

<分区>

我试图在我的程序顶部写一段代码,如果程序不小心在 Python 2.x 中运行,它会给出错误消息并退出,但如果在 Python 3.x 中运行将正常运行:

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,即使我告诉它有一个异常。

  File "version.py", line 2
    print "This program should only be run in Python 3"
                                                      ^
SyntaxError: invalid syntax

我错过了什么?

最佳答案

SyntaxError编译时 抛出。您不能像捕获运行时异常一样捕获它们。

如果你想检查 python 版本,请查看 sys.version_info

import sys
if sys.version_info.major < 3:
    sys.exit('This program should only be run in Python 3')

关于python - SyntaxError 在 Python 3 中不异常(exception),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21662999/

相关文章:

c++ - Boost.Python - 公开一个类

python - Sphinx 自动文档与 Django 1.4

python - int()参数必须是字符串,类似字节的对象或数字,而不是 'NoneType'

python - 是否可以在 Python 中重载++ 运算符?

python - 将字典列表中的值映射到 Python 中的字符串

python - 为什么当尝试获取 Python 内置源时,inspect.getsource 会抛出 TypeError ?

python - 使用请求模块未收到来自 HTTPS 站点的响应

python - 我怎样才能打破这一行来满足 PEP8 要求?

python - 属性错误 : 'tuple' object has no attribute 'split' with result of input()?

python - 当 Python 中不再显示唯一 ID 时标记大型数据集