简体   繁体   English

尽管设置了 PYTHONPATH,但在 VSCode 中导入错误

[英]Import error in VSCode despite setting the PYTHONPATH

I have an airflow environment locally deployed on WSL, and I am using VScode to debug and code.我在WSL本地部署了一个airflow的环境,正在使用VScode进行调试和编码。

My app folder structure is as follows:我的app文件夹结构如下:

~/workspaces
|--- .env
|---organization/gcp/datalake
    |--- dags
        |--- //My dags
    |--- plugins
        |--- __init.py__
        |--- operators
            |--- __init.py__
            |--- facebook_operators.py
        |--- hooks
            |--- __init.py__
            |--- facebook_hooks.py

I am having trouble understanding the behavior of VSCode regarding the imports.我无法理解 VSCode 关于导入的行为。

I added the dags and plugins folders to the PYTHONPATH via .env file.我通过.env文件将dagsplugins文件夹添加到PYTHONPATH My VSCode is opened directly on the workspaces directory.我的VSCode是直接在workspaces目录下打开的。

The problem:问题:

I get import errors, although I can successfully go to definition of the class I want to import.我收到导入错误,尽管我可以成功地go to definition为我要导入的 class。

Example: In my facebook_operators.py示例:在我的facebook_operators.py

from hooks.facebook_hooks import FacebookAdsHook raises the following error: from hooks.facebook_hooks import FacebookAdsHook引发以下错误:

No name 'facebook_hooks' in module 'hooks'模块“hooks”中没有名称“facebook_hooks”

The contents of my .env file:我的.env文件的内容:

PROJECTDIR=~/workspaces/organization/gcp/datalake
PYTHONPATH=${PROJECTDIR}/plugins
PYTHONPATH=${PROJECTDIR}/dags:${PYTHONPATH}

Where did I go wrong?我go哪里错了? I'd like to understand and solve this error please.我想了解并解决这个错误。

Add the following statement at the beginning of the file " facebook_operators.py " to help VSCode find the file that needs to be imported:在“ facebook_operators.py ”文件开头添加如下语句,帮助VSCode找到需要导入的文件:

 import os,sys sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

(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.) (VSCode默认是从当前打开文件的父文件夹中查找文件,我们可以通过上面的语句将需要导入的文件路径添加到系统路径中,VSCode就可以找到了。)

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM