1

I have a program with plugin functionality and I don't want to install all the plugins from setup.py if I am not using them. They should only be installed when they are activated in the config of the main program.

Is it possible to install these programs using pip while running the main program?

Something like this:

try:
   if PLUGINNAME not installed:
      pip install PLUGINNAME

I know its possible to use os.system to force console input but that seems really bad.

andrew
  • 389
  • 1
  • 4
  • 11
Zanndorin
  • 360
  • 3
  • 15

2 Answers2

4

You can do this with a by trying to import the module. If the module is not installed an ImportError will be given and you can install the package.

import pip
import imp

try:
    imp.find_module(package)
except ImportError:
    pip.main(['install', package])
Jens de Bruijn
  • 939
  • 9
  • 25
  • How can I do this if I do not want to import it? Can I Just throw it out? – Zanndorin Aug 10 '15 at 12:51
  • That is very difficult (http://stackoverflow.com/questions/1668223/how-to-de-import-a-python-module). At least you could remove the import after the exception as this is not required. I have modified the answer to use imp to check if the module is available which does not actually import the module – Jens de Bruijn Aug 10 '15 at 12:58
-3

you should use this

import pip
import sys

def install(package):
    if not package in sys.modules:
        pip.main(['install', package])
# Example
if __name__ == '__main__':
    install('argh')
greybeard
  • 2,249
  • 8
  • 30
  • 66
Atul Jain
  • 1,053
  • 11
  • 36