How to check if a Python package is installed

In this tutorial, we will learn about how to check if a Python package is installed in your local machine running Python or not.

We need to know how to import them as well as how to check if they are installed or not.

Checking for installed Python packages

A Python package is a group of modules and smaller packages. A Python package must always have an __init__.py file in it. There are many methods to check if a Python package is installed or not. Three of them are discussed below:-

  • Using the import statement.
  • Pip without importing the package.
  • The importlib.util module

Using the import keyword in Python

One way to know if a package is installed or not is by simply importing it. If it is installed, it won’t show any error. On the other hand, if it is not installed, there will be an import error shown. Another way is to use exception handling to do the same thing. A simple code for the same is given below.

try:
    import pandas
except ImportError as err:
    print(err)

If pandas is not installed we will get the following output

No module named 'pandas'

If on the other hand, pandas is installed, no error will be shown.

Pip without importing the package in Python

Another way to know if a package is installed is by using the command pip freeze in the terminal. Doing so will give you a list of all the installed packages. In order to search for a particular package, one can use the grep command in Linux terminal as shown in the following line of code:

pip freeze | grep numpy

The output, if NumPy is present is as follows:-

numpy==1.18.1.

If NumPy is not installed the terminal will give no output. For windows instead of using grep, we can use findstr which searches for a particular word in the given list just like grep in Linux.

Using importlib.util module of Python to check for installed packages

A package by the name of importlib has a module called util which has a function called find_spec which can also help to find if a package is installed or not without importing the package. The find_spec module will look for the package and if not present, it will return null. The code for the same is as follows:-

import importlib.util 
def main():
    package= 'tensorflow'

    is_present = importlib.util.find_spec(package) #find_spec will look for the package
    if is_present is None:
        print(package_name +" is not installed")
    else:
        print ("Successfull")

if __name__=='__main__':
    main()

If TensorFlow is not installed the output will be as follows:-

tensorflow is not installed.

See Also:

Leave a Reply

Your email address will not be published.