Python3.8与VScode。我有两个同级目录,我想将第一个同级目录(support_tools)导入到第二个目录中。
这是我的项目层次结构:
├── support_tools
│ ├── __init__.py
│ └── file_utils.py
└── optimizations
├──.vscode
│ ├── launch.json
│ └── settings.json
├── __init__.py
└── test1.py
我向launch.json添加了父路径:
{
// 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",
"env": {
"PYTHONPATH": "${workspaceFolder}${pathSeparator}..${pathSeparator}",
},
}
]
}
对settings.json来说:
{
"python.analysis.extraPaths": [
"${workspaceFolder}/../"
]
}
幽门识别模块support_tools.py,但如果不将父路径附加到os.paths:sys.path.append("../")
,则无法导入support_tools模块。
在本教程:https://k0nze.dev/posts/python-relative-imports-vscode/中,他们明确提到,在将路径添加到两个文件之后,我应该能够删除os.path.append行
此外,我还试图在以下几页找到答案:
Import Sibling Packages with __init__.py doesn't work
Importing modules from parent folder
谢谢你的帮助
发布于 2022-10-10 01:49:33
一个简单的方法是使用优化父文件夹作为工作区。
VsCode使用工作区作为根目录搜索文件。如果要导入的文件不在工作区中,它将找不到内容。
技巧:
您可以在“python.Analytics. extraPaths”中使用绝对路径。
因为在工作区中,工作区已经是根目录。如果使用相对路径,则不存在父目录。
https://stackoverflow.com/questions/73998994
复制相似问题