Open In App

How to Check If Python Package Is Installed

Last Updated : 19 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we are going to see how to check if Python package is installed or not.

Check If Python Package is Installed

There are various methods to check if Python is installed or not, here we are discussing some generally used methods for Check If Python Package Is Installed or not which are the following.

  • By using Exception handling
  • By using importlib package
  • Using Importlib.Util Module
  • By using os module the
  • By using pkgutil module
  • By Using pkg_resources Module
  • Using Sys Modules in Python. 

Check if Python is Installed using Exception handling

In this method, we will use the try and except method. Under try, importing will be done. If the module is imported it will automatically move forward else move to except and print the error message.

In this example the below code attempts to import a module named “Module” and prints “Already installed” if successful; otherwise, it catches an ImportError and prints the specific error message.

Python3




try:
    import Module
    print("Already installed")
except ImportError as e:
    print("Error -> ", e)


Output:

Error ->  No module named 'Module'

Python Package Check By using importlib Package

importlib module in Python provides a flexible way to work with imports at runtime. To check if a specific module, such as “example_module,” is installed, you can use the find_loader function from importlib.util.

In this example, we try to import the ‘sys’ module using importlib.import_module. If the import is successful, it means that Python is installed, and the message “Python is installed.” is printed. If the import fails, it means that Python is not installed, and the message “Python is not installed.” is printed.

Python3




import importlib
 
def check_python_installation():
    try:
        importlib.import_module('sys')
        print("Python is installed.")
    except ImportError:
        print("Python is not installed.")
 
# Call the function to check Python installation
check_python_installation()


Output :

Python is installed

Check Python Package By using importlib.util Package

In this, find_spec returns the None is module is not found

Syntax: find_spec(fullname, path, target=None)

In this example the below code checks if a Python module named ‘Module’ is installed by using the `importlib.util.find_spec` function. If not installed, it prints a message indicating that ‘Module’ is not installed.

Python3




import importlib.util
 
# For illustrative purposes.
package_name = 'Module'
 
if importlib.util.find_spec(package_name) is None:
    print(package_name +" is not installed")


Output:

Module is not installed

Check if Python is Installed By using OS Module

Here we will execute pip list commands and store it into the list and then check the package is installed or not.

In this example the below code checks if the “opencv-python” package with version “0.46” is installed by running the ‘pip list’ command, parsing the output, and checking for a specific package version. It then prints whether the module is installed or not based on the result.

Python3




import os
 
stream = os.popen('pip list')
 
pip_list = stream.read()
 
Package=list(pip_list.split(" "))
# Count variable
c = 0
for i in Package:
    if "0.46\nopencv-python" in i:
        c = 1
 
# Checking the value of c
if c==1:
  print("Module Installed")
else :
  print("Module is not installed")


Output:

Module is not installed

Check if Python is Installed By using the pkgutil Module

One alternative approach to check if a Python package is installed is to use the pkgutil module. The pkgutil module provides utilities for working with packages, and specifically includes a find_loader function that can be used to check if a package is installed.

In this example the below code uses the `pkgutil` module to check if the ‘numpy’ package is installed in the Python environment and prints a corresponding message based on the result.

Python3




#import pkgutil
 
# Check if the 'example' package is installed
if pkgutil.find_loader('numpy') is not None:
    print("Package is installed")
else:
    print("Package is not installed")


Output:

Package is installed

Note that pkgutil.find_loader returns a ModuleLoader object if the package is installed, or None if it is not. Therefore, the condition in the if statement checks if the returned value is not None.

This approach has the advantage of being platform-agnostic and working for both Python 2 and Python 3. However, it does not provide information about where the package is installed or how it was installed (e.g. whether it was installed with pip or from a source distribution).

Python Package Check By using pkg_resources Module

To check if python package is installed using the pkg_resources module in Python, you can use the working_set attribute and the try-except block to handle the absence of the package

In this example in the below code the `is_package_installed` function checks if a given package is installed by attempting to get its distribution information using `pkg_resources.get_distribution`. It returns `True` if the package is found and `False` if not.

Python3




import pkg_resources
 
def is_package_installed(package_name):
    try:
        pkg_resources.get_distribution(package_name)
        return True
    except pkg_resources.DistributionNotFound:
        return False
 
# Example usage for checking if 'numpy' is installed
if is_package_installed('numpy'):
    print("numpy is installed")
else:
    print("numpy is not installed")


Output :

numpy is not installed  

Check Package using Sys Modules in Python

sys module in Python to check whether Python is installed or not. The sys module provides access to some variables used or maintained by the Python interpreter, including information about the Python installation

In this example Python script uses the `sys` module to check if Python is installed. If the `sys` module has the ‘version’ attribute, it prints “Python is installed” along with the Python version. Otherwise, it prints “Python is not installed.”

Python3




import sys
 
if hasattr(sys, 'version'):
    print("Python is installed.")
    print("Python version:", sys.version)
else:
    print("Python is not installed.")


Output :

Python is not installed


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads