Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to import module with the name of the module being a user input

As the title says I need the user to input the name of an account eg: Main or Spam and then import that specific module.

I tried using this but python expects to find a module called "Accounts" i wanted it to look for the module with the same name as the input

Account=input("Which account to use?: ")
    if Account in acc.accounts:
        import Account as info

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You would want to use import_module: https://docs.python.org/3/library/importlib.html#importlib.import_module

module.py:

def foo():
    print("bar")

In the script:

from importlib import import_module
m = import_module("module") ## refers to module.py
m.foo() ## prints "bar"

In your code, you would want to change

import Account as info

to

info = import_module(Account)

You would want to make sure the module you are trying to import is also on your $PATH.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading