SyntaxError not excepting in Python 3 [duplicate]

◇◆丶佛笑我妖孽 提交于 2020-01-05 12:12:57

问题


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

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

What am I missing?


回答1:


SyntaxErrors are thrown at compile-time. You cannot catch them like runtime exceptions.

If you want to check python version, look at sys.version_info.

i.e.

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



回答2:


Here's a small example on how to do what you want:

import sys

if sys.version_info.major == 2:
    print("Error: This program should only be run in Python 3.")
    raw_input('>')
    exit(0)

This code will run in python2 and python3. You don't need to use a try catch in that case. Since in python2, it happens that the ( and ) will have no effect since they aren't tuples. You can write that kind of thing and it will work in python2 and python3 without SyntaxError.



来源:https://stackoverflow.com/questions/21662999/syntaxerror-not-excepting-in-python-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!