TechBeamersTechBeamers
  • Learn ProgrammingLearn Programming
    • Python Programming
      • Python Basic
      • Python OOP
      • Python Pandas
      • Python PIP
      • Python Advanced
      • Python Selenium
    • Python Examples
    • Selenium Tutorials
      • Selenium with Java
      • Selenium with Python
    • Software Testing Tutorials
    • Java Programming
      • Java Basic
      • Java Flow Control
      • Java OOP
    • C Programming
    • Linux Commands
    • MySQL Commands
    • Agile in Software
    • AngularJS Guides
    • Android Tutorials
  • Interview PrepInterview Prep
    • SQL Interview Questions
    • Testing Interview Q&A
    • Python Interview Q&A
    • Selenium Interview Q&A
    • C Sharp Interview Q&A
    • PHP Interview Questions
    • Java Interview Questions
    • Web Development Q&A
  • Self AssessmentSelf Assessment
    • Python Test
    • Java Online Test
    • Selenium Quiz
    • Testing Quiz
    • HTML CSS Quiz
    • Shell Script Test
    • C/C++ Coding Test
Search
  • Python Multiline String
  • Python Multiline Comment
  • Python Iterate String
  • Python Dictionary
  • Python Lists
  • Python List Contains
  • Page Object Model
  • TestNG Annotations
  • Python Function Quiz
  • Python String Quiz
  • Python OOP Test
  • Java Spring Test
  • Java Collection Quiz
  • JavaScript Skill Test
  • Selenium Skill Test
  • Selenium Python Quiz
  • Shell Scripting Test
  • Latest Python Q&A
  • CSharp Coding Q&A
  • SQL Query Question
  • Top Selenium Q&A
  • Top QA Questions
  • Latest Testing Q&A
  • REST API Questions
  • Linux Interview Q&A
  • Shell Script Questions
© 2024 TechBeamers. All Rights Reserved.
Reading: How to Check Python Version Using Code
Font ResizerAa
TechBeamersTechBeamers
Font ResizerAa
  • Python
  • SQL
  • C
  • Java
  • Testing
  • Selenium
  • Agile
  • Linux
  • MySQL
  • Python Quizzes
  • Java Quiz
  • Testing Quiz
  • Shell Script Quiz
  • WebDev Interview
  • Python Basic
  • Python Examples
  • Python Advanced
  • Python OOP
  • Python Selenium
  • General Tech
Search
  • Programming Tutorials
    • Python Tutorial
    • Python Examples
    • Java Tutorial
    • C Tutorial
    • MySQL Tutorial
    • Selenium Tutorial
    • Testing Tutorial
  • Top Interview Q&A
    • SQL Interview
    • Web Dev Interview
  • Best Coding Quiz
    • Python Quizzes
    • Java Quiz
    • Testing Quiz
    • ShellScript Quiz
Follow US
© 2024 TechBeamers. All Rights Reserved.
Python BasicPython TutorialsTechnology

How to Check Python Version Using Code

Last updated: Nov 28, 2023 11:14 pm
By Harsh S.
Share
7 Min Read
Check Python Version Using Code
SHARE

Do you know how to check the Python version you are using? This tutorial provides you with 10 different ways to check the Python version. Now, you may ask why use code and 10 different methods. It is because we are programmers and we like our code to do the tasks. It is not only easy and simple but also creative.

Contents
1. Using the platform module2. Using the sys module3. Using the subprocess module to check the Python version4. Using the pkg_resources module5. Using the __version__ attribute to check the Python version6. Using the python3 command-line tool7. Using sysconfig module and os.path.join8. Using the PYTHONHOME environment variable9. Using the sys.executable attribute10. Using the site module to check the Python version

However, let’s not leave the most basic way which is to use the terminal to check the Python version. You just need to issue the following command to show the Python version:

Use terminal to check python version

Different Ways to Check Python Version with Full Code

Now, review the 10 different methods to check the Python version with fully working code examples. You may reuse the code, and add it to your DevOps scripts, or in your applications.

1. Using the platform module

The platform module is a built-in module that provides information about the underlying platform, including the Python version. Here’s a simple example to check the Python version:

import platform

python_version = platform.python_version()
print(python_version)

This code will print the Python version, for example:

3.10.13

2. Using the sys module

The sys module is a built-in module that provides access to system-specific parameters and functions, and it contains a version attribute that holds the Python version. Here’s a simple example:

import sys

python_version = sys.version
print(python_version)

This code shows the Python version, including the release level and serial number. For instance:

3.10.13 (main, Mar 14 2023, 23:21:36) [1] 64-bit

3. Using the subprocess module to check the Python version

The subprocess module lets you run shell commands. You can use it to execute the ‘python’ command-line tool and retrieve the Python version.

import subprocess

process = subprocess.Popen(['python3', '--version'], stdout=subprocess.PIPE)
output, _ = process.communicate()
python_version = output.decode('utf-8').strip()
print(python_version)

This code prints the Python version. For instance:

Python 3.10.13

4. Using the pkg_resources module

The pkg_resources module helps access details about installed packages. You can use it to fetch the version of the matplotlib package, which aligns with the Python version.

import pkg_resources

matplotlib_version = pkg_resources.get_distribution('matplotlib').version
print("Matplotlib version:", matplotlib_version)

This code will print the Python version, for example:

3.5.1

5. Using the __version__ attribute to check the Python version

The __version__ attribute is a common attribute of Python modules, including the matplotlib module itself. This method can be used to access the Python version directly from the module.

import matplotlib

matplotlib_version = matplotlib.__version__
print("Python version:", matplotlib_version)

This code will print the Python version, for example:

3.5.1

6. Using the python3 command-line tool

The python3 command-line tool can be used to execute Python scripts. This method can be used to get the Python version by running the python3 command with the --version flag.

