Question

Check the Python Version Running Your Script

pythonversion

Question

How can I determine which version of the Python interpreter is currently running my script?

If you need to identify the exact Python executable rather than its version—for example, when debugging a pip installation issue or checking whether a virtual environment is active—use sys.executable.

Short Answer

You will learn how to inspect the Python version from inside a running program. You will also learn the difference between the interpreter's version, its executable path, and the recommended way to write version-dependent code.

Concept

Python code runs inside a Python interpreter. The interpreter has a version such as Python 3.10.12 or Python 3.12.2.

A script can inspect the interpreter that launched it at runtime. This is useful when:

  • A program requires a minimum Python version.
  • You are debugging differences between your terminal, IDE, CI server, and production environment.
  • A package behaves differently across Python versions.
  • You need to choose a compatible implementation.

Python exposes this information through the built-in sys module:

  • sys.version_info provides structured version fields and is best for comparisons.
  • sys.version provides a human-readable descriptive string.
  • sys.executable provides the path to the interpreter executable, which answers a different but commonly related question.

For program logic, prefer sys.version_info because it is structured data rather than text that must be parsed.

Mental Model

Think of the Python interpreter as the engine running your script.

  • sys.version_info is the engine's specification sheet: major version, minor version, and patch level are separate fields.
  • sys.version is the label printed on the engine: useful for people, but less convenient for program decisions.
  • sys.executable is the engine's location: it tells you which installed Python program started the script.

If you need to decide whether the engine is new enough, use the specification sheet (sys.version_info), not the printed label.

Take Quiz

Syntax and Examples

Import sys and inspect sys.version_info:

import sys

print(sys.version_info)
print(sys.version_info.major)
print(sys.version_info.minor)
print(sys.version_info.micro)

A typical result might look like:

sys.version_info(major=3, minor=12, micro=2, releaselevel='final', serial=0)
3
12
2

To display a short, readable version number:

import sys

version = f"{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}"
print(version)

For a complete descriptive string, use sys.version:

import sys

print(sys.version)

This can include build and compiler details, so it is mainly useful for diagnostic output.

To check whether the running interpreter is at least Python 3.10:

import sys

if sys.version_info < (3, 10):
    raise RuntimeError("This program requires Python 3.10 or later.")

print("Supported Python version detected.")

Tuples compare item by item, so (3, 12) is greater than (3, 10).

Step by Step Execution

Consider this script:

import sys

required_version = (3, 10)
current_version = sys.version_info[:2]

print(f"Running Python {current_version[0]}.{current_version[1]}")

if current_version < required_version:
    print("Please upgrade Python.")
else:
    print("Python version is supported.")

Suppose the script runs on Python 3.12.2:

  1. import sys loads Python's standard system-information module.
  2. required_version stores the minimum acceptable major and minor version: (3, 10).
  3. sys.version_info contains all version fields. [:2] selects only major and minor, producing (3, 12).
  4. The script prints Running Python 3.12.
  5. Python compares (3, 12) with (3, 10).
  6. Since 12 is greater than 10, the condition is false.
  7. The else branch runs and prints Python version is supported.

Using only the first two fields is often appropriate when your requirement is based on a language release such as Python 3.10 or later.

Real World Use Cases

  • Command-line tools: Print version details in a --debug command to help users report environment problems.
  • Library compatibility: Reject unsupported interpreter versions with a clear error before using unavailable syntax or standard-library features.
  • Automated tests: Log the Python version in CI output when a test passes on one version but fails on another.
  • Deployment troubleshooting: Confirm whether a web service is running the intended Python release.
  • Data scripts: Record the Python version alongside generated results to make an analysis easier to reproduce.

For environment troubleshooting, include both the version and executable path:

import sys

print("Python version:", sys.version)
print("Python executable:", sys.executable)

The version tells you what release is running; the executable tells you which installation or virtual environment is running it.

Take Quiz

Real Codebase Usage

In production code, version checks are usually kept small and placed near the program entry point.

Fail early for unsupported versions

import sys

MINIMUM_PYTHON = (3, 10)

if sys.version_info < MINIMUM_PYTHON:
    found = ".".join(map(str, sys.version_info[:3]))
    required = ".".join(map(str, MINIMUM_PYTHON))
    raise SystemExit(f"Python {required}+ is required; found Python {found}.")

This is a guard clause: the program stops immediately when it cannot run safely.

Add diagnostics when handling errors

import sys
import traceback

try:
    result = 10 / 0
