user8920191
user8920191

Reputation:

Python import from user input or command line argument

I want one module to import data from another, but I don't want to hard code the name of the other module. I have attempted using sys.argv, as in:

from sys import argv
from argv[1] import database

but this gives me invalid syntax under argv[1]. I have also tried raw_input, as in:

module = raw_input("Enter module name: ")
from module import database

This results in ImportError: No module named module. I checked that this is not due to the name being module. Other variable names have the same result. The name of the variable database will always be the same. I have successfully imported this variable by importing from the name of the module, but I would like this code to handle cases where the module name is different, as I can then use more than one, and the user is not obliged to use the same module name every time. Is there a way to do this? All the other questions I have seen do not address this specific issue, and I have not found any information in Python's help module either.

Upvotes: 3

Views: 2186

Answers (1)

Chris
Chris

Reputation: 22953

You can importlib.import_module to import a given module using a string:

Import a module. The name argument specifies what module to import in absolute or relative terms (e.g. either pkg.mod or ..mod). If the name is specified in relative terms, then the package argument must be set to the name of the package which is to act as the anchor for resolving the package name (e.g. import_module('..mod', 'pkg.subpkg') will import pkg.mod).

(emphasis mine)

>>> from importlib import import_module
>>> module_name = 're'
>>> module = import_module(module_name)
>>> module
<module 're' from 'C:\\Users\\Christian\\AppData\\Local\\Programs\\Python\\Python36\\lib\\re.py'>
>>> 

Also, as a side recommendation, if you plan on getting command line arguments from the user, use a dedicated command line argument parsing library instead of using bare sys.argv. There are several good ones out there. In fact, Python has one in the standard library; argparse.

Upvotes: 4

Related Questions