The Python Oracle

How do I check which version of Python is running my script?

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: Puzzling Curiosities

--

Chapters
00:00 Question
00:19 Accepted answer (Score 1636)
01:33 Answer 2 (Score 416)
01:54 Answer 3 (Score 103)
02:09 Answer 4 (Score 99)
02:25 Thank you

--

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

Accepted answer links:
[sys.version]: http://docs.python.org/library/sys.html#...
[sys]: http://docs.python.org/library/sys.html
[sys.version_info]: http://docs.python.org/library/sys.html#...
[sys.hexversion]: http://docs.python.org/library/sys.html#...

Answer 3 links:
[platform]: https://docs.python.org/3/library/platfo...

Answer 4 links:
[sys.hexversion]: http://docs.python.org/library/sys.html#...

--

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

--

Tags
#python #version

#avk47



ACCEPTED ANSWER

Score 1700


This information is available in the sys.version string in the sys module:

>>> import sys

Human readable:

>>> print(sys.version)  # parentheses necessary in python 3.       
2.5.2 (r252:60911, Jul 31 2008, 17:28:52) 
[GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)]

For further processing, use sys.version_info or sys.hexversion:

>>> sys.version_info
(2, 5, 2, 'final', 0)
# or
>>> sys.hexversion
34014192

To ensure a script runs with a minimal version requirement of the Python interpreter add this to your code:

assert sys.version_info >= (2, 5)

This compares major and minor version information. Add micro (=0, 1, etc) and even releaselevel (='alpha','final', etc) to the tuple as you like. Note however, that it is almost always better to "duck" check if a certain feature is there, and if not, workaround (or bail out). Sometimes features go away in newer releases, being replaced by others.




ANSWER 2

Score 427


From the command line (note the capital 'V'):

python -V

This is documented in 'man python'.

From IPython console

!python -V



ANSWER 3

Score 100


I like sys.hexversion for stuff like this.

>>> import sys
>>> sys.hexversion
33883376
>>> '%x' % sys.hexversion
'20504f0'
>>> sys.hexversion < 0x02060000
True



ANSWER 4

Score 75


Your best bet is probably something like so:

>>> import sys
>>> sys.version_info
(2, 6, 4, 'final', 0)
>>> if not sys.version_info[:2] == (2, 6):
...    print "Error, I need python 2.6"
... else:
...    from my_module import twoPointSixCode
>>> 

Additionally, you can always wrap your imports in a simple try, which should catch syntax errors. And, to @Heikki's point, this code will be compatible with much older versions of python:

>>> try:
...     from my_module import twoPointSixCode
... except Exception: 
...     print "can't import, probably because your python is too old!"
>>>