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

0

1 Answer 1

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)
Sign up to request clarification or add additional context in comments.

1 Comment

Better to use importlib?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.