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

Viewed 146491

I would like to install the modules 'mutagen' and 'gTTS' for my code, but I want to have it so it will install the modules on every computer that doesn't have them, but it won't try to install them if they're already installed. I currently have:

def install(package):
    pip.main(['install', package])

install('mutagen')

install('gTTS')

from gtts import gTTS
from mutagen.mp3 import MP3

However, if you already have the modules, this will just add unnecessary clutter to the start of the program whenever you open it.

9 Answers

you can use simple try/except:

try:
    import mutagen
    print("module 'mutagen' is installed")
except ModuleNotFoundError:
    print("module 'mutagen' is not installed")
    # or
    install("mutagen") # the install function from the question

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.

You can check if a package is installed using pkg_resources.get_distribution:

import pkg_resources

for package in ['mutagen', 'gTTS']:
    try:
        dist = pkg_resources.get_distribution(package)
        print('{} ({}) is installed'.format(dist.key, dist.version))
    except pkg_resources.DistributionNotFound:
        print('{} is NOT installed'.format(package))

Note: You should not be directly importing the pip module as it is an unsupported use-case of the pip command.

The recommended way of using pip from your program is to execute it using subprocess:

subprocess.check_call([sys.executable, '-m', 'pip', 'install', 'my_package'])

Although @girrafish's answer might suffice, you can check package installation via importlib too:

import importlib

packages = ['mutagen', 'gTTS']
[subprocess.check_call(['pip', 'install', pkg]) 
for pkg in packages if not importlib.util.find_spec(pkg)]

If you would like to preview if a specific package (or some) are installed or not maybe you can use the idle in python. Specifically :

  1. Open IDLE
  2. Browse to File > Open Module > Some Module
  3. IDLE will either display the module or will prompt an error message.

Above is tested with python 3.9.0

You can run pip show package_name or for broad view use pip list Reference

Related