首页 > 解决方案 > Python VSCode:尽管添加了 PYTHONPATH,但无法使用“播放”按钮导入模块

问题描述

TL;DR - VSCode settings.json 和 .env 文件未在 MacOS 的终端中设置 PYTHONPATH

我正在尝试在 MacOS 上使用带有 Python3 的 VSCode 在我的工作区中运行代码,该代码会导入工作区中的其他模块。我的代码可以在这里找到:https ://github.com/stuti-rastogi/commonAlgorithms/blob/master/dataStructures/graphs/graphSearch.py

这是我的工作区的结构:

commonAlgorithms/
|____dataStructures/
     |____stacks.py
     |____queues.py
     |____...
     |____graphs/
           |_____graph.py
           |_____graphSearch.py
           |_____minimumSpanningTrees.py.py
           |_____...

graphSearch.py(实现 BFS 和 DFS)中,我想利用我在 dataStructures 下的堆栈队列实现。因此我有这样的导入语句(我不想使用相对导入):

from dataStructures.queues import Queue
from dataStructures.stacks import Stack
from dataStructures.graphs.graph import Graph

我正在使用一种非常老套的方法来设置我的 PYTHONPATH,它适用于 F5、Ctrl+F5 以及在终端中运行代码的 VSCode 上的“播放”按钮:我在我的~/.bash_profile:

PYTHONPATH="/Users/stutirastogi/dev/commonAlgorithms:$PYTHONPATH"
export PYTHONPATH

现在,为了以一种更优雅的方式来处理不同的工作区,我决定修改 VSCode 工作区设置来做到这一点。我遵循了这个答案这个博客但是,我可以让代码使用 F5 和 Ctrl+F5 但不使用“播放”按钮。

我做了以下修改(也重新启动了 VSCode,杀死了终端):

1.launch.json:添加envcwd

{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Python: Current File",
            "type": "python",
            "request": "launch",
            "program": "${file}",
            "console": "integratedTerminal",
            "cwd": "${fileDirname}",
            "env": {"PYTHONPATH": "${workspaceFolder}${pathSeparator}${env:PYTHONPATH}"}
        }
    ]
}

2. settings.json : 添加了 PYTHONPATH 和 envFile

{
    "python.pythonPath": "/usr/local/bin/python3",
    "python.testing.promptToConfigure": false,
    "python.testing.pytestEnabled": false,
    "python.testing.unittestEnabled": false,
    "python.testing.nosetestsEnabled": false,
    "terminal.integrated.env.osx": {
        "PYTHONPATH": "${workspaceFolder}"
    },
    "python.envFile": "${workspaceFolder}/.env"
}

3. .env 文件:在工作空间的根目录添加了一个 .env 文件

WORKSPACE_FOLDER="/Users/stutirastogi/dev/commonAlgorithms"
PYTHONPATH="${WORKSPACE_FOLDER}"

由于 F5 和 Ctrl+F5 正在工作,我觉得 launch.json 更改工作但 settings.json 的更改不是我所理解的(如果我错了,请纠正我)。我通常使用“播放”按钮来运行代码,所以很想找到一种让它工作的方法。

我尝试过的其他一些事情:

不知道我哪里出错了,我很感激任何帮助来完成这项工作!谢谢!

其他参考:

标签: pythonvisual-studio-codemodulevscode-settingspythonpath

解决方案


推荐阅读