简体   繁体   中英

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

Exception has occurred: ModuleNotFoundError
No module names 'MyPackage'

How can I put PYTHONPATH to the debug configuration such that it will taken care?

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

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

Now I'm able to run my project with the package.

In VSCode 1.74.0 I got it to work by putting the path in my debugging 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.

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. 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.

I added this to the bottom of myProject/.venv/bin/activate :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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