0

I'm trying to take the user's input, and see if there's a module named whatever they input. If there is, I then want that module to be imported, and to call a function within it of the same name. I know there are more simple ways of doing this, but I wanted to try and make it super compact.

This was my idea:

userinput = str.lower(input(prompt))
try:
    import (userinput) as _(userinput)
    _(userinput).(userinput)
except:
    print("Module not found")

If it couldn't find a module with the name given, it would simply trip the exception and continue.

My problem is being able to import a module from the string given from the input.

2 Answers2

0
userinput = str.lower(input(prompt))
try:
    exec("import %s as _(userinput)"%(userinput))
    #_(userinput).(userinput)  ???????
except:
    print("Module not found")

The exec() part works, but I'm not sure what you want to do with the _(userinput).(userinput)

Phonzi
  • 144
  • 3
  • 9
0

Use the __import__ function.

userinput = input("Enter name of module to import: ")
module = __import__(userinput)
kindall
  • 178,883
  • 35
  • 278
  • 309