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

标签 python import importerror nameerror

我正在编辑以最小化为可重现的示例:

cal.py 的内容

import M1

M1.SM1.nice_hello.hello()

目录结构:

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

SM1/nice_hello.py 的内容:

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

所有其他文件(init.py 文件)都是空的。

运行 cal.py:

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

但这给了我以下错误:

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

最佳答案

如果您导入整个模块名称,即在文件cal.py中,它应该可以工作

import M1.SM1.nice_hello

M1.SM1.nice_hello.hello()

关于python - 为什么主模块看不到里面的子模块?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67565002/

相关文章:

python - Groupby 应用多个参数

python - 在线程中使用 exec(compile()) 导入问题

java - 如果一个类调用另一个类,我可以将它们放在单独的 JAR 文件中吗?

python - Golang net.Listen 绑定(bind)到已在使用的端口

python - 可编辑的 QTableView 和 Pandas 不能正常工作

python - 如何将 PIL 图像绘制到 DearPyGui Canvas 上?

android - 导入包时出错

python - pyautogui,屏幕截图功能无法识别已安装的 Pillow 模块

python - 在 Python 中导入本地模块 - ImportError : Not module named *

python - 尝试在 Mac 上使用 Python TestRail API - ImportError : No module named Conf_Reader