How do I check what version of Python is running my script? – Dev

The best answers to the question “How do I check what version of Python is running my script?” in the category Dev.


How can I check what version of the Python Interpreter is interpreting my script?


From the command line (note the capital ‘V’):

python -V

This is documented in ‘man python’.

From IPython console

!python -V


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

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.


Use platform‘s python_version from the stdlib:

from platform import python_version

# 3.9.2


I like sys.hexversion for stuff like this.

>>> import sys
>>> sys.hexversion
>>> '%x' % sys.hexversion
>>> sys.hexversion < 0x02060000