Daniel Dias
Daniel Dias

Reputation: 9

How to dynamically switch python interpreter in VS Code?

I have a project workspace with multiple microservices, how can I make VS Code switch between python interpreters to the nearest virtual environment folder?

For example:

Workspace/
├── folder1/
│   ├── .venv/
│   └── src/
│       └── main.py
├── folder2/
│   ├── .venv/
│   └── src/
│       └── main.py
├── folder3/
│   └── src/
│       └── main.py
├── folder4/
│   └── toolsfolder/
│       ├── tool1
│       │   ├── .venv/
│       │   └── main.py
│       ├── tool2
│       │   ├── .venv/
│       │   └── main.py
│       └── README.md
├── .venv/
├── Makefile
└── README.md

Upvotes: 1

Views: 1157

Answers (2)

rioV8
rioV8

Reputation: 28663

If you want to automatically activate the correct environment and start debugging the current active editor you have to split the starting the debugger and attach the client (VSC) to the debugger.

Write a shell script that has as argument the current file path. The script will activate the correct Python environment and start a debugger on the given file path that waits for the client.

I have described this process and what to use as commands in another Python Debug answer

The task to use is:

{
  "version": "2.0.0",
  "tasks": [
    {
      "label": "Script to activate specific environment and debug",
      "type": "shell",
      "command": "activate-env-and-debug ${workspaceFolder} ${relativeFile}",
      "problemMatcher": []
    }
  ]
}

In the script to start the debugger use a command like:

python <path>/.vscode/extensions/ms-python.python-2021.12.1559732655/pythonFiles/lib/python/debugpy
  --listen 5678 --wait-for-client $1/$2

Because the environment is active python should execute the correct interpreter.

The version number of the ms-python.python extension will vary after updates, maybe you can extract the current (latest) by enumerating the extensions folder and search for the one with the largest version number (by parts) (they don't use 2 months digits)

Upvotes: 1

MingJie-MSFT
MingJie-MSFT

Reputation: 9219

I don't understand why you want to use multiple environments in the same workspace.

I think it would be better to separate them in different workspaces in order to avoid environmental chaos.

The chosen python interpreter is specific to the current workspace, instead of an independent directory. If you like, you could manually select the interpreter (ctlr+shift+P) when using different folders.

Upvotes: 0

Related Questions