-1

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".

1 Answers1

2

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)
Moses Koledoye
  • 77,341
  • 8
  • 133
  • 139