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?
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.
PIP is automatically installed with Python 2.7. 9+ and Python 3.4+ and it comes with the virtualenv and pyvenv virtual environments.
Note: pip installs wheels by default. Wheels include package requirements. If pip does not find a wheel to install, it will build one.
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 .
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.
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
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