Search code examples
pythonpython-3.xpython-2.7pyinstallerlibraries

Module installed but not imported


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?


Solution

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