我有一大块Python 2代码.它想在开始时检查Python 3,如果使用python3则退出.所以我尝试过:
import sys
if sys.version_info >= (3,0):
print("Sorry, requires Python 2.x, not Python 3.x")
sys.exit(1)
print "Here comes a lot of pure Python 2.x stuff ..."
### a lot of python2 code, not just print statements follows
Run Code Online (Sandbox Code Playgroud)
但是,退出不会发生.输出是:
$ python3 testing.py
File "testing.py", line 8
print "Here comes a lot of pure Python 2.x stuff ..."
^
SyntaxError: invalid syntax
Run Code Online (Sandbox Code Playgroud)
因此,看起来python 在执行任何操作之前检查整个代码,因此错误.
有没有一个很好的方法让python2代码检查正在使用的python3,如果是这样打印一些友好的东西,然后退出?
我想在Python 2.5,2.7和3.2中保留并使用异常的错误值.
在Python 2.5和2.7(但不是3.x)中,这适用于:
try:
print(10 * (1/0))
except ZeroDivisionError, error: # old skool
print("Yep, error caught:", error)
Run Code Online (Sandbox Code Playgroud)
在Python 2.7和3.2中(但不在2.5中),这适用于:
try:
print(10 * (1/0))
except (ZeroDivisionError) as error: # 'as' is needed by Python 3
print("Yep, error caught:", error)
Run Code Online (Sandbox Code Playgroud)
是否有任何代码可用于2.5,2.7和3.2?
谢谢