简体   繁体   中英

Visual Studio Code launch.json settings for debugging Python modules

Currently I have my file structure like this:

├── Utilities
|   ├── __init__.py
│   ├── module1.py
├── main.py
├── global_var.py

In main.py and module1.py I have already written import global_var , and everything goes well when I run main.py .

However, when I tried to debug or run module1.py itself, it always shows

Exception has occurred: ModuleNotFoundError
No module named 'global_var'

And I have to manually move module1.py to the same folder with global_var.py so that it can run successfully.

I would like to know how to set the launch.json to stop moving the files. Here's my launch.json right now:

{
    "name": "Python: Modules",
    "type": "python",
    "request": "launch",
    "program": "${file}",
    "cwd": "${workspaceFolder}",
    "console": "integratedTerminal"
}

I don't know what the name of the parent folder of file ' global_var.py ' is, so I temporarily named it folder_aa .

Since they are not in the same folder, Visual Studio Code cannot find the path, so you could tell it the path of the file you want to import:

  1. Add the line of settings to the launch.json file of .vscode file:

    "env": {"PYTHONPATH": "${workspaceRoot}"},

    Visual Studio Code will find the root directory (the project folder name) of the current project according to "${workspaceRoot}" .

  2. Use ' from folder_aa import global_var ' instead of ' import global_var '.

    Visual Studio Code will find file 'global_var.py' from folder 'folder_aa'.

I created a project similar to the directory structure you provided, and through the above operations, it can be successfully imported.

My environment: Python 3.8.3; Visual Studio Code 1.47.3; OS: Windows_NT x64 10.0.18362

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