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!
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!
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!
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.