Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 562
Gameskiller01 Avatar asked May 26 '17 22:05

Gameskiller01


People also ask

How do I know if a Python module is installed or not?

To check all the installed Python modules, we can use the following two commands with the 'pip': Using 'pip freeze' command. Using 'pip list command.

How do I find out where a Python module is installed?

You can manually go and check the PYTHONPATH variable contents to find the directories from where these built in modules are being imported. Running "python -v"from the command line tells you what is being imported and from where. This is useful if you want to know the location of built in modules.

How do I use a Python module without installing it?

If you are not able to install modules on a machine(due to not having enough permissions), you could use either virtualenv or save the module files in another directory and use the following code to allow Python to search for modules in the given module: >>> import os, sys >>> file_path = 'AdditionalModules/' >>> sys.


2 Answers

EDIT - 2020/02/03

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) 

Like @zwer mentioned, the above works, although it is not seen as a proper way of packaging your project. To look at this in better depth, read the the page How to package a Python App.

like image 116
Girrafish Avatar answered Sep 27 '22 20:09

Girrafish


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  
like image 21
matan h Avatar answered Sep 27 '22 18:09

matan h