正确的相关导入:“无法导入模块" [英] Proper relative imports: "Unable to import module"
问题描述
我有一个这样结构的项目:
<预><代码>.└── 我的应用├── app.py├── 模型│ ├── hello.py│ └── world.py└── 需求.txt我有两个模型,hello
和 world
.这两个模型都是从 app.py
使用的,我像这样导入它们:
from models.hello import Hellofrom models.world import World
但是world
也需要使用hello
.我在 world.py
中试过这个:
from models.hello import Hello
当我运行应用程序时,上述技术在技术上有效,但 VSCode 的 Python 扩展给了我以下错误:
E0401:无法导入models.hello".
从同一目录导入子模块的正确方法是什么?如何在 VSCode 中避免此错误?
您收到的错误是由名为 pylint
的 python linter 报告的.所以这个问题并不是真正特定于 vscode 扩展.
有两种解决方案:
请尝试使用 vape
PYTHONPATH=./myapp
在您的项目目录中添加一个.env
文件,这将告诉 pylint 在哪里可以找到您的模块或者直接在 vscode 中打开文件夹
myapp
而不是在 vscode 中打开父目录.
I have a project structured like this:
.
└── myapp
├── app.py
├── models
│ ├── hello.py
│ └── world.py
└── requirements.txt
I have two models, hello
and world
. Both models are used from app.py
where I import them like this:
from models.hello import Hello
from models.world import World
But world
also needs to use hello
. I tried this in world.py
:
from models.hello import Hello
The above technically works when I run the app, but VSCode's Python extension gives me the following error:
E0401:Unable to import 'models.hello'.
What is the proper way of importing a submodule from the same directory? How do I avoid this error in VSCode?
The error you are receiving is one that's reported by a python linter named pylint
. So the problem isn't really specific to the vscode extension.
There are two solutions:
Please try adding an
.env
file in your project directory with the vapePYTHONPATH=./myapp
, this will tell pylint where to find your modulesOr just open the folder
myapp
in vscode directly instead of opening the parent directory in vscode.
这篇关于正确的相关导入:“无法导入模块"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!