-1

I want to write a 'If Else' function in Python to check if a list of modules are present or not, else install modules in Python (3.6).

Thanks in advance!

AI2.0
  • 313
  • 1
  • 3
  • 7

2 Answers2

1

Here's how I'd do it:

import os
def checkModules(module_list):
    missing = []
    for m in module_list:
        try:
            exec("import %s" % m)
        except ImportError:
            missing.append(m)
    if len(missing) > 0:
        os.system("python -m pip install %s" % ' '.join(missing))

Hope that helps!

scripter
  • 356
  • 2
  • 8
0

https://docs.python.org/3/library/sys.html#sys.modules

This is a dictionary that maps module names to modules which have already been loaded.

Tynan J
  • 69
  • 6