Home > Enterprise >  Module installed but not imported
Module installed but not imported

Time:02-16

I’m trying to install and import the modules who are missing in a python script before it shows error.

try: 
     import matplotlib 
     import numpy
except ImportError as e:
     import os 
     module = e.name 
     os.system(‘pip install ‘  module)
     import module

The errors I get : ModuleNotFound : No module named “matplotlib”

import module ModuleNotFoundError: No module named “module” Although the module gets installed correctly, when I rerun it again, the script recognizes the installed modules and works fine. Any idea what it could be?

CodePudding user response:

I think these functions will solve it. I use importlib because if you try to import like import module python sees it like there is a module named module not matplotlib. So, you need to use importlib.import_module() to overcome this situation.

import os
import sys


def library_installer(name):
    """
    Install a library from the pip package manager.
    """
    import subprocess
    subprocess.call([sys.executable, "-m", "pip", "install", name])

def library_importer(name):
    """
    Import a library from the pip package manager.
    """
    import importlib
    return importlib.import_module(name)

try:
    import e

except ImportError as x:
    library_installer(x.name)
    library_installer(x.name)

Here is a link for importlib if you want.

  • Related