Home > other >  How to correctly import python modules when the program runs in visual studio code?
How to correctly import python modules when the program runs in visual studio code?

Time:04-21

I have a my_program.py python script.

Inside this script, I can import the class in utils/my_util.py by starting the script with python -m foo.my_program.

Here's the content of my_program.py

from utils.my_util import Util

u = Util()

But when I press Start Debugging button for foo/my_program.py in visual studio code, it generates the following error.

Exception has occurred: ModuleNotFoundError
No module named 'utils'
  File "/Users/my_name/debug/python_proj/foo/my_program.py", line 1, in <module>
    from utils.my_util import Util

How can I run python -m foo.my_program in visual studio code?

I think there's something in .vscode/launch.json that I can configure to make the program run correctly.

I've tried setting "cwd" to "${workspaceFolder}". But this doesn't work.

Here's the folder structure of my scripts.

.
├── foo
│   └── my_program.py
└── utils
    └── my_util.py

CodePudding user response:

I found that adding the following parameters under "configurations" of .vscode/launch.json works.

"cwd": "${workspaceFolder}",
"env": {
    "PYTHONPATH":"${workspaceFolder}"
}

According to this document, ${workspaceFolder} means "the path of the folder opened in VS Code".

And this document says that PYTHONPATH is an environment variable which the user can set to add additional directories that the user wants Python to add to the sys. path directory list.

So Adding ${workspaceFolder} to PYTHONPATH means python will search ${workspaceFolder} folder when it runs import.

CodePudding user response:

Except in the launch.json file, you can also:

Add this in the settings.json file, it will affects the action which run within the terminal, such as Run Python File in Terminal:

  "terminal.integrated.env.windows": {
      "PYTHONPATH": "${workspaceFolder}",
  },

Or, create a .env file and added this to it:

PYTHONPATH={some path to the parent folder of the module which you want to import, such as workspaceFolder}

and you can point the .env file manually through "python.envFile" in the settings.json or "envFile" in the launch.json, and "envFile" will overwrite "python.envFile".

  • Related