Home > database >  Automate import modules
Automate import modules

Time:10-09

I have this to import all modules if they dont exist, the thing is that even if i have them it also behaves has if i dont, what am i doing wrong?

listimport=["request","shutil","shutil","styless","time","tkinter","openpyxl","html","datetime","importlib","string",
      "easygui","bs4","webbrowser","glob","tarfile","webbrowser","pathlib","platform","subprocess","tkinterweb",
            "jira","numpy","matplotlib","calendar","sys","math","math","parser","pyautogui","dateutil","xlwt"]
for x_imp in listimport:
    try:
        import x_imp
    except ImportError as e:
        os.system('pip install '   x_imp)

this always tries to install all modules even if they already exist, any ideas?

CodePudding user response:

When you import a module you do it like this:

import request

Using your program you will try to import every string like this:

import "request"

Because listimport contains strings! so you will get an error every time!

You can fix it using __import__ that do the same thing, but on a string:

import os

listimport = ["request","shutil","shutil","styless","time","tkinter","openpyxl","html","datetime","importlib","string",
      "easygui","bs4","webbrowser","glob","tarfile","webbrowser","pathlib","platform","subprocess","tkinterweb",
            "jira","numpy","matplotlib","calendar","sys","math","math","parser","pyautogui","dateutil","xlwt"]

for x_imp in listimport:
    try:
        __import__(x_imp)
    except ImportError as e:
        os.system('pip install '   x_imp)

CodePudding user response:

You are now trying to import a string, for example import "numpy". A simple solution can be to use exec()

listimport=["request","shutil","shutil","styless","time","tkinter","openpyxl","html","datetime","importlib","string",
      "easygui","bs4","webbrowser","glob","tarfile","webbrowser","pathlib","platform","subprocess","tkinterweb",
            "jira","numpy","matplotlib","calendar","sys","math","math","parser","pyautogui","dateutil","xlwt"]

for x_imp in listimport:
    try:
        exec('import {}'.format(x_imp))
    except ImportError:
        os.system('pip install '   x_imp)
  • Related