Search code examples
pythonvisual-studio-codevirtualenvzshoh-my-zsh

How to activate python environment in ZSH using VSCode terminal


I have a folder called src where there is a python environment called venv.

When src is open in VSCode, I need this environment to be activated as soon as I launch a terminal.

In src/.vscode/settings.json I have set

"python.terminal.activateEnvironment": true

Which correctly activates venv when terminal.integrated.defaultProfile.linux is set to bash. However when it is set to zsh, the python interpreter used is the global one (/usr/bin/python3) and I have to manually run source venv/bin/activate in the terminal so that it uses src/venv/bin/python3 instead.

I also tried the following:

  "terminal.integrated.profiles.linux": {
    "venv": {
      "path": "/bin/zsh", // works with "/bin/bash" 
      "source": "venv/bin/activate",
      "args": []
    }
  },
  "terminal.integrated.defaultProfile.linux": "venv"

But I get the same result.

In this folder, zsh always puts this at the end of the line enter image description here. I am not sure what this means exactly but I suspect it could give a clue of what's happening.

I also tried disabling all my zsh plugins but again, same result.


Solution

  • I found a workaround (inspired from here). The -c argument from zsh allows to run any command at invocation.

    Since we can use arguments with terminal.integrated.profiles.linux, a simple solution to put in settings.json is:

      "terminal.integrated.profiles.linux": {
        "venv": {
          "path": "zsh", // works with "bash" too 
          "args": ["-c", "source venv/bin/activate; zsh -i"]
        }
      },
      "terminal.integrated.defaultProfile.linux": "venv"
    

    NB: It is necessary to write zsh -i at the end otherwise the zsh terminal closes instantly.