[英]why can't python see my module?
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: 我正在尝试根据命令行参数从
main.py
动态导入config.py
,如下所示:
#!/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'
. 但它抱怨由于
ModuleNotFoundError: No module named 'default_config'
中断ModuleNotFoundError: No module named 'default_config'
。 Similar code in ipython does not suffer the same issue, when called from /package
从
/package
调用时,ipython中的类似代码不会遇到相同的问题
If there is a better way to load a package at run time via user input, I'm open to suggestions. 如果有更好的方法可以在运行时通过用户输入来加载程序包,我欢迎您提出建议。
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
: 或者,使用相对导入,然后将第二个参数设置为
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. 这更加安全,因为现在
config_str
字符串不能用于“突破” config_files
子软件包。
You do want to strip dots from user-provided names (and, preferably, limit the name to valid Python identifiers only). 您确实想从用户提供的名称中删除点(最好将名称限制为仅有效的Python标识符)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.