Reputation: 11171
I have a file structure like this:
/package/main.py
/package/__init__.py
/package/config_files/config.py
/package/config_files/__init__.py
I'm trying to dynamically import config.py
from main.py
based on a command line argument, something like this:
#!/usr/bin/env python
from importlib import import_module
cmd_arguments = sys.argv
config_str = cmd_arguments[1]
config = import_module(config_str, 'config_files')
but it complains breaks with ModuleNotFoundError: No module named 'default_config'
. Similar code in ipython does not suffer the same issue, when called from /package
If there is a better way to load a package at run time via user input, I'm open to suggestions.
Upvotes: 0
Views: 58
Reputation: 1121534
You are trying to import from a nested package, so use the full package name:
config = import_module(config_str, 'package.config_files')
Alternatively, use a relative import, and set the second argument to package
:
config = import_module('.config_files.{}'.format(config_str), 'package')
This is more secure, as now the config_str
string can't be used to 'break out' of the config_files
sub package.
You do want to strip dots from user-provided names (and, preferably, limit the name to valid Python identifiers only).
Upvotes: 1