python - 如何在VSCode中自动将根目录添加到python路径中?

标签 python visual-studio-code python-import importerror

我从 PyCharm 切换到 VSCode。现在,我在导入同一个包中的模块时遇到问题。
main.py

from importlib_resources import files

import household_prices.data.raw_data as raw_data # <- moudle not found

source = files(raw_data).joinpath("household_price.csv")
df = pd.read_csv(source)
我认为这与python路径有关。当我打电话时sys.path在 PyCharm 中,我有两个 ~/code/household_prices/household_prices/analysis~/code/household_prices/household_prices .
VSCode 中缺少第二条路径。是否有一种自动方法可以始终在 python 路径中包含包的根目录?
文件夹结构
* household_prices
  * .idea
  * household_prices
    * analysis
      * __init__.py
      * main.py
    * data/
      * __init__.py
      * raw_data/
        * __init__.py
        * household_price.csv
    * README.md

最佳答案

根据您的描述,建议您可以尝试以下提示:

  • 将设置行添加到 launch.json .vscode 的文件文件:

  • "env": {"PYTHONPATH" : "${workspaceRoot}"},


    VSCode 会自动Cally 在项目的根目录中查找。(最外面的 household_prices ),
    然后,VSCode 会根据这行代码进一步查找需要的文件:import household_prices.data.raw_data .
  • 创建 ' __init__.py ' 文件夹中的文件 household_prices (二楼),会让VSCode更准确的知道一个文件就是一个包。

  • 我已经创建了一个与你的文件结构相同的项目,经过测试,我可以成功导入模块。
    我的环境:python3.8.3; VSCode:1.47.3;操作系统:Windows_NT x64 10.0.18362

    关于python - 如何在VSCode中自动将根目录添加到python路径中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63168089/

    相关文章:

    visual-studio-code - 无法在 VS Code 中启动客户端 Clang 语言服务器

    typescript - Visual Studio Code 中 console.log 的快捷方式是什么

    visual-studio-code - 当 VSCode 设置为 Git 编辑器时中止交互式 rebase

    python-3.x - __init__.py 中的 google.cloud 命名空间导入错误

    python - 通过用户输入的文件路径导入文件

    python - 如何将参数与函数对象相关联?

    python - Django 注释总和

    python - 在计算集群上训练 RandomForest 很慢

    python - 单个 python 文件中的多个类具有不同的依赖关系

    python - 从csv文件Python计算一行值的总和