How to check if a module is installed in Python an

2019-03-29 05:47发布

问题:

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.

回答1:

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

To hide the output, you'd need to create a function for it (from the code in this 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])

Or another way to go about it is with a simple try except:

import pip

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

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.



回答2:

Another solution it to put an import statement for whatever you're trying to import into a try/except block, so if it works it's installed, but if not it'll throw the exception and you can run the command to install it.



回答3:

You can use the command line :

python -m MyModule

it will say if the module exists

Else you can simply use the best practice :

pip freeze > requirements.txt

That will put the modules you've on you python installation in a file

and :

pip install -r requirements.txt

to load them

It will automatically you purposes

Have fun



回答4:

pip list | grep <module_name_you_want_to_check>

Above is the answer, where:

pip list

list all modules, and

grep <module_name_you_want_to_check>

find the keyword from the list. Works for me.