2

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"
}

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

ya it does work. However I found that I will have to modify A LOT to fit this solution, and pycharm can easily solve this by setting root directory. I would hold for a while until I'm tired of pycharm lol

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.