0

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?

  • 1
    `Import` is not a valid python statement. do you mean `import`? –  Feb 15 '22 at 14:38
  • @SembeiNorimaki yes that's what I meant, thanks for noticing it – user14635293 Feb 15 '22 at 14:46
  • Ok, now it gives the error `SyntaxError: invalid character '‘' (U+2018)` You are using strange quotes, you should use `'` or `"` –  Feb 15 '22 at 14:48
  • and then take a look at https://stackoverflow.com/questions/13598035/importing-a-module-when-the-module-name-is-in-a-variable You cannot do `import module` you need to use __import__ –  Feb 15 '22 at 14:50
  • Thanks I solved it with importlib! One more question I'm trying to write all the missing in a file and install them fromt ehre, but somehow only the first missing module gets wrriten. The code goes like ```try: import matplotlib import numpy except ImportError as e: with open("file.txt", "a+") as f: f.write(e.name)``` – user14635293 Feb 16 '22 at 10:05

1 Answers1

0

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.

Mrrelaxed
  • 40
  • 1
  • 7
  • One more question I'm trying to write all the missing in a file and install them fromt ehre, but somehow only the first missing module gets wrriten. The code goes like ```try: import matplotlib import numpy except ImportError as e: with open("file.txt", "a+") as f: f.write(e.name)``` – user14635293 Feb 16 '22 at 10:02
  • Can you open another question? I don't want to break format of Q&A system and I can easily show and explain the code you want. @user14635293 – Mrrelaxed Feb 16 '22 at 14:58