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

I would like to install the 'mutagen' and 'gTTS' modules for my code, but I want him to install the modules on every computer that does not have them, but he will not try to install them if they are 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 modules, it will simply add unnecessary clutter to the beginning of the program whenever you open it.

+4
source share
3 answers

To check if the package exists or not, and install it in the latter case, try using the module pip:

: , ( post):

from contextlib import contextmanager
import sys, os

@contextmanager
def suppress_stdout():
    with open(os.devnull, "w") as devnull:
        old_stdout = sys.stdout
        sys.stdout = devnull
        try:  
            yield
        finally:
            sys.stdout = old_stdout

import pip

required_pkgs = ['mutagen', 'gTTS']
installed_pkgs = [pkg.key for pkg in pip.get_installed_distributions()]

for package in required_pkgs:
    if package not in installed_pkgs:
        with suppress_stdout():
            pip.main(['install', package])

try except:

import pip

pkgs = ['mutagen', 'gTTS']
for package in pkgs:
    try:
        import package
    except ImportError, e:
        pip.main(['install', package])

.. @zwer, , . , Python.

+5

:

python -m MyModule

,

, :

pip freeze > requirements.txt

, python

:

pip install -r requirements.txt

+1

Another solution is to put the import statement for everything that you are trying to import into the try / except block, so if it works, it will be installed, but if it does not throw an exception, and you can run the command to install it.

0
source

Source: https://habr.com/ru/post/1678017/


All Articles