简体   繁体   English

如何使用带有 VSCode Python 扩展的 PYTHONPATH 进行调试?

[英]How to use PYTHONPATH with VSCode Python Extension for Debugging?

I'm working on a project which is structured like我正在做一个结构如下的项目

Parent Directory
----+ MyPackage
     ----__init__.py
     ----file1.py
----+ Tests
     ----test.py

When I run the tests from terminal, I use当我从终端运行测试时,我使用

PYTHONATH=./ python ./Tests/test.py

Now, when I try the debug option after installing 'Python Extension', error is raised现在,当我在安装“Python Extension”后尝试调试选项时,会出现错误

Exception has occurred: ModuleNotFoundError
No module names 'MyPackage'

How can I put PYTHONPATH to the debug configuration such that it will taken care?我怎样才能把 PYTHONPATH 放到调试配置中,这样它就会被处理?

After some search and trial and error, I found something that works.经过一番搜索和反复试验,我发现了一些可行的方法。 I'm posting it here so that people looking for the same problem can also try.我在这里发布它,以便寻找相同问题的人也可以尝试。 I'm not sure whether this is the right way to do t.我不确定这是否是正确的做法。

Create (or add to) a file .vscode/settings.json the contents as创建(或添加到)文件.vscode/settings.json的内容为

{
    // .. any other settings
    "terminal.integrated.env.linux": {
        "PYTHONPATH": "${workspaceFolder}"
      }
}

Now I'm able to run my project with the package.现在我可以使用 package 运行我的项目。

In VSCode 1.74.0 I got it to work by putting the path in my debugging launch.json在 VSCode 1.74.0 中,我通过将路径放在我的调试launch.json中来让它工作

{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Python debugging"
            "type": "python"
            // other settings
            "env": {
                "PYTHONPATH": "${workspaceFolder}",
            }
        }
    ]
}

Using venv I have tried every variation of tinkering with the terminal.integrated.env.x setting, and env / cwd in launch.json and while I could get this scenario OK when running a file, I could not get it working correctly when debugging a file.使用 venv 我已经尝试了各种修改terminal.integrated.env.x设置和launch.json中的env / cwd的各种变体,虽然我可以在运行文件时让这个场景正常,但在调试时我无法让它正常工作一份文件。

So, what I ended up doing was modifying the bin/activate file in the .venv folder locally to add the project to the python path as part of activation.所以,我最终做的是在本地修改.venv文件夹中的bin/activate文件,以将项目添加到 python 路径作为激活的一部分。 I think this solution is fine as the venv is to be used only with this project and it covers all scenarios of running files within the IDE.我认为这个解决方案很好,因为 venv 只用于这个项目,它涵盖了 IDE 中运行文件的所有场景。

I added this to the bottom of myProject/.venv/bin/activate :我将其添加到myProject/.venv/bin/activate的底部:

PYTHONPATH="../:$PYTHONPATH"
export PYTHONPATH

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM