Home > Net >  Cannot run python code in vs code from root folder
Cannot run python code in vs code from root folder

Time:01-25

I have a folder debug_example in vs code with the following structure:

enter image description here

The content in main is:

from debug_example.src.util import my_util

if __name__ == '__main__':
    my_util()

whereas the content in util is:

def my_util():
    print("foo")

When I click on the "play" button in vs code

enter image description here

or debug it, or run it in any way from vs code, I get

ModuleNotFoundError: No module named 'debug_example'

But if I run it from the terminal it works fine:

python -m debug_example.main

When debugging this, I see that sys.path has the debug_example folder in it when running from vs code, but not when running from terminal. Is there any way for this to run in a regular way in vs code, as in terminal?

CodePudding user response:

The play button vs launching from terminal

When you click on "the play button" on VSCode, it calls the current interpreter and puts the first parent directory of the script as the current working directory. Therefore, when the system won't find the module debug_example inside debug_example.

You should rather use the alternative method, I think it is a better habit for when working with complex projects and different environments.

Debugging with VSCode

To debug in VSCode, you simply have to add the following env entry to the launch.json configuration file (that you can open from the debug console):

{
    "version": "0.2.0",
    "configurations": [
        {
           "name": "Python: Current File",
           "type": "python",
           "request": "launch",
           "program": "${file}",
           "console": "integratedTerminal",
           "env": { "PYTHONPATH": "${workspaceRoot}"}
        }
    ]
}

CodePudding user response:

modulenotfounderror caused because interpreter can't locate specified package. Therefore please check if specified package installed correct path to package specified in script.

Also can specify required package path using sys.path.append.

For more related queries can check modulenotfounderror reasons with respected answer .

  •  Tags:  
  • Related