Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot run python code in vs code from root folder

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?

like image 725
David Masip Avatar asked Sep 13 '25 19:09

David Masip


1 Answers

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}"}
        }
    ]
}
like image 109
Benjamin Rio Avatar answered Sep 15 '25 10:09

Benjamin Rio