【问题标题】:No module found error when I have added the path添加路径后未找到模块错误
【发布时间】:2019-10-03 07:00:41
【问题描述】:

我的项目结构如下:

文件greet.py如下:

def greet_morning(message):
    print("Hello, {}", message)

def greet_evening(message):
    print("Evening message: {}", message)

文件msg.py 为:

import sys
import os
sys.path.append(os.getcwd())


from greet.greet import greet_morning

greet_morning("heyy")

当我尝试以python message/msg.py 运行msg.py 时,我收到一条错误消息ImportError: No module named greet.greet。我从根目录运行这个文件。为什么我已经在系统路径中添加了cwd 会出现此错误?

【问题讨论】:

标签: python module path


【解决方案1】:

我觉得是

from untitled.greet.greet import greet_morning

如果还是不行,添加:

import sys
sys.path.append('../')

编辑

我想你可以在这里找到所有可能的解决方案Importing files from different folder

【讨论】:

  • 还是报错ImportError: No module named untitled.greet.greet
  • 在我在所有目录中添加__init__.py 后,它可以工作,但使用from greet.greet import greet_morning。我不得不删除untitled。你能帮我理解一下吗?
  • @Amanda ,是的,基本上你通过将并行模块添加到 sys.path 中来使它们可见
  • 我需要在项目内的所有文件中都这样做吗?
【解决方案2】:

add __init__.py 在 greet 和 msg 文件夹中__init__.py

【讨论】:

    【解决方案3】:

    您错过了模块中的文件__init__.py

    只需在 greet 文件夹中创建一个空文件 __init__.py

    【讨论】:

    • ``` import sys import os sys.path.append(os.path.abspath('../greet')) import greet.greet_morning("heyy") ```跨度>
    猜你喜欢
    • 2022-09-24
    • 2020-06-05
    • 2022-01-11
    • 1970-01-01
    • 2018-11-21
    • 2011-07-06
    • 2018-10-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多