【问题标题】:Python3 ModuleNotFoundError importingPython3 ModuleNotFoundError 导入
【发布时间】:2021-12-17 09:20:57
【问题描述】:

我有以下目录结构

/home/project/src/numeric.py
/home/project/test/test.py

我正在尝试通过导入 numeric.py 来运行 test.py:

import src.numeric as n

Python 给了我:

ModuleNotFoundError: No module named 'src'

目前我在目录中

$ cd /home/project/test/
$ python3 test.py

我有什么遗漏的吗?

【问题讨论】:

  • src.numeric 是文件名。我想你需要写成from src.numeric import <function, class etc. or * if you want everything>的格式

标签: python python-3.x module directory importerror


【解决方案1】:

Python 正在根据脚本执行目录的相对路径导入模块。

因此,您的输入语句计算为:

/home/project/test/src/numeric.py

-> 但文件位于:

/home/project/src/numeric.py

如果你想保持这个结构,你必须在你的路径中包含'src'目录,如下所示:

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

Python import src modules when running tests

【讨论】:

    猜你喜欢
    • 2020-11-17
    • 2021-10-26
    • 1970-01-01
    • 2022-11-05
    • 1970-01-01
    • 2018-10-20
    • 1970-01-01
    • 2021-05-10
    • 2021-05-09
    相关资源
    最近更新 更多