Check if Python Package is installed

Check If Python Package Is Installed (1)

Sometimes when we need to use certain modules in our program, we forget whether we have it installed in our system or not. We can directly do this by importing the required module in our code but it will raise an "ImportError" which is not something that we desire.

We can also use python’s command line tool but that won’t help us to check our required package in our script.

Methods to Check if Python Package is Installed

There are many ways in which we can check our packages in python. Let us look at some of the easy ways in which we can make sure all our packages are available in our system before use.

Method 1: Using the importlib.util and sys modules

To check whether we have a specific module or library installed in our system, we can use the python library called importlib.util along with the sys (system) module.

The import library or the importlib module contains a function called find_spec() which is a shorter version of finding a specific module. The syntax of the function is

importlib.util.find_spec(filename or modulename, path(optional), target=None)

Let us take a look at how this can be done.

In my system I already have the numerical python or the numpy module installed. Hence for this example, I will check whether my code can correctly judge whether the module is present or not.

As for your need, please feel free to change the name of the module as per your requirements.

#importing importlib.util module
import importlib.util
#importing the system module
import sys

# For illustration
name = 'numpy'

#code to check if the library exists
if (spec := importlib.util.find_spec(name)) is not None:
    #displaying that the module is found
    print(f"{name!r} already in sys.modules")
    #importing the present module
    module = importlib.util.module_from_spec(spec)
    sys.modules[name] = module
    spec.loader.exec_module(module)
    #displaying that the module has been imported
    print(f"{name!r} has been imported")
#else displaying that the module is absent
else:
    print(f"can't find the {name!r} module")

The output will be:

'numpy' already in sys.modules
'numpy' has been imported
Importutil And Sys Modules
Importlib.util And Sys Modules

Also read: Convert an RGB image into grayscale using Matplotlib

Method 2: By using the os module

The os module can also be used to determine whether a particular library exists or not in our system. Let’s take a look at the same.

#importing the os module
import os
#opening the module list 
lst = os.popen('pip list')
#storing the list of pip modules 
pack_list = lst.read()
#formatting of the list
Detpack=list(pack_list.split(" "))
# setting counter
c = 0
for i in Detpack:
    if "numpy" in i:
        c = 1
        break
# Checking the value of counter
if c==1:
  print("Yay! Module is Installed")
else :
  print("Uh oh! Module is not installed")

Since in this code I am also checking the availability of numpy in my computer, the output should be the same as the previous example. The output is given below.

Yay! Module is Installed
Using The Os Module
Using The Os Module

Method 3: Exception Handling

This is the easiest method to check whether a package is installed or not. In this method we will use python’s built-in exception handling by using the try-except block. The try-except block just like its name suggests tries to perform an action defined by the user. When the execution of the user defined code in the try block fails, the except block handles it without the hassle of raising an error or an exception.

Lets look at how exception handling works in python. For this example, let’s use a library that I don’t have installed in my system, called, emoji. This is to check if the except condition handles error properly or not. Again feel free to change the name of the modules as per your wish.

try:
    #trying to import emoji 
    import emoji
    print("Module Already installed")
#handling exception if file not found
except ImportError as err:
    print("Error>>", err)

The output of the above code would be:

Error>> No module named 'emoji'
Exception Handling
Exception Handling

Note: To read about exception handling in python, read this awesome and thorough article on askpython!

List of installed packages

The following command line code can be used to get a precise list of all the python packages installed in our system.

pip list

The output will list all of the installed python modules in your system just like as shown below.

List Of All Packages
List Of All Packages

Summary

Checking whether are packages are properly stored and readily available is a must before importing them in our code. If you are unsure about a particular package installed your system, you can use any of the first three methods. To list all the available packages in your system use the fourth method. We hope you find your solution!