【问题标题】:python 2 code: if python 3 then sys.exit()python 2 代码:如果 python 3 则 sys.exit()
【发布时间】: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


    【解决方案1】:

    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 代码。

    【讨论】:

    • 使用 EAFP 并把 the_real_thing 的导入放在 try 块中会不会被认为更 Pythonic
    • @martineau:我不会在手头的情况下这样做。 import 很可能会成功,main() 中可能会发生其他错误。您不想将 the_real_thing.main() 包含在 try/except 中。
    • @inspectorG4dget:我不太明白你的意见,但为了完整起见,我添加了if __name__ == "__main__":
    • @inspectorG4dget:这些块只有在文件开头时才会首先执行。可能我很无聊,但我真的不明白!
    • @inspectorG4dget:在 Python 开始执行模块之前,整个文件是字节编译的。这包括解析整个文件。添加if __name__ == "foo" 并没有改变任何内容。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-05
    • 2018-12-12
    • 1970-01-01
    • 1970-01-01
    • 2020-08-29
    • 2022-06-17
    相关资源
    最近更新 更多