尽管设置了PYTHONPATH,但在VSCode中导入错误 [英] Import error in VSCode despite setting the PYTHONPATH
问题描述
我在WSL上本地部署了一个气流环境,并且正在使用VScode进行调试和编码.
I have an airflow environment locally deployed on WSL, and I am using VScode to debug and code.
我的应用文件夹结构如下:
My app folder structure is as follows:
~/workspaces
|--- .env
|---organization/gcp/datalake
|--- dags
|--- //My dags
|--- plugins
|--- __init.py__
|--- operators
|--- __init.py__
|--- facebook_operators.py
|--- hooks
|--- __init.py__
|--- facebook_hooks.py
我无法理解VSCode关于导入的行为.
I am having trouble understanding the behavior of VSCode regarding the imports.
我通过.env
文件将dags
和plugins
文件夹添加到了PYTHONPATH
中.我的VSCode直接在workspaces
目录上打开.
I added the dags
and plugins
folders to the PYTHONPATH
via .env
file. My VSCode is opened directly on the workspaces
directory.
问题:
我遇到导入错误,尽管我可以成功go to definition
要导入的类.
I get import errors, although I can successfully go to definition
of the class I want to import.
示例:在我的facebook_operators.py
from hooks.facebook_hooks import FacebookAdsHook
引发以下错误:
模块挂钩"中没有名称"facebook_hooks"
No name 'facebook_hooks' in module 'hooks'
我的.env
文件的内容:
PROJECTDIR=~/workspaces/organization/gcp/datalake
PYTHONPATH=${PROJECTDIR}/plugins
PYTHONPATH=${PROJECTDIR}/dags:${PYTHONPATH}
我哪里出错了?我想了解并解决此错误.
Where did I go wrong? I'd like to understand and solve this error please.
推荐答案
在文件"facebook_operators.py
"的开头添加以下语句;帮助VSCode查找需要导入的文件:
Add the following statement at the beginning of the file "facebook_operators.py
" to help VSCode find the file that needs to be imported:
import os,sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
(VSCode默认从当前打开的文件的父文件夹中查找文件.我们可以使用上面的语句将需要导入的文件路径添加到系统路径中,然后VSCode可以找到它.)
(VSCode defaults to find the file from the parent folder of the currently opened file. We can use the above statement to add the file path that needs to be imported to the system path, and then VSCode can find it.)
这篇关于尽管设置了PYTHONPATH,但在VSCode中导入错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!