如何设置VSCode以便能够从子目录导入文件

3

@温馨提示:我已经搜索了像这个或者这个现有的线程,以寻找潜在解决方案。但是,我仍然无法将所有信息汇集在一起,并找到最佳和有效的设置。虽然我的情况可能不太普遍,但它试图从SO的不同地方连接起来。请在判定为重复之前考虑这一点。

我的项目结构如下:

my-project/
  src/
    model.py
    utils.py
    __init__.py
  notebooks/
    test.py

model.py中,我有一个导入语句:
from utils import my_function

我的工作目录设置为my-project(由os.getcwd()返回)。 我正在使用Conda环境,并尝试根据这里的建议修改PYTHONPATH

"env": {"PYTHONPATH": "${workspaceRoot}, ${workspaceRoot}/src"}

我还在src目录下有一个__init__.py文件。据我的理解,如果我使用from src.utils import my_function,那么在VSCode中就能正常工作——但是,在从位于src目录(其中位于model.py脚本的位置)运行的bash终端时却不行。除此之外,我还想能够从位于notebooks目录下的jupyter笔记本文件中导入我的模块。

最佳设置是什么,以便从这里的另一个模块src中导入脚本?在这里真的需要编辑PYTHONPATH吗?(我没看到这种影响)。


你想从 "utils.py" 导入方法到 "module.py" 吗?如何理解 "除此之外,我希望能够在位于 notebooks 中的 Jupyter notebook 文件中导入我的模块。",你想在 Jupyter 文件中导入 Python 文件吗? - Jill Cheng
PYTHONPATH是一个环境变量,你需要用分号;或冒号:(在UNIX/Windows上分别)进行分隔。 - user202729
1个回答

3

导入其他文件夹中的模块时,默认情况下VSCode从该文件的父文件夹开始。

在VSCode中,我导入和使用其他文件中的类和方法的方式如下:

  1. Use absolute paths. The way to set the VSCode search path is to start from the current project. VSCode first changes to the project folder path before executing the code.

    For example: Use

    "env": {
                    "PYTHONPATH": "D:\\...\\folder"
                }
    

    in "launch.json" to add the absolute path of the project.

  2. Use relative paths. Find the project path based on the relative path of the file (using the imported module file), then VSCode will start searching from the project folder.

    For example: Use the following code at the beginning of the file to find the project folder path:

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

运行:

输入图像描述

输入图像描述

输入图像描述


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接