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

sup*_*ing 39 python python-2.x python-3.x

我有一大块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,如果是这样打印一些友好的东西,然后退出?

Sve*_*ach 66

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()
Run Code Online (Sandbox Code Playgroud)

该语句import the_real_thing仅在语句之后执行if,因此该模块中的代码不需要解析为Python 3.x代码.

  • 难道不会考虑更多*Pythonic*使用EAFP并将the_real_thing导入到`try`块中吗? (2认同)
  • @martineau:我不会在手头的情况下这样做。导入很可能会成功,并且其他错误可能会在main()中发生。您不想在try / except中包含`the_real_thing.main()`。 (2认同)