21

I've written some scripts, which run either only with Version 2.x or some only with Version 3.x of Python.

How can I detect inside the script, if it's started with fitting Python Version?

Is there a command like:

major, minor = getPythonVersion()
smci
  • 32,567
  • 20
  • 113
  • 146
rundekugel
  • 1,118
  • 1
  • 10
  • 23
  • Possible duplicate of [Detect Python version at runtime](https://stackoverflow.com/questions/9079036/detect-python-version-at-runtime) – smci Feb 05 '18 at 00:42

2 Answers2

30

sys.version_info provides the version of the used Python interpreter.

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

For details see the documentation.

Klaus D.
  • 13,874
  • 5
  • 41
  • 48
  • @ewerybody I rejected your edit since using the namedtupel attributes does not work in all versions. – Klaus D. May 17 '23 at 15:41
6

You can use the six library (https://pythonhosted.org/six/) to make it easier to write code that works on both versions. (It includes two booleans six.PY2 and six.PY3 which indicate whether the code is running in Python 2 or Python 3)

Also in Python 2.6 and 2.7, you can use

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

to enable some of the Python 3 behaviour in a way that works on both 2 and 3.

Nameless One
  • 1,615
  • 2
  • 23
  • 39
Cld
  • 461
  • 3
  • 7