How to Check Python Version in Linux
Python is an essential programming language for Linux users, whether you’re a developer, system administrator, or data scientist. Knowing which Python version you’re working with is crucial for ensuring compatibility with libraries, frameworks, and scripts. This comprehensive guide will walk you through various methods to check and manage Python versions in Linux, from basic commands to advanced version management techniques.
Introduction
Linux distributions often come with Python pre-installed, serving as a critical component for many system tools and applications. As Python evolves, different versions coexist, with Python 2 and Python 3 being fundamentally different and not fully compatible with each other. This makes knowing your Python version essential before starting any project or troubleshooting issues.
Python version verification becomes particularly important when:
- Installing new packages with specific version requirements
- Running scripts developed for specific Python versions
- Configuring development environments
- Deploying applications to production servers
- Troubleshooting compatibility issues
In this guide, we’ll explore multiple methods to check Python versions in Linux, from simple command-line techniques to programmatic approaches using Python’s built-in modules. We’ll also cover managing multiple Python versions and best practices for version verification in various scenarios.
Understanding Python Versioning in Linux
Before diving into the commands, it’s essential to understand how Python versioning works in Linux environments.
Python 2 vs Python 3
Python 2 and Python 3 represent different branches of the language, with Python 3 introducing significant changes that are not backward compatible. Although Python 2 reached its end of life on January 1, 2020, many legacy systems and scripts still use it.
Python Version Numbering System
Python follows a semantic versioning system with three main components:
- Major version: Indicates significant changes with potential compatibility issues (e.g., Python 2 vs Python 3)
- Minor version: Introduces new features while maintaining backward compatibility (e.g., Python 3.8 vs Python 3.9)
- Micro version: Contains bug fixes and minor improvements (e.g., Python 3.8.5 vs Python 3.8.6)
For example, in Python 3.8.5:
- 3 is the major version
- 8 is the minor version
- 5 is the micro version
Default Python Configurations in Linux Distributions
Different Linux distributions handle Python installations differently:
- Ubuntu and many Debian-based distributions maintain separate
python
(Python 2) andpython3
(Python 3) commands - Newer distributions like Fedora and Arch Linux often use
python
to refer to Python 3 - Some distributions may have multiple Python versions installed to support system applications
Understanding your distribution’s approach to Python versioning will help you correctly identify and manage Python installations on your system.
Basic Command Line Methods
The command line provides the quickest and simplest way to check your Python version in Linux. Here are several methods you can use.
Using the python --version
Command
The most straightforward way to check your Python version is with the --version
flag:
python --version
This command will display output similar to:
Python 2.7.18
Many modern Linux distributions map python
to Python 2 by default, so you might need to use python3
to check your Python 3 installation.
Using the python3 --version
Command
To specifically check your Python 3 version:
python3 --version
This will output something like:
Python 3.8.10
Using Short Flag Alternatives
You can also use the short flag -V
to achieve the same result:
python -V
python3 -V
These commands produce the same version information but in a more concise format.
Detailed Version Information with -VV
For more detailed version information, including build details, you can use the -VV
flag (available in Python 3.6 and newer):
python3 -VV
This provides additional information about the Python build, which can be helpful for troubleshooting platform-specific issues:
Python 3.8.10 (default, May 26 2023, 13:12:25)
[GCC 9.4.0]
Checking if Python is Installed
If you’re unsure whether Python is installed on your system, running the version command will either return the version number or a “command not found” error, indicating Python isn’t installed or isn’t in your PATH.
Using the Python Interpreter for Version Checking
Another approach to check your Python version is through the Python interpreter itself. This method is particularly useful when you’re already working within Python’s interactive environment.
Starting the Python Interactive Shell
Open a terminal and start the Python interpreter by typing:
python
or
python3
Checking Version in the Interactive Shell
Once in the Python shell (indicated by the >>>
prompt), you can check the version using the sys
module:
import sys
print(sys.version)
This will display detailed version information, including build date and compiler details:
3.8.5 (default, Sep 4 2020, 07:30:14)
[GCC 7.3.0]
Exiting the Python Shell
After checking the version, you can exit the Python shell by typing:
exit()
or pressing Ctrl+D.
Using the interpreter method is advantageous when you want to verify which specific Python environment is active, especially when working with virtual environments or when multiple Python versions are installed on your system.
Comprehensive Version Information with Python Modules
For more detailed version information or when you need to check the Python version programmatically, you can use Python’s built-in modules.
Using the sys
Module
The sys
module provides comprehensive version information through different attributes:
sys.version
String
The sys.version
attribute returns a string containing the complete version information:
import sys
print(sys.version)
Output:
3.8.5 (default, Sep 4 2020, 07:30:14)
[GCC 7.3.0]
This string includes the version number, build date, and compiler information.
sys.version_info
Tuple
For structured version information, you can use sys.version_info
:
import sys
print(sys.version_info)
Output:
sys.version_info(major=3, minor=8, micro=5, releaselevel='final', serial=0)
This returns a named tuple with individual components of the version number.
Accessing Individual Version Components
You can access specific components of the version information:
import sys
print(f"Major version: {sys.version_info.major}")
print(f"Minor version: {sys.version_info.minor}")
print(f"Micro version: {sys.version_info.micro}")
Output:
Major version: 3
Minor version: 8
Micro version: 5
This approach is particularly useful in scripts where you need to check for compatibility with specific Python versions or features.
Platform Module for Version Checking
The platform
module offers another way to retrieve Python version information, with functions specifically designed for version checking.
Using platform.python_version()
The python_version()
function returns a string containing the version number:
import platform
print(platform.python_version())
Output:
3.8.5
This method returns just the version number without additional build information, making it cleaner for display purposes.
Using platform.python_version_tuple()
For structured version information similar to sys.version_info
, you can use:
import platform
version_tuple = platform.python_version_tuple()
print(f"Major: {version_tuple[0]}")
print(f"Minor: {version_tuple[1]}")
print(f"Micro: {version_tuple[2]}")
Output:
Major: 3
Minor: 8
Micro: 5
When to Use Platform vs Sys Module
- Use the
sys
module when you need detailed build information or when working directly with Python internals - Use the
platform
module when you just need version numbers or when writing cross-platform code that also checks other system information
Both modules are part of Python’s standard library, so no additional installation is required.
Creating a Version Check Script
Creating a reusable script for version checking can be useful for deployment, compatibility verification, or system administration.
Basic Version Check Script
Here’s a simple script that checks the Python version and verifies if it meets minimum requirements:
#!/usr/bin/env python3
import sys
def check_python_version(min_major=3, min_minor=6):
"""Check if the Python version meets minimum requirements."""
major = sys.version_info.major
minor = sys.version_info.minor
if major < min_major or (major == min_major and minor < min_minor):
print(f"Python {major}.{minor} detected.")
print(f"This script requires Python {min_major}.{min_minor} or higher.")
return False
else:
print(f"Python {major}.{minor} detected - requirements satisfied.")
return True
if __name__ == "__main__":
# Check for Python 3.6+
if not check_python_version(3, 6):
sys.exit(1)
# Continue with the rest of your script
print("Script continuing...")
Save this as check_version.py
, make it executable with chmod +x check_version.py
, and then run it with ./check_version.py
.
Including Version Checks in Larger Scripts
For larger applications, you can include version checks at the beginning of your main script:
import sys
# Check Python version before importing other modules
if sys.version_info < (3, 6):
print("This script requires Python 3.6 or higher.")
print(f"You are using Python {sys.version_info.major}.{sys.version_info.minor}")
sys.exit(1)
# Continue with imports and script execution
import some_module
# Rest of your code...
This approach prevents your script from running in incompatible environments and provides clear feedback to users.
Checking Python Version in Bash Scripts
When automation involves both Bash and Python, you might need to check the Python version within your Bash scripts.
Creating a Bash Wrapper
Here’s how to check Python version in a Bash script:
#!/bin/bash
# Check if Python is installed
if ! command -v python3 &>/dev/null; then
echo "Python 3 is not installed. Please install it and try again."
exit 1
fi
# Get Python version
python_version=$(python3 -c "import sys; print(f'{sys.version_info.major}.{sys.version_info.minor}')")
# Check if version meets requirements
required_version="3.6"
if [ "$(printf '%s\n' "$required_version" "$python_version" | sort -V | head -n1)" != "$required_version" ]; then
echo "Python version $python_version is too old. Version $required_version or higher is required."
exit 1
fi
echo "Python version $python_version is acceptable."
# Continue with the rest of your script
# ...
Storing Python Version in Bash Variables
To store and use the Python version in Bash variables:
#!/bin/bash
# Get major version
py_major=$(python3 -c "import sys; print(sys.version_info.major)")
# Get minor version
py_minor=$(python3 -c "import sys; print(sys.version_info.minor)")
echo "Found Python $py_major.$py_minor"
# Use these variables in conditional logic
if [ "$py_major" -eq 3 ] && [ "$py_minor" -ge 6 ]; then
echo "Python version is suitable for this script."
else
echo "This script requires Python 3.6 or higher."
exit 1
fi
These Bash scripts can be especially useful for deployment scripts or system setup automation where you need to ensure the correct Python version before proceeding.
Managing Multiple Python Versions
Many Linux systems have multiple Python versions installed simultaneously. Here’s how to manage them effectively.
Finding All Python Installations
To locate all Python installations on your system:
which python python2 python3
whereis python
For a more comprehensive search:
find /usr -name "python*" -type f -executable | grep -E "/python[0-9.]*$"
Understanding Symbolic Links
In most Linux distributions, python
and python3
are symbolic links to specific Python versions:
ls -l $(which python python3)
This command shows where these symlinks point to, helping you understand which version is used by default.
Setting a Specific Version as Default
While not recommended for system-wide changes (as it might break system tools), you can create aliases in your shell configuration:
# Add to ~/.bashrc or ~/.zshrc
alias python='/usr/bin/python3.8'
A safer approach is to use virtual environments or version managers like pyenv, which we’ll discuss next.
Virtual Environments and Version Control
Virtual environments allow you to create isolated Python environments with specific versions and packages, preventing conflicts between projects.
Creating Virtual Environments with venv
Python 3.3+ includes the venv
module for creating virtual environments:
# Create a virtual environment
python3 -m venv myenv
# Activate it
source myenv/bin/activate
# Check Python version in the environment
python --version
When activated, the python
command will use the version specified during environment creation, regardless of the system default.
Using virtualenv for Older Python Versions
For more flexibility, especially with older Python versions:
# Install virtualenv
pip install virtualenv
# Create environment with specific Python version
virtualenv -p /usr/bin/python3.8 myenv
# Activate it
source myenv/bin/activate
Virtual environments are the recommended way to manage project-specific Python versions and dependencies without affecting the system Python installation.
Advanced Version Management with External Tools
For more sophisticated Python version management, dedicated tools offer greater flexibility and control.
Using pyenv for Version Management
Pyenv is a powerful tool that allows you to install and switch between multiple Python versions easily:
# Install pyenv
curl https://pyenv.run | bash
# Add to ~/.bashrc
export PATH="$HOME/.pyenv/bin:$PATH"
eval "$(pyenv init --path)"
eval "$(pyenv virtualenv-init -)"
# Install a specific Python version
pyenv install 3.8.10
# Set global Python version
pyenv global 3.8.10
# Set local version for a project
cd myproject
pyenv local 3.7.9
Using Anaconda for Scientific Computing
Anaconda is popular in data science and provides its own environment manager:
# Create environment with specific Python version
conda create -n myenv python=3.8
# Activate environment
conda activate myenv
# Check Python version
python --version
These tools are invaluable for developers working on multiple projects with different Python version requirements.
Troubleshooting Common Version Issues
When working with Python in Linux, you might encounter several common issues related to version management.
Resolving “Command Not Found” Errors
If Python commands aren’t recognized, check if Python is installed and in your PATH:
which python3
echo $PATH
To fix PATH issues, add Python’s location to your PATH:
# Add to ~/.bashrc
export PATH="/usr/bin:$PATH"
Then reload your configuration:
source ~/.bashrc
Handling Conflicting Python Installations
When multiple Python versions conflict:
- Identify all installed versions:
ls -la /usr/bin/python*
- Check which version each command points to:
python --version python3 --version
- Use specific version executables when needed:
python3.8 script.py
Fixing Symbolic Link Issues
If symbolic links point to the wrong Python version:
# Check the current link
ls -l /usr/bin/python3
# Create a new link (requires sudo)
# sudo ln -sf /usr/bin/python3.8 /usr/bin/python3
Note: Modifying system symbolic links can break system tools. Use virtual environments or pyenv instead for personal projects.
Best Practices for Python Version Verification
Follow these best practices to avoid version-related issues in your Python projects:
Document Version Requirements
Always specify Python version requirements in your project documentation and setup files:
# In setup.py
setup(
# ...
python_requires='>=3.6',
# ...
)
Or in a requirements.txt or README file:
Python 3.6 or higher is required.
Include Version Checks in Scripts
Add version checks at the beginning of important scripts to prevent compatibility issues:
import sys
assert sys.version_info >= (3, 6), "Python 3.6+ required"
Use Virtual Environments Consistently
Create a new virtual environment for each project to isolate dependencies and Python versions. This prevents conflicts and makes your development environment reproducible.
Maintain Compatibility Testing
If your code needs to support multiple Python versions, test it against all target versions using tools like tox or CI/CD pipelines.