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


this question has answer here:

i running windows 7, python 2.7, anaconda 4.0.0:

here want do. want take code , put in function.

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

this have come not able work.

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

the error "importerror: no module named mypack".

the import statement takes module name literally , not reference other object. import mypack not translate import easygui, import module mypack

instead, should use builtin __import__ takes name/string:

__import__(mypack) 

Comments

Popular posts from this blog

qt - QML MouseArea onWheel event not working properly when inside QML Scrollview -

java - is not an enclosing class / new Intent Cannot Resolve Constructor -

python - Error importing VideoFileClip from moviepy : AttributeError: 'PermissionError' object has no attribute 'message' -