python - 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:添加env
和cwd
{
// 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 的更改不是我所理解的(如果我错了,请纠正我)。我通常使用“播放”按钮来运行代码,所以很想找到一种让它工作的方法。
我尝试过的其他一些事情:
- 硬编码绝对路径而不是
workspaceFolder
- 将init .py添加到 dataStructures/ 和 dataStructures/graphs
- 仅尝试使用 .env 文件,也仅使用 settings.json 中的 PYTHONPATH
不知道我哪里出错了,我很感激任何帮助来完成这项工作!谢谢!
其他参考:
解决方案
推荐阅读
- java - Spring Boot - 请求映射不接受斜杠或多个目录
- java - Stirng[] 无法转换为字符串
- spring-integration - 如何使用 Spring Integration 设置 ThreadPool 来处理文件消息源?
- ios - 使用 iPhone X Truedepth 构建人脸的 3D 对象
- reactjs - 空检查仍然会引发 Flow 错误
- ios - iOS 中的交互式 ImageView
- java - 减少嵌套循环并提高 Java 中的可读性
- javascript - $(...).sortable 在 JQuery 回调中不是函数
- java - 是否可以使用自定义注释进行此操作?
- c - 为什么将变量移位超过其宽度(以位为单位)会归零?