简体   繁体   English

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

[英]python 2 code: if python 3 then sys.exit()

I have a large piece of Python 2 only code. 我有一大块Python 2代码。 It want to check for Python 3 at the beginning, and exit if python3 is used. 它想在开始时检查Python 3,如果使用python3则退出。 So I tried: 所以我尝试过:

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

However, the exit does not happen. 但是,退出不会发生。 The output is: 输出是:

$ python3 testing.py 
  File "testing.py", line 8
        print "Here comes a lot of pure Python 2.x stuff ..."
                                                        ^
SyntaxError: invalid syntax

So, it looks like python checks the whole code before executing anything, and hence the error. 因此,看起来python在执行任何操作之前检查整个代码,因此错误。

Is there a nice way for python2 code to check for python3 being used, and if so print something friendly and then exit? 是否有一个很好的方法让python2代码检查正在使用的python3,如果是这样打印一些友好的东西,然后退出?

Python will byte-compile your source file before starting to execute it. Python将在开始执行之前对源文件进行字节编译。 The whole file must at least parse correctly, otherwise you will get a SyntaxError . 整个文件必须至少正确解析 ,否则你将得到一个SyntaxError

The easiest solution for your problem is to write a small wrapper that parses as both, Python 2.x and 3.x. 解决问题的最简单方法是编写一个解析为Python 2.x和3.x的小包装器。 Example: 例:

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()

The statement import the_real_thing will only be executed after the if statement, so the code in this module is not required to parse as Python 3.x code. 语句import the_real_thing只会在if语句之后执行,因此该模块中的代码不需要解析为Python 3.x代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM