我有一大段仅限 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 会在开始执行之前对源文件进行字节编译。整个文件必须至少正确解析,否则你会得到一个SyntaxError
。
解决您的问题的最简单方法是编写一个小型包装器,将其解析为 Python 2.x 和 3.x。示例:
import sys
if sys.version_info >= (3, 0):
sys.stdout.write("Sorry, requires Python 2.x, not Python 3.x\n")
sys.exit(1)
import the_real_thing
if __name__ == "__main__":
the_real_thing.main()
import the_real_thing
语句只会在 if
语句之后执行,因此该模块中的代码不需要解析为 Python 3.x代码。
关于python 2代码: if python 3 then sys.退出(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11277721/