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

Solution 1:

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

Solution 2:

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.

Solution 3:

try:
    import foo
except ImportError:
    sys.exit("""You need foo!
                install it from http://pypi.python.org/pypi/foo
                or run pip install foo.""")

Don't touch user's installation.