简体   繁体   English

为什么主模块看不到里面的子模块?

[英]Why can't Main Module see sub-module inside it?

I am editing to minimize to a reproducible example:我正在编辑以最小化为可重现的示例:

Contents of cal.py cal.py 的内容

import M1

M1.SM1.nice_hello.hello()

Directory structure:目录结构:

M1/
├── __init__.py
└── SM1
    ├── __init__.py
    └── nice_hello.py

Contents of SM1/nice_hello.py: SM1/nice_hello.py 的内容:

def hello():
    print(f'Hello my friend!!!')

All other files ( init .py files) are empty.所有其他文件( init .py 文件)都是空的。

To run cal.py:要运行 cal.py:

export PYTHONPATH=/PATH/TO/M1 ; python cal.py

But that gives me following error:但这给了我以下错误:

Traceback (most recent call last):
  File "cal.py", line 3, in <module>
    M1.SM1.nice_hello.hello()
AttributeError: module 'M1' has no attribute 'SM1'

It should work if you import the whole module name, ie in the file cal.py如果您导入整个模块名称,即在文件cal.py中,它应该可以工作

import M1.SM1.nice_hello

M1.SM1.nice_hello.hello()

Submodules are not imported recursively, if you want that to happen you can do the below: -子模块不会以递归方式导入,如果您希望这样做,您可以执行以下操作:-

A) Create init .py file inside M1 module ( I think you already have that ) A)在 M1 模块中创建init .py 文件(我想你已经有了)

B) Have the below code in your init .py file: - B)在您的init .py 文件中有以下代码:-

import importlib
import pkgutil

def import_submodules(package, recursive=True):
""" Import all submodules of a module, recursively, including subpackages

:param package: package (name or actual module)
:type package: str | module
:rtype: dict[str, types.ModuleType]
"""
if isinstance(package, str):
    package = importlib.import_module(package)
results = {}
for loader, name, is_pkg in pkgutil.walk_packages(package.__path__):
    full_name = package.__name__ + '.' + name
    results[full_name] = importlib.import_module(full_name)
    if recursive and is_pkg:
        results.update(import_submodules(full_name))
return results

This will help you import all the submodules inside that package ( M1)这将帮助您导入 package ( M1 ) 中的所有子模块

Now in your cal.py do below: -现在在您的 cal.py 中执行以下操作:-

import M1
M1.import_submodules(M1)
def hello():
    print(f'Hello my friend!!!')

Hopefully this will resolve your issue and might guide you on how to import modules recursively in python希望这能解决您的问题,并可能指导您如何在 python 中递归地导入模块

Reference:- How to import all submodules?参考:- 如何导入所有子模块?

Please reach out in comments if any further clarification is required.如果需要进一步澄清,请在评论中联系。 Will be happy to help很乐意提供帮助

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

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