在 VSCode 中调试多目录 Python 项目时出现相对导入的导入错误

问题描述 投票:0回答:1

我正在开发一个具有多个目录的 Python 项目,并在尝试使用 VSCode 进行调试时遇到问题。项目结构如下:

├── main_script.py
├── plots
│   ├── plot_script_1.py
│   └── plot_script_2.py
├── src
│   ├── __init__.py
│   ├── analysis
│   │   ├── __init__.py
│   │   └── analysis_module.py
│   ├── frameworks
│   │   ├── __init__.py
│   │   └── framework_module.py
│   └── utils
│       ├── __init__.py
│       └── utility_module.py
└── tests
    └── test_framework.py

framework_module.py
中,我尝试从其他模块导入:

from ..analysis.analysis_module import dummy_analysis
from ..utils.utility_module import dummy_util

def framework_analysis(arguments):
    # Rest of the code...

从终端运行

main_script.py
工作正常,但是当我尝试在 VSCode 中使用断点调试
framework_module.py
时,我遇到以下
ImportError
:

Exception has occurred: ImportError
attempted relative import with no known parent package
  File "{file}", line {line}, in <module>
    from ..analysis.analysis_module import dummy_analysis

即使我在framework_module.py中包含 if

__name__
==
'__main__'
: 块以进行测试,也会发生这种情况。

我尝试过的:

  • 在framework_module.py中设置一个
    __main__
    块并将其作为脚本运行。
  • 检查导入语句中是否有不正确的路径或拼写错误。

我不确定在多目录项目中调试各个模块时如何解决这些导入错误。在这种情况下,我应该如何使用 VSCode 正确设置调试?

我已经在这里检查了与相对导入相关的其他问题,但它们似乎都不起作用。

python debugging importerror visual-studio-debugging relative-import
1个回答
0
投票

您可能想要为 Python 脚本配置 vscode 的启动选项。举个例子:在你的工作目录下创建一个文件

.vscode/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",
            "program": "${file}",
            "console": "integratedTerminal",
            "justMyCode": false,
            "cwd": "/path/to/your/working/directory",
            "args": [
                "--some", "launch", "arguments"
            ],
            "env": {
                "ENVIRONMENT_VARIABLES": "SOME_VALUE"
            }
        }
    ]
}

这使得 vscode 中的调试启动相当于在

/path/to/your/working/directory
下运行此命令:

ENVIRONMENT_VARIABLES=SOME_VALUE python ${file} --some launch arguments

如果还有不清楚的地方,请参阅官方文档以获取更多信息。

© www.soinside.com 2019 - 2024. All rights reserved.