Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm trying to setup python project in Visual Studio Code. My problems is to create and use scr 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 for 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 tired 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?

like image 572
grzegorz700 Avatar asked Jul 23 '19 14:07

grzegorz700


Video Answer


1 Answers

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:

  • Setting Python source folders in VSCode
  • Use of the PYTHONPATH variable
like image 75
Laurens Knoll Avatar answered Oct 02 '22 14:10

Laurens Knoll