How do I automatically install missing python modules?

j b picture j b · May 25, 2011 · Viewed 71.7k times · Source

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?

Answer

ring bearer picture ring bearer · Apr 21, 2016

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