The Python Oracle

How do I detect the Python version at runtime?

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Puddle Jumping Looping

--

Chapters
00:00 Question
00:32 Accepted answer (Score 697)
01:30 Answer 2 (Score 144)
01:43 Answer 3 (Score 29)
01:59 Answer 4 (Score 19)
02:48 Thank you

--

Full question
https://stackoverflow.com/questions/9079...

Accepted answer links:
[sys.version]: http://docs.python.org/library/sys.html#...
[sys.version_info]: http://docs.python.org/library/sys.html#...
[How can I check for Python version in a program that uses new language features?]: https://stackoverflow.com/questions/4460...

Answer 3 links:
[sys.hexversion]: https://docs.python.org/library/sys.html...
[API and ABI Versioning]: https://docs.python.org/c-api/apiabivers...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python

#avk47



ACCEPTED ANSWER

Score 755


Sure, take a look at sys.version and sys.version_info.

For example, to check that you are running Python 3.x, use

import sys
if sys.version_info[0] < 3:
    raise Exception("Must be using Python 3")

Here, sys.version_info[0] is the major version number. sys.version_info[1] would give you the minor version number.

In Python 2.7 and later, the components of sys.version_info can also be accessed by name, so the major version number is sys.version_info.major.

See also How can I check for Python version in a program that uses new language features?




ANSWER 2

Score 162


Try this code, this should work:

import platform
print(platform.python_version())



ANSWER 3

Score 34


Per sys.hexversion and API and ABI Versioning:

import sys
if sys.hexversion >= 0x3000000:
    print('Python 3.x hexversion %s is in use.' % hex(sys.hexversion))



ANSWER 4

Score 18


The best solution depends on how much code is incompatible. If there are a lot of places you need to support Python 2 and 3, six is the compatibility module. six.PY2 and six.PY3 are two booleans if you want to check the version.

However, a better solution than using a lot of if statements is to use six compatibility functions if possible. Hypothetically, if Python 3000 has a new syntax for next, someone could update six so your old code would still work.

import six

# OK
if six.PY2:
  x = it.next() # Python 2 syntax
else:
  x = next(it) # Python 3 syntax

# Better
x = six.next(it)

http://pythonhosted.org/six/