Explain Codes LogoExplain Codes Logo

Printing Python version in output

python
version-info
python-versions
python-configuration
Alex KataevbyAlex Kataev·Sep 2, 2024
TLDR

Let's print out the Python version using the sys module:

import sys print(sys.version)

This code will output the full version string you're running, including the major, minor, and patch levels. It’s like printing the ID card of your Python interpreter. It doesn't get any simpler, does it?

Just the version numbers, please!

Sometimes you just need the core version numbers (major.minor.micro), without additional fluff. Based on Bastien Léonard's solution, we can extract it this way:

import sys version_numbers = f'{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}' print(version_numbers)

Now, this doesn’t scare off the version number purists!

When more is better

For occasions when you need more detailed version info, like when debugging or troubleshooting some intricate issues, use sys.version_info:

import sys print(f'Python version : {sys.version}') print(f'Version info: {sys.version_info}')

sys.version_info serves the full info sandwich with major, minor, micro, release level, and serial. Tasty!

Deep diving with sysconfig

In cases where even this is not enough, we turn to our secret weapon, the sysconfig module. It's the Swiss Army knife of Python version info:

import sysconfig print(sysconfig.get_python_version()) print(sysconfig.get_config_var('py_version_nodot'))

This gives you the most comprehensive details you probably never thought you needed.

The terminal quickie

For when you're 'on the outside' and need a quick check of the Python version:

python --version

Or if you're hanging out in a Jupyter notebook, the command is:

!python --version

A simple and neat trick that’s also OS-agnostic. Faster than the Flash!

Your environment – such as the operating system or Python distribution – matters when you are retrieving the Python version:

  1. With virtual environments:

    import platform print(platform.python_version())
  2. In containerized applications: Consider checking the Docker image tag for the Python version.

  3. For build details:

    print(sys.version.split()[0], "built on:", sys.version.split()[1])

Now you are ready to sail through all sorts of weather conditions!

Simplicity at its best

For a quick and simple version check without unnecessary guff, use the platform method:

import platform print("Simple version: ", platform.python_version())

This is your minimalist buddy, always providing the gist.