0

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.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
  • 1
    This is going to break for any modules whose import is named differently from the package. Why don't you supply a `requirements.txt` and install all the necessary packages from that? – jonrsharpe Feb 08 '20 at 12:03
  • 1
    This is possible to do, e.g. via import hooks. However, it will not create a fire-and-forget application - for example, you can't set specific versions. Are you sure that you really need to replicate package management, instead of using available but external tools? – MisterMiyagi Feb 08 '20 at 12:18
  • 1
    Does this answer your question? [How to install and import Python modules at runtime?](https://stackoverflow.com/questions/17234762/how-to-install-and-import-python-modules-at-runtime) – MisterMiyagi Feb 08 '20 at 17:36
  • I'm curious, why do you want to do this? – AMC Feb 08 '20 at 19:56
  • to auto import from a list so any .py document i make in that project i can just use from imports.py import install() function, inside of install function it will try to import if it fails it installs. So my environment for python is consistent on any pc for major projects. And if I give the code to a firend to assist it sets up their environment with the modules rather than waste countless time per person checking how to download and install those specific modules on the IDE of their choice – user11335084 Mar 23 '20 at 04:56

0 Answers0