How to check if a Python package is installed?
In this article, we will see how to check if a python package is installed or not.
Using Exception Handling
In this method, we will use the try and exclude method. When you try, the import will be executed. If the module is imported it will automatically move forward, otherwise jump to the exception and print an error message.
try:
import Module
print("Already installed")
except ImportError as e:
print("Error -> ", e)
output:
Error -> No module named 'Module'
Using the importlib package
In this case, find_spec returns None if the module is not found.
Syntax: find_spec(fullname, path, target=None)
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
Using the OS module
Here we will execute the pip list commands and store them in a list and then check if the package is installed or not.
import os
stream = os.popen('pip list')
pip_list = stream.read()
Package=list(pip_list.split(" "))
# Count variable
c =
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