Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I automatically install missing python modules? [duplicate]

I would like to be able to write:

try:     import foo except ImportError:     install_the_module("foo") 

What is the recommended/idiomatic way to handle this scenario?

I've seen a lot of scripts simply print an error or warning notifying the user about the missing module and (sometimes) providing instructions on how to install. However, if I know the module is available on PyPI, then I could surely take this a step further an initiate the installation process. No?

like image 810
j b Avatar asked May 25 '11 07:05

j b


People also ask

How do I install a missing module in Python?

You can install modules or packages with the Python package manager (pip). To install a module system wide, open a terminal and use the pip command. If you type the code below it will install the module.

Does Python automatically install pip?

PIP is automatically installed with Python 2.7. 9+ and Python 3.4+ and it comes with the virtualenv and pyvenv virtual environments.

Does pip install requirements automatically?

Note: pip installs wheels by default. Wheels include package requirements. If pip does not find a wheel to install, it will build one.

How do you auto install requirements txt in Python?

You can use pipreqs to automatically generate a requirements. txt file based on the import statements that the Python script(s) contain. To use pipreqs , assuming that you are in the directory where example.py is located: pip install pipreqs pipreqs .


2 Answers

Installation issues are not subject of the source code!

You define your dependencies properly inside the setup.py of your package using the install_requires configuration.

That's the way to go...installing something as a result of an ImportError is kind of weird and scary. Don't do it.

like image 22
Andreas Jung Avatar answered Oct 08 '22 06:10

Andreas Jung


Risking negative votes, I would like to suggest a quick hack. Please note that I'm completely on board with accepted answer that dependencies should be managed externally.

But for situations where you absolutely need to hack something that acts like self contained, you can try something like below:

import os  try:   import requests except ImportError:   print "Trying to Install required module: requests\n"   os.system('python -m pip install requests') # -- above lines try to install requests module if not present # -- if all went well, import required module again ( for global access) import requests 
like image 144
ring bearer Avatar answered Oct 08 '22 06:10

ring bearer