5

I am working on a Python program which will be distributed to our clients.

Their requirement is that the program should take care of everything without their manual intervention.

How do I check and install missing modules in Python at the time of executing the code? In R, I can use the code as provided below.

How do I replicate something similar in Python?

# Check and install missing packages in R
list.of.packages <- c("RDCOMClient", "htmlTable")
new.packages <- list.of.packages[!(list.of.packages %in% installed.packages()[,"Package"])]
if(length(new.packages) > 0) {
  install.packages(new.packages)
}
ayhan
  • 70,170
  • 20
  • 182
  • 203
Code_Sipra
  • 1,571
  • 4
  • 19
  • 38

2 Answers2

5

Use exception handling, then pip to install the modules:

import pip

def install(package):
    pip.main(['install', package])

def install_all_packages(modules_to_try):
    for module in modules_to_try:
        try:
           __import__(module)        
        except ImportError as e:
            install(e.name)

Note: the __import__ built-in imports modules by a string name. A probably better way to do this is to use the importlib module, for example importlib.import_module

rassar
  • 5,412
  • 3
  • 25
  • 41
  • Your code doesn't work if user doesn't have superuser permission: PermissionError –  Jan 04 '18 at 16:02
  • Hello rassar, I tried the above solution. But it does not seem to be working for me for some reason. I even tried changing the `install(e.name)` to `install('e.name')` but that too does not seem to work. Any idea what I might be doing wrong? I am using Python 3.6. I am new to Python by the way. Most of my work is in R. – Code_Sipra Jan 05 '18 at 00:08
  • This is the error message - `Traceback (most recent call last): File "C:\Users\KING\Desktop\Test.py", line 6, in for module in modules_to_try: NameError: name 'modules_to_try' is not defined` – Code_Sipra Jan 06 '18 at 08:40
  • That's just a variable placeholder. Replace it with the list of modules you need to install. Run the function `install_all_packages` and pass it as an argument. – rassar Jan 07 '18 at 16:16
0

You can use exception handling:

try:
    import some_module

except ImportError as e:
    print(e)
    # install module or some operation
  • This will require the user to type in every single module that they want to import. The `__import__` function, or `importlib.import_module` is better in this case. – rassar Jan 04 '18 at 14:50
  • Ok, I understood this way is not much efficient but it's not wrong! –  Jan 04 '18 at 15:37