import os

command = 'python3 --version'
output = os.popen(command).read()
python_version = output.strip()
print(python_version)

This code lists the current Python version, for example:

Python 3.10.6

7. Using sysconfig module and os.path.join

We can also check the Python version by combining sysconfig and os.path.join. Let’s display the Python version and the executable path.

import sysconfig
import os

try:
    print("Python version")
    print(sysconfig.get_python_version())
    
    executable_path = sysconfig.get_path('executable')
    if executable_path:
        print("Executable path")
        print(os.path.realpath(executable_path))
except KeyError:
    pass  # Do nothing if 'executable' key is not present
except Exception as e:
    print(f"An unexpected error occurred: {e}")

This code will print the Python version, for example:

Python 3.10

8. Using the PYTHONHOME environment variable

The PYTHONHOME environment variable specifies the location of the Python installation. This method can be used to get the Python version by extracting the version number from the path to the Python executable.

import sys

python_version = sys.version.split(' ')[0]
print("Python version:", python_version)

This code will print the Python version, for example:

Python version: 3.10.6

9. Using the sys.executable attribute

The sys.executable attribute contains the path to the Python executable. This method can be used to get the Python version by extracting the version number from the path to the Python executable.

import sys
import re

python_executable = sys.executable

# Extract Python version from the executable path using regex
match = re.search(r'python(\d+(\.\d+)*)', python_executable)
python_version = match.group(1) if match else "Unknown"

print("Python version:", python_version)

This code will print the Python version, for example:

3

10. Using the site module to check the Python version

The site module provides access to site-specific Python configuration. This method can be used to get the path to the Python installation, which can then be used to extract the Python version.

import site
import sys
import platform

# Get the site-packages path
python_path = site.getsitepackages()[0]

# Extract Python version from the path
python_version = python_path.split('/')[-1]

# Print Python version
print(f"Python version: {python_version}")

# Additional information using sys and platform
print(f"Python version (sys): {sys.version}")
print(f"Python version (platform): {platform.python_version()}")

This code will print the Python version, for example:

Python version: dist-packages
Python version (sys): 3.10.6 (main, Nov 14 2022, 16:10:14) [GCC 11.3.0]
Python version (platform): 3.10.6

Conclusion

We hope you would have got the desired help from the above code examples. The purpose of this tutorial is also to show how easily you can achieve the same thing in many different ways. Also, Python has a vast set of features that we want you to explore. Once you are aware of a technique it is much easier to use it somewhere else as well. Just be mindful of the pros and cons of each approach before using it.

Happy Coding!

You Might Also Like

How to Connect to PostgreSQL in Python

Generate Random IP Address (IPv4/IPv6) in Python

Python Remove Elements from a List

Selenium Python Extent Report Guide

How to Fix Load CSS Asynchronously

Sign Up For Daily Newsletter

Be keep up! Get the latest breaking news delivered straight to your inbox.
Loading
By signing up, you agree to our Terms of Use and acknowledge the data practices in our Privacy Policy. You may unsubscribe at any time.
Harsh S. Avatar
By Harsh S.
Follow:
Hello, I'm Harsh, I hold a degree in Masters of Computer Applications. I have worked in different IT companies as a development lead on many large-scale projects. My skills include coding in multiple programming languages, application development, unit testing, automation, supporting CI/CD, and doing DevOps. I value Knowledge sharing and want to help others with my tutorials, quizzes, and exercises. I love to read about emerging technologies like AI and Data Science.
Previous Article Find Length of Python List How to Find the Length of a List in Python
Next Article Cracking coding interview guide Cracking the Coding Interview: How a Young Girl Succeeded

Popular Tutorials

SQL Interview Questions List
50 SQL Practice Questions for Good Results in Interview
SQL Interview Nov 01, 2016
Demo Websites You Need to Practice Selenium
7 Sites to Practice Selenium for Free in 2024
Selenium Tutorial Feb 08, 2016
SQL Exercises with Sample Table and Demo Data
SQL Exercises – Complex Queries
SQL Interview May 10, 2020
Java Coding Questions for Software Testers
15 Java Coding Questions for Testers
Selenium Tutorial Jun 17, 2016
30 Quick Python Programming Questions On List, Tuple & Dictionary
30 Python Programming Questions On List, Tuple, and Dictionary
Python Basic Python Tutorials Oct 07, 2016
//
Our tutorials are written by real people who’ve put in the time to research and test thoroughly. Whether you’re a beginner or a pro, our tutorials will guide you through everything you need to learn a programming language.

Top Coding Tips

  • PYTHON TIPS
  • PANDAS TIPSNew
  • DATA ANALYSIS TIPS
  • SELENIUM TIPS
  • C CODING TIPS
  • GDB DEBUG TIPS
  • SQL TIPS & TRICKS

Top Tutorials

  • PYTHON TUTORIAL FOR BEGINNERS
  • SELENIUM WEBDRIVER TUTORIAL
  • SELENIUM PYTHON TUTORIAL
  • SELENIUM DEMO WEBSITESHot
  • TESTNG TUTORIALS FOR BEGINNERS
  • PYTHON MULTITHREADING TUTORIAL
  • JAVA MULTITHREADING TUTORIAL

Sign Up for Our Newsletter

Subscribe to our newsletter to get our newest articles instantly!

Loading
TechBeamersTechBeamers
Follow US
© 2024 TechBeamers. All Rights Reserved.
  • About
  • Contact
  • Disclaimer
  • Privacy Policy
  • Terms of Use
TechBeamers Newsletter - Subscribe for Latest Updates
Join Us!

Subscribe to our newsletter and never miss the latest tech tutorials, quizzes, and tips.

Loading
Zero spam, Unsubscribe at any time.
x