Skip to main content
 首页 » 编程设计

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

2025年05月04日11daizhj

<分区>

我试图在我的程序顶部写一段代码,如果程序不小心在 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 

我错过了什么?