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.
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.
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.
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.
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.
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With