我有一大块Python 2代码。它希望在开始时检查python3,如果使用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将在开始执行源文件之前对其进行字节编译。整个文件必须至少正确解析,否则将得到一个
SyntaxError
。对于您的问题,最简单的解决方案是编写一个小包装器,它可以同时解析为Python 2.x和3.x
语句
import the_real_thing
只在if
语句之后执行,因此不需要将此模块中的代码解析为Python3.x代码。相关问题 更多 >
编程相关推荐