小编sup*_*ing的帖子

python 2代码:if python 3 then sys.exit()

我有一大块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 python-2.x python-3.x

39
推荐指数
1
解决办法
3万
查看次数

尝试...除了...作为Python 2.5中的错误 - Python 3.x

我想在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?

谢谢

python exception try-catch

25
推荐指数
1
解决办法
2万
查看次数

标签 统计

python ×2

exception ×1

python-2.x ×1

python-3.x ×1

try-catch ×1