except ZeroDivisionError:
    print("Python executable:", sys.executable)
    print("Python version:", sys.version)
    traceback.print_exc()

This pattern can make bug reports more actionable.

Prefer feature checks when possible

When the real requirement is whether an object or API exists, checking the feature can be more flexible than checking a version:

from pathlib import Path

path = Path("report.txt")

if hasattr(path, "read_text"):
    print(path.read_text())

However, if your project officially supports only certain Python releases, an explicit sys.version_info requirement remains clear and appropriate.

Common Mistakes

Parsing sys.version for comparisons

This is fragile because sys.version is a descriptive string, not a version-comparison API.

import sys

# Avoid this.
if sys.version >= "3.10":
    print("Supported")

String comparisons can produce surprising results. For example, text such as "3.9" can compare differently from numerical version values. Use sys.version_info instead:

import sys

if sys.version_info >= (3, 10):
    print("Supported")

Comparing only the major version

import sys

# Too broad when Python 3.10+ is required.
if sys.version_info.major == 3:
    print("Supported")

Python 3.7 and Python 3.12 both have major version 3. Include the minor version:

if sys.version_info >= (3, 10):
    print("Supported")

Confusing the version with the interpreter path

import sys

print(sys.version)      # Version and build information
print(sys.executable)   # File path of the interpreter

Use sys.executable when diagnosing the active virtual environment or an unexpected pip installation.

Assuming python --version always matches your script

A terminal command checks the python found on that terminal's PATH. An IDE, scheduled task, or service may launch your script with another interpreter. Checking from inside the script is authoritative for that running process.

Forgetting the Python version used by pip

When installing packages, use:

python -m pip install package-name

This runs pip with the same python command, reducing the chance of installing into a different environment.

Comparisons

Tool or valueWhat it tells youBest use
sys.version_infoStructured major, minor, micro, and release fieldsVersion comparisons and program logic
sys.versionA detailed human-readable version/build stringDiagnostics and bug reports
platform.python_version()A version string such as "3.12.2"Displaying a concise version string
sys.executablePath of the interpreter executableDebugging virtual environments and multiple installations
python --versionVersion of the python command in the current shellQuick terminal checks

platform.python_version() is valid for display:

import platform

print(platform.python_version())

But sys.version_info is usually better when your code needs to compare versions because it avoids converting text into version parts.

Take Quiz

Cheat Sheet

import sys

# Structured version information
print(sys.version_info)

# Individual fields
print(sys.version_info.major)
print(sys.version_info.minor)
print(sys.version_info.micro)

# Compare against a minimum version
if sys.version_info >= (3, 10):
    print("Python 3.10 or newer")

# Major and minor tuple
print(sys.version_info[:2])  # for example: (3, 12)

# Detailed diagnostic string
print(sys.version)

# Interpreter path / active environment
print(sys.executable)

Rules to remember:

  • Use sys.version_info for conditions and comparisons.
  • Use sys.version for detailed diagnostic text.
  • Use sys.executable to identify the actual interpreter installation.
  • Prefer python -m pip to ensure pip belongs to the selected python command.

FAQ

How do I print the Python version in a script?

import sys
print(sys.version)

For a shorter version number, format sys.version_info.

What is the best way to compare Python versions?

Use sys.version_info with a tuple:

if sys.version_info >= (3, 10):
    print("Compatible")

How do I find the Python executable running my script?

Use:

import sys
print(sys.executable)

This is especially useful for confirming an active virtual environment.

Is sys.version the same as sys.version_info?

No. sys.version is a descriptive string. sys.version_info is a structured value designed for accessing and comparing version components.

Why does my terminal show a different Python version than my script?

Your IDE, virtual environment, service, or task runner may use a different interpreter. Print sys.executable and sys.version from inside the script to identify the interpreter actually running it.

Can I check for exactly Python 3.12?

Yes, but exact checks are uncommon unless necessary:

import sys

if sys.version_info[:2] == (3, 12):
    print("Running Python 3.12")

Usually, checking a minimum supported version is more useful.

Take Quiz

Mini Project

Description

Create a small environment-report script. It prints the Python version and interpreter location, then exits with a helpful message if the running version is older than the version your program supports. This is useful as a diagnostic command in command-line tools and deployment scripts.

Goal

Build a script that reports its interpreter details and requires Python 3.10 or later.

Requirements

Create a file named environment_report.py.

Import the sys module.

Print the major, minor, and micro Python version.

Print the interpreter path currently running the script.

Exit with a clear error message when the interpreter is older than Python 3.10.

Take Quiz

Keep learning

Related questions

View more