Kevin Burtnett Kevin Burtnett - 1 month ago 10
Python Question

Can I use a function to either import or install a module

I am running Windows 7, Python 2.7, Anaconda 4.0.0:
Here is what I want to do. I want to take this code and put it in a function.

try:
import easygui
except ImportError:
from os import system
system('pip install easyqui')
import easygui
else:
pass


This is what I have come up with but I am not able to get it to work.

def install(mypack):
try:
import mypack
except ImportError:
from os import system
system('pip install ' + str(mypack))
import mypack
else:
pass
install('easygui')


The error I get is "ImportError: No module named mypack".

Answer

The import statement takes the module name literally and not just as a reference to some other object. So import mypack does not translate to import easygui, but import module mypack

Instead, you should use the builtin __import__ which takes a name/string:

__import__(mypack)