首页 > 解决方案 > 在 vscode 上从根目录导入文件时显示 ModuleNotFound 错误

问题描述

我有一个具有这种结构的 vscode 项目

注意有两个配置文件,一个在labor文件夹下,一个在app文件夹下。在functions.py中,我试图在app文件夹下导入config.py。

# note I need to add app. before config because if I don't it will think that I'm referencing the file under labor folder
import app.config as app_config

在 testing.py 我正在导入两个文件

import config as app_config
import labor.config as labor_config

print("test")

这给了我一个 ModuleNotFound 错误。疯狂的部分是,如果我按住 CTRL 键并单击 functions.py 文件中 app.config 中的“config”,它会将我带到该文件夹​​。所以它正在识别它。但不知何故,在运行代码时,python 不是。

如果您想尝试一下,我在这里创建了一个 repo: https ://github.com/jadeid91/testproject

标签: pythonvisual-studio-code

解决方案


如果你想在 app 目录中进行测试,你在错误的地方运行测试,你必须使用import config而不是import app.config在 labour 目录中的 .py 文件并添加__init__.py到 labour 以确保 python 不会混淆并给你 labour.config

测试.py

import config as app_config
import labor.config as labor_config
import labor.functions as labor_functions

print(app_config.MAIN_TABLE_ID)
print(labor_config.LABOR_TABLE_ID)

劳动/功能.py

import config as app_config

# if I import config, it will take me to labor.config
# import config


def hello():
    print(app_config.MAIN_TABLE_ID)

文件夹结构

  • /应用程序
    • /劳动
      • __init__.py
      • 配置文件
      • 函数.py
    • 配置文件
    • 测试.py

推荐阅读