How to check if package is installed python

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

Читайте также:  Ajax one to one chat in php

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:

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

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:

Источник

How to check if package is installed python

Last updated: Feb 23, 2023
Reading time · 3 min

banner

# Table of Contents

# Check if a Python package is installed

To check if a Python package is installed:

  1. Import the package in a try block.
  2. Use an except block to handle the potential ModuleNotFoundError .
  3. If the try block runs successfully, the module is installed.
Copied!
try: import requests print('The requests module is installed') except ModuleNotFoundError: print('The requests module is NOT installed')

check if python package is installed

We used a try/except block to check if a module is installed.

If the try block doesn’t raise an exception, the module is installed.

If the module isn’t installed, a ModuleNotFoundError error is raised and the except block runs.

# Installing the module if it isn’t already installed

You can also extend the try/except statement to install the module if it isn’t installed.

Copied!
import sys import subprocess try: import requests print('The requests module is installed') except ModuleNotFoundError: print('The requests module is NOT installed') # 👇️ optionally install module python = sys.executable subprocess.check_call( [python, '-m', 'pip', 'install', 'requests'], stdout=subprocess.DEVNULL ) finally: import requests

installing the module if it is not already installed

If you need to check if a package is installed using pip , use the pip show command.

check if module installed using pip

The pip show module_name command will either state that the package is not installed or show a bunch of information about the package, including the location where the package is installed.

You can also use the following one-liner command.

Copied!
python -c 'import pkgutil; print(1 if pkgutil.find_loader("module_name") else 0)'

Make sure to replace module_name with the actual name of the module you are checking for.

The command returns 1 if the module is installed and 0 if it isn’t but this can be easily adjusted.

# Check if a Python package is installed using find_spec

An alternative approach is to use the importlib.util.find_spec method.

The find_spec() method will return a spec object if the module is installed, otherwise, None is returned.

Copied!
import importlib.util module_name = 'requests' spec = importlib.util.find_spec(module_name) if spec: print(f'The module_name> module is installed') else: print(f'The module_name> module is NOT installed')

check if python package is installed using find spec

The importlib.util.find_spec method finds the spec for a module.

The spec for a module is a namespace containing the import-related information used to load the module.

If no spec is found, the method returns None.

# Installing the package if it isn’t already installed

You can optionally install the package if it isn’t already installed.

Copied!
import importlib.util import sys import subprocess module_name = 'requests' spec = importlib.util.find_spec(module_name) if spec: print(f'The module_name> module is installed') else: print(f'The module_name> module is NOT installed') # 👇️ optionally install the module if it's not installed python = sys.executable subprocess.check_call( [python, '-m', 'pip', 'install', 'requests'], stdout=subprocess.DEVNULL )

# Checking if the module isn’t installed

If you need to check if the module isn’t installed, check if the spec variable stores a None value.

Copied!
import importlib.util import sys import subprocess module_name = 'requests' spec = importlib.util.find_spec(module_name) if spec is None: print(f'The module_name> module is NOT installed') # 👇️ optionally install the module if it's not installed python = sys.executable subprocess.check_call( [python, '-m', 'pip', 'install', 'requests'], stdout=subprocess.DEVNULL ) print(f'The module_name> module is now installed')

Which approach you pick is a matter of personal preference. I’d use the try/except statement because I find it quite direct and easy to read.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

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" 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" has been imported") #else displaying that the module is absent else: print(f"can't find the module")
'numpy' already in sys.modules 'numpy' has been imported

Importutil And Sys Modules

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.

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

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.

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

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!

Источник

Оцените статью