close

How to check if a module is installed in Python and, if not, install it within the code?

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to check if a module is installed in Python and, if not, install it within the code in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

How to check if a module is installed in Python and, if not, install it within the code?

  1. How to check if a module is installed in Python and, if not, install it within the code?

    The pip module has updated quite a lot since the time I posted this answer. I've updated the snippet with the proper way to install a missing dependency, which is to use subprocess and pkg_resources, and not pip.

  2. check if a module is installed in Python and, if not, install it within the code

    The pip module has updated quite a lot since the time I posted this answer. I've updated the snippet with the proper way to install a missing dependency, which is to use subprocess and pkg_resources, and not pip.

Method 1

The pip module has updated quite a lot since the time I posted this answer. I’ve updated the snippet with the proper way to install a missing dependency, which is to use subprocess and pkg_resources, and not pip.

To hide the output, you can redirect the subprocess output to devnull:

import sys
import subprocess
import pkg_resources

required = {'mutagen', 'gTTS'}
installed = {pkg.key for pkg in pkg_resources.working_set}
missing = required - installed

if missing:
    python = sys.executable
    subprocess.check_call([python, '-m', 'pip', 'install', *missing], stdout=subprocess.DEVNULL)

Method 2

If you want to know if a package is installed, you can check it in your terminal using the following command:

pip list | grep <module_name_you_want_to_check>

How this works:

pip list

lists all modules installed in your Python.

The vertical bar | is commonly referred to as a “pipe”. It is used to pipe one command into another. That is, it directs the output from the first command into the input for the second command.

grep <module_name_you_want_to_check>

finds the keyword from the list.

Example:

pip list| grep quant

Lists all packages which start with “quant” (for example “quantstrats”). If you do not have any output, this means the library is not installed.

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read