简体   繁体   English

从python中的命名空间导入模块

[英]importing modules from namespaces in python

I had some modules in the same path as my the script I'm running. 我的脚本与我运行的脚本位于同一路径。

my_dir/
├── my_script.py
├── module_script_1.py
└── module_script_2.py

I had some code to import those modules on the fly when I needed them, and it worked like a charm: 我有一些代码可以在需要时即时导入这些模块,它的工作原理很吸引人:

print('Starting python module ' + name_value)
module = __import__(name_value)
df = getattr(module, name_value)(arg1 = val1)
print('Finished python module ' + name_value, df)

However, I'm trying to refactor this into a better design as the system is getting bigger. 但是,随着系统变得越来越大,我正在尝试将其重构为更好的设计。

I am attempting to use a namespace, so here's my folder structure now: 我正在尝试使用名称空间,所以现在是我的文件夹结构:

root_dir/
├── modules_dir/
|   ├── __init__.py
│   ├── module_script_1.py
│   └── module_script_2.py
├── workflow_dir/
│   └── my_script.py
└── setup.py

Now, in the setup.py we have a namespace called root_dir : 现在,在setup.py我们有一个名为root_dir的命名空间:

setup(
    name='root_dir',
    namespace_packages=['root_dir'],
    packages=[f'root_dir.{p}' for p in find_packages(where='root_dir')],
    ...

So that's my setup, but I can't seem to replicate my previous functionality of importing the modules on the fly as easily. 这就是我的设置,但是我似乎无法像以前那样轻松地复制之前导入模块的功能。 Let me show you what I have in my_script.py now: 现在让我向您展示my_script.py

import root_dir.modules_dir # not necessary - just testing if import works
...
print('Attempting to import python module ' + name_value)
module = __import__('root_dir.modules_dir.' + name_value)
df = getattr(module,  name_value)...

That gives an error: 这给出了一个错误:

    df = getattr(module,  name_value)...
AttributeError: module 'root_dir' has no attribute 'module_script_1'

Can you show me how to use namespaces correctly in this situation? 您能告诉我在这种情况下如何正确使用名称空间吗? It seems to get past the __import__ line but hasn't imported the correct thing. 似乎已超过__import__行,但未导入正确的内容。

how do I import from a module within a namespace on the fly? 如何即时从命名空间中的模块导入?

during my research I found: 在研究过程中,我发现:

How to use python's import function properly __import__() 如何正确使用python的import函数__import __()

which suggested I try: 建议我尝试:

module = importlib.import_module('root_dir.modules_dir.' + name_value)

which worked. 起作用了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM