Pythonバージョンの取得方法

  • 9
    いいね
  • 0
    コメント

実行中のPythonプログラムからPythonバージョンを取得する方法を示す。
取得方法は複数ある。

  1. sys.version_info
  2. platform.python_version_tuple()
  3. six

sys.version_infoから取得

sys.version_infoはPython 2.7未満/3.0はtuple
2.7/3.1以降はnamedtupleになっている。

28.1. sys — System-specific parameters and functions — Python 2.7.11 documentation

sys.version_info

A tuple containing the five components of the version number: major, minor, micro, releaselevel, and serial. All values except releaselevel are integers; the release level is 'alpha', 'beta', 'candidate', or 'final'. The version_info value corresponding to the Python version 2.0 is (2, 0, 0, 'final', 0). The components can also be accessed by name, so sys.version_info[0] is equivalent to sys.version_info.major and so on.

New in version 2.0.

Changed in version 2.7: Added named component attributes

python2.5
>>> import sys
>>> sys.version_info
(2, 5, 2, 'final', 0)
python2.7
>>> import sys
>>> sys.version_info
sys.version_info(major=2, minor=7, micro=12, releaselevel='final', serial=0)
python3.5
>>> import sys
>>> sys.version_info
sys.version_info(major=3, minor=5, micro=2, releaselevel='final', serial=0)

platform.python_version_tuple()で取得

15.15. platform — Access to underlying platform’s identifying data — Python 2.7.11 documentation

New in version 2.3.

platform.python_version_tuple()

Returns the Python version as tuple (major, minor, patchlevel) of strings.

Note that unlike the Python sys.version, the returned value will always include the patchlevel (it defaults to '0').

実行例

python3.5
>>> import platform
>>> platform.python_version_tuple()
('3', '5', '2')

six

sixで取得できるのはPython 2.x/3.xの判別のみ。

>>> import six
>>> six.PY2
True
>>> six.PY3
False