Different ways of getting local python version

Knowing about the local Python version is sometimes useful for debugging complex issues. Sometimes certain Python packages are not supported for a given version of Python which would explain why you are running into some weird Python error or sometimes the Python version on your computer may have reached the end of its life and may support certain new Python features which you thought were ubiquitously available.

In this article, we will learn about how to find the Python version on your computer or any Python virtual environment that you are working with. We will learn how to get the Python version using the command line and using simple Python code.

Getting the Python version from the command line

We all know we can find the version of Python in a Python environment by executing the following command in your command prompt.

> python --version
Python 3.7.6 :: Anaconda, Inc.

Getting the Python version using code

Many times we need to consume the Python version inside a Python module or code. Fortunately, Python modules sys and platform allow us to get the Python versions in a nice program-consumable interface.

Getting the Python version using the sys module

Using the sys module we can get the Python version using the code below. sys.version_info produces a tuple that gives the major, minor and patch versions of Python.

>>> import sys
>>> python_version = sys.version_info
>>> python_version
sys.version_info(major=3, minor=7, micro=6, releaselevel='final', serial=0)
>>> python_version[0]
3
>>> python_version[1]
7
>>> python_version[2]
6

Getting the Python version using the platform module

Using the platform module we can get the Python version as a string using the code below:-

>>> import platform
>>> python_version = platform.python_version()
>>> python_version
'3.7.6'

There is not much to choose from the above two methods to get the Python version. The method described using the sys module gives more flexibility in terms of inspecting the major, minor and patch versions of Python whereas the method described using the platform module is more restrictive as it just gives the Python version as a bare string. To extract the major, minor and patch versions from this string, one has to spend some time composing the tedious regular expressions.