mtoloo
mtoloo

Reputation: 1875

How to set the root directory for Visual Studio Code Python Extension?

I have no trouble running and debugging my project with VSCode Python Extension (ms-python.python), but since python sub-project root directory is not the whole project directory, all imports from my sources are underlined with red color and are listed in the problems and so Go to definition and some similar features don't work properly. How can I tell the IDE where's the start point of my project:

Whole Project path:
  docs
  server
    entities
      user.py
      customer.py
  env
  viewer
  db

The server directory is where the imports path are started from:

from entities.user import User

Upvotes: 72

Views: 124128

Answers (6)

balu
balu

Reputation: 3821

I just ran into the same issue. My Python code's entry point (main.py) is under ./tools/ and there are multiple subfolders/packages in that directory. (Basically, ./tools is my "src" folder.)

Meanwhile, my pyproject.toml and my .venv folder are in the repo/workspace root because I want easy access to a properly configured Python environment (with Poetry, Ruff, Mypy, and all) from everywhere in my repository.

I added the following to my ./.vscode/settings.json (= Workspace settings) to get VSCode/Pylance to stop complaining about missing packages and incorrectly rewriting imports when refactoring/renaming modules:

{
  "python.defaultInterpreterPath": ".venv/bin/python",
  "python.poetryPath": "~/.asdf/shims/poetry",
  "python.analysis.extraPaths": ["tools"],
}

(Note that I installed Poetry through asdf – adapt the path as necessary. However, I don't think you need Poetry at all to get imports to work correctly but I still added it for good measure & better support.)

PS: Interestingly, adding the above settings to the settings field of the my-project.code-workspace file did not work.

Upvotes: 0

Sanchit
Sanchit

Reputation: 3289

I am writing another but more general answer in this thread since what I have seen there is some mis-understandings and confusions still going on. Because I am also coming from Pycharm and now using VSCode.

First thing sourcing a directory (e.g., in Pycharm it would be source root) in VSCode needs two different setups for both Run and Debug modes.

For Debug mode:

  • Go to Run -> Add Configuration -> Python file. It will create a launch.json file (under .vscode folder). This config launch.json file will be only running during the debug time. Thus, do not expect this configuration will help you in case of executing your code during run-time.
  • Inside of this file and under "configurations", add these lines. Note that here core is an example directory. It can be either your src or app etc directory.

"cwd": "${workspaceFolder}/core", "env": {"PYTHONPATH": "${workspaceFolder}/core"},

  • So, during debugging VSCode will pick up this PYTHONPATH environment variable and execute your code from this directory.

For Run-time mode (i.e., no debugging):

  • Best and simple way to first install Pylance extension in your VSCode.
  • Then, go to Settings -> search for "Pylance". Go to Workspace tab (which means only for this project) and then scroll down to: Python > Analysis: Extra Paths.
  • Finally, add an absolute path under Add item. E.g., for above core directory it looks like this: /home/Sanchit/work/Project123/core.
  • During run-time, VSCode will pick up this extra import path. Thus, it will resolve your paths.

Final note that you should always execute your script from Run -> Start Debugging (Debug mode) and Run -> Run with Debugging (Run mode).

Upvotes: 2

NicoNing
NicoNing

Reputation: 3212

The PYTHONPATH is an environment variable which you can set to add additional directories where python will look for modules and packages.

If you need to set working directory for Visual Studio Code,

The better way is to customize Settings.json and launch.json, do like this:

// vi .vscode/Settings.json
{
    "python.pythonPath": "venv/bin/python",
}

use cwd to Specifies the current working directory for the debugger, which is the base folder for any relative paths used in code. If omitted, defaults to ${workspaceFolder} (the folder open in VS Code).

// vi .vscode/launch.json
{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Python: your project name",
            "type": "python",
            "request": "launch",
            "cwd": "${workspaceRoot}/server",
        }
    ]
}

If you want the server run properly without any IDE, just insert the Root Drectory in front of PYTHONPATH . Assume there is a server/run.py:

import sys
src_path = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, _src_path)   

refer: https://code.visualstudio.com/docs/editor/debugging#_launch-versus-attach-configurations

refer: https://code.visualstudio.com/docs/python/debugging#python-articles

refer: https://docs.python.org/3/using/cmdline.html#envvar-PYTHONPATH

Upvotes: 11

CyberFly
CyberFly

Reputation: 867

If you are using the Pylance extension you can set your source folder via the python.analysis.extraPaths option. It also looks for common source folder names like src by default, this option is called python.analysis.autoSearchPaths.

Go to File > Preferences > Settings, search for pythonpath. Under the Pylance options you should see Extra Paths, this is where you set your source folder.

Upvotes: 48

val
val

Reputation: 159

Setting PYTHONPATH is what makes it work, as noted above. I use the following .env content so that it works for any project:

PYTHONPATH=${PROJ_DIR}:${PYTHONPATH}

This is essentially what PyCharm does when you check "Add Content Roots to PYTHONPATH" in your run/debug configuration. It's a helpful setting, but it spoils you because your code fails outside PyCharm.

Or, if you run in terminal, first export:

export PYTHONPATH=...

Upvotes: 2

Brett Cannon
Brett Cannon

Reputation: 15990

You can create a .env file with:

PYTHONPATH=server

That will add your server folder to PYTHONPATH as needed.

(You may need to restart VSCode for it to take PYTHONPATH into account correctly.)


Edited to clarify...

Create a file named .env under the repo root e.g. your_repo/.env.

Also creating the file under the folder where your consuming code is, instead of under repo root, seems to work e.g. your_repo/service/.env.

For more details, see documentation on environment variable definition files.

For me this worked without restarting VSC, perhaps this is a matter of newer VSC and extensions versions.

Upvotes: 86

Related Questions