grzegorz700
grzegorz700

Reputation: 331

How to proper setup python source root direcory in Visual Studio Code?

I'm trying to setup a python project in Visual Studio Code. My problem is to create and use the src directory as source root (like it is working in pycharm). I have this directory structure:

project_name\
  src\
    __init__.py
    dta\
      __init__.py
      dtapy.py
    tests\
      __init__.py
      tet.py

My problem occurs e.g. with this code:

import dta.dtapy
print('ok')

I get the message:

File ".../project_name/scr/tests/tet.py", line 1, in import dta.dtapy ModuleNotFoundError: No module named 'dta'

I tried several tips like:

What is the proper way to setup this correctly in VS Code?

Upvotes: 10

Views: 16907

Answers (5)

johannstark
johannstark

Reputation: 81

Okay! So here is the easiest way I found to set up this as a very loyal PyCharm user.

My usual project configuration is very similar to the one in question:

project_name\
  src\
    main.py
    controllers\
      endpoints.py
    tests\
      test.py

Run and debug config file

VSCode uses a .json file to configure how it runs and debugs your Python project. This file is called launch.json and is stored in project/.vscode/

The magic line here is the cwd property that allows to set a path for the main execution of the project. Here is the launch.json file that works for me:

    {
       "version": "0.2.0",
       "configurations": [
          {
             "name": "Python: FastAPI",
             "type": "python",
             "request": "launch",
             "cwd": "${workspaceFolder}/src",
             "module": "uvicorn",
             "args": [
                 "main:app"
             ],
             "jinja": true,
          }
       ]
    }

This will run and debug your project EVERY TIME as if src was the actual root, the sources root

Upvotes: 1

Cees Timmerman
Cees Timmerman

Reputation: 19654

I didn't use any __init__.py files and your project works fine in Visual Studio Code using this project_name\.vscode\launch.json:

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

Note the addition of the PYTHONPATH environment variable. It's the same as would be set by marking that src directory as a Sources Root in PyCharm, though technically that's

 'PYTHONPATH': 'C:\\Users\\Cees\\PycharmProjects\\testimport;C:\\Users\\Cees\\PycharmProjects\\testimport\\src;C:\\Program '
               'Files\\JetBrains\\PyCharm '
               '2020.2.3\\plugins\\python\\helpers\\pycharm_matplotlib_backend;C:\\Program '
               'Files\\JetBrains\\PyCharm '
               '2020.2.3\\plugins\\python\\helpers\\pycharm_display',

according to pprint(dict(os.environ))

Upvotes: 3

Laurens Knoll
Laurens Knoll

Reputation: 639

Setting a source folder in VSCode requires some effort. Instead of adding a source folder via the PyCharm UI, you need to configure the PYTHONPATH for the editors' Python environment and the integrated terminal. You need to configure it twice, because not all Extensions use the editors' Python environment to run their commands.

The editors' Python environment is configured by the Python environment variables file. By default this is found at workspaceFolder/.env

PYTHONPATH=./src

The integrated terminal is configured by the Workspace settings file: .vscode/settings.json

{
  "terminal.integrated.env.osx": {
    "PYTHONPATH": "${workspaceFolder}/src",
  },
  "terminal.integrated.env.linux": {
    "PYTHONPATH": "${workspaceFolder}/src",
  },
  "terminal.integrated.env.windows": {
    "PYTHONPATH": "${workspaceFolder}/src",
  }
}

More info:

Upvotes: 17

Brett Cannon
Brett Cannon

Reputation: 16070

Using a .env file with relative paths and changing your current working might confuse things. I would just use the .env file. Also delete the src/__init__.py file as it's unnecessary. Finally, I would move your tests/ directory up out of src/ so it's next to it, otherwise it should probably be under dta/ and then use relative imports.

Upvotes: 0

ipaleka
ipaleka

Reputation: 3957

Not really an answer, but still...

Name that directory project_name instead of src.

Together with __init__.py inside that directory, create __main__.py file with your main function in it:

def main():
    # call your app from here


if __name__ == "__main__":
    main()

That way you may start your app from the root directory of your project (first project_name) with:

$ python -m project_name

And your launch.json configuration for VS Code (click that gear icon in the Debug section) should be like:

{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Python: Module",
            "type": "python",
            "request": "launch",
            "module": "project_name",
            "console": "integratedTerminal"
        }
    ]
}

Upvotes: -3

Related Questions