8

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:

  • add .envfile with: PYTHONPATH=src to root directory
  • setup launch.json with: "cwd": "${workspaceFolder}/src",

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

Benyamin Jafari
  • 27,880
  • 26
  • 135
  • 150
grzegorz700
  • 171
  • 1
  • 5
  • 4
    Same issue here. It's hard to believe there doesn't seem to be straightforward documentation to do this. – Mushu909 Nov 02 '19 at 04:04

5 Answers5

15

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:

Laurens Knoll
  • 581
  • 3
  • 6
  • 1
    It doesn't work. Neither `.vscode/` nor `.env` exist in the project. I also created the `.vscode/settings.json` file manually and put the mentioned stuff without any result. – Benyamin Jafari Aug 07 '22 at 08:26
  • Could you elaborate on that Benyamin? Are you trying to run a python file from vscode, from command line, ..? – Laurens Knoll Aug 24 '22 at 10:24
3

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))

Cees Timmerman
  • 17,623
  • 11
  • 91
  • 124
0

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.

Brett Cannon
  • 14,438
  • 3
  • 45
  • 40
0

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

starball
  • 20,030
  • 7
  • 43
  • 238
johannstark
  • 71
  • 1
  • 5
-3

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"
        }
    ]
}
ipaleka
  • 3,745
  • 2
  • 13
  • 33