0

I want to test in script whether all the necessary libraries are installed or not, if not, install it. Here is my code:

libs = ['lib1','lib2','lib3']
def import_m(name):
    try:
        import name 
    except:
        pip.main(['install',name])
        import name                    #look at this line
for i in libs:
        import_m(i)
print("Done importing %s." % i)

But when running it raise an exection:

ImportError: No module named name

The line mentioned with this exection are indicated by the comment.

How can I fix it?

MomoBD
  • 1
  • 1
  • 1
    start with checking the return value of pip.main – tkhurana96 Dec 31 '17 at 20:18
  • @tkhurana96 What do you mean by **return value** ? – MomoBD Dec 31 '17 at 20:29
  • have a look at [this link](https://stackoverflow.com/questions/45799042/installing-packages-from-a-list-using-pip) – tkhurana96 Dec 31 '17 at 20:37
  • @tkhurana96 It does return 0. – MomoBD Dec 31 '17 at 20:40
  • Possible duplicate of [Installing python module within code](https://stackoverflow.com/questions/12332975/installing-python-module-within-code). The error says `No module named name`, even though you're actually installing `lib1`, `lib2` and `lib3`. `import name` literally imports `name`, not the value of the `name` variable. – mercator Dec 31 '17 at 20:45

1 Answers1

1

you are going to need

importlib

for this functionality.

A similar question is answered here

For your requirement you can first try to import a library using

globals()['module_name'] = importlib.import_module('module_name')

if it throws an exception you just need to install it and run the above code again. Don't try to run import module_name again. If module_name is successfully stored in globals you are all good to go.

HariUserX
  • 1,341
  • 1
  • 9
  • 17