【发布时间】:2012-06-30 21:14:17
【问题描述】:
我有一大段仅限 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
但是,退出并没有发生。输出是:
$ python3 testing.py
File "testing.py", line 8
print "Here comes a lot of pure Python 2.x stuff ..."
^
SyntaxError: invalid syntax
因此,看起来 python 在执行任何操作之前检查了整个代码,因此出现了错误。
python2 代码是否有一个很好的方法来检查 python3 是否被使用,如果是,打印一些友好的内容然后退出?
【问题讨论】:
标签: python python-3.x python-2.x