Thursday, December 26, 2024
Google search engine
HomeLanguagesHow to Check If Python Package Is Installed

How to Check If Python Package Is Installed

In this article, we are going to see how to check whether the python package is installed or not.

By 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 moves forward else move to except and print the error messge.

Python3




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


Output:

Error ->  No module named 'Module'

By using importlib package

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

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

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

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.

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

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.

Here is an example of how to use pkgutil.find_loader to check if a package is installed:

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).

RELATED ARTICLES

Most Popular

Recent Comments