I am trying to import a module if the import fails install the module that failed and attempt again. I have a working solution but it is not ideal.
I have the modules stored as a tuple and want to be able to add to the list of modules at a later point without adding try:
and except ImportError:
for each one.
I am trying to import each object or module in pd
and if it fails install the module while keeping the code short.
pd = "opencv-python", "matplotlib", "numpy", "pygame"
for module in pd:
try:
import module
except ImportError:
subprocess.check_call([sys.executable, "-m", "pip", "install", module])
One method I have tried is:
try:
import cv2
print("Successfully Imported " + pd[0])
except ImportError:
print("Installing Module " + pd[0])
subprocess.check_call([sys.executable, "-m", "pip", "install", 'pd[0]'])
Making the code longer and longer with each module added.