Home > Back-end >  How to import module with the name of the module being a user input
How to import module with the name of the module being a user input

Time:12-22

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

CodePudding user response:

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.

CodePudding user response:

To import a module whose name is stored in a variable, you can use the importlib library. Specifically, you can use the importlib.import_module() function to import a module with a dynamic name.

Here's an example of how you can use importlib.import_module() to import a module with the name stored in a variable:

import importlib

# List of valid account names
acc = ['Main', 'Spam']

account = input("Which account to use?: ")

if account in acc:
    # Import the module with the name specified in the `account` variable
    info = importlib.import_module(account)

print(info.some_function())
  • Related