【问题标题】:How to detect Python Version 2 or 3 in script?如何在脚本中检测 Python 版本 2 或 3?
【发布时间】:2015-02-07 05:23:54
【问题描述】:

我已经编写了一些脚本,它们要么只在 2.x 版中运行,要么一些只在 Python 3.x 版中运行。

如果脚本以适配 Python 版本开始,我如何检测脚本内部?

有没有类似的命令:

major, minor = getPythonVersion()

【问题讨论】:

标签: python python-3.x version python-2.x six


【解决方案1】:

sys.version_info 提供使用的 Python 解释器的版本。

Python 2

>>> import sys
>>> sys.version_info
sys.version_info(major=2, minor=7, micro=6, releaselevel='final', serial=0)
>>> sys.version_info[0]
2

Python 3

>>> import sys
>>> sys.version_info
sys.version_info(major=3, minor=7, micro=10, releaselevel='final', serial=0)
>>> sys.version_info[0]
3

详情见the documentation

【讨论】:

    【解决方案2】:

    您可以使用六个库 (https://pythonhosted.org/six/) 来更轻松地编写适用于两个版本的代码。 (它包括两个布尔值six.PY2six.PY3,表示代码是在 Python 2 还是 Python 3 中运行)

    在 Python 2.6 和 2.7 中也可以使用

    from __future__ import (print_function, unicode_literals, division)
    __metaclass__ = type
    

    以一种适用于 2 和 3 的方式启用某些 Python 3 行为。

    【讨论】:

    • 这是有用的补充信息,但并不能真正回答问题。
    猜你喜欢
    • 2011-09-02
    • 1970-01-01
    • 2020-04-20
    • 2013-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多