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

python - How to insert QWidgets in the middle of a Layout? -

python - serve multiple gunicorn django instances under nginx ubuntu -

module - Prestashop displayPaymentReturn hook url -