python - 在 vscode 上从根目录导入文件时显示 ModuleNotFound 错误
问题描述
我有一个具有这种结构的 vscode 项目
- /应用程序
- /劳动
- 配置文件
- 函数.py
- 配置文件
- 测试.py
- /劳动
注意有两个配置文件,一个在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
解决方案
如果你想在 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
- /劳动
推荐阅读
- cucumber - 将 cucumber-java 从 info.cukes 的 1.2.4 更新到 cucumber.io 的 4.2.2 throwing import Given(Or When/Then) cannot be resolved 错误
- selenium - 如何通过 Selenium 打开 Chrome 浏览器控制台?
- asp.net - 没有为此对象定义无参数构造函数。使用 asp.net mvc
- c# - 基础脑电图
- c# - 如何修复Unity中的“'GameObject'类型的对象已被破坏,但您仍在尝试访问它”错误?
- c# - 图像转换器在 Xamarin.Forms 中不起作用
- django - 成功消息不适用于创建视图
- dojo - 如何在dojo工具包的当前JS文件中使用另一个JS文件中创建的对话框变量
- php - 一些 index.php 文件生成或自动出现在我的文档根文件夹中
- sql - SSRS SQL 报表生成器删除列