如何在脚本中检测Python版本2或3?

run*_*gel 9 python version python-2.x python-3.x six

我编写了一些脚本,它们只运行版本2.x或者只运行Python版本3.x.

我如何检测脚本内部,如果它是从适合Python版本开始的?

有这样的命令:

major, minor = getPythonVersion()
Run Code Online (Sandbox Code Playgroud)

Kla*_* D. 12

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

有关详细信息,请参阅https://docs.python.org/2/library/sys.html.


小智 6

您可以使用六个库 ( 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
Run Code Online (Sandbox Code Playgroud)

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