MichaelAquilina / zsh-autoswitch-virtualenv

🐍 ZSH plugin to automatically switch python virtualenvs (including pipenv and poetry) as you move between directories
GNU General Public License v3.0
507 stars 80 forks source link

Error auto switching in VS Code terminal #196

Closed ricky9w closed 5 months ago

ricky9w commented 6 months ago

Issue Details

If I run mkvenv in a shell outside of VS Code, and then open a terminal in VS Code, if will fail to switch to the locally created virtual environment (but entering and leaving the directory in the terminal outside of VS Code will do).

Only if I run mkvenv in the VS Code terminal will be able to auto-switch to the right virtual environment.

Operating System (uname -a)

Darwin MacBook 23.2.0 Darwin Kernel Version 23.2.0: Wed Nov 15 21:53:34 PST 2023; root:xnu-10002.61.3~2/RELEASE_ARM64_T8103 arm64

zsh version (zsh --version)

zsh 5.9 (x86_64-apple-darwin23.0)

autoswitch-virtualenv version

echo "$AUTOSWITCH_VERSION"
3.7.1

How is zsh-autoswitch-virtualenv

I installed Python with pyenv, and installed this plugin with znap.

Steps to reproduce the issue

gist link to your zshrc

https://gist.github.com/ricky9w/99c07d11aee251591d778cf9440fab37

ricky9w commented 5 months ago

I looked into the code of the plugin, and found the possible reason of the problem: I usually open a project directory in VS Code by typing code .. When I cd into the project directory, the plugin successfully switches to the virtual environment, and sets the VIRTUAL_ENV environment variable. This variable is passed along to VS Code, making the shell opened in VS Code wrongly assume that it's already in the correct virtual environment, thus causing the error.

A workaround is adding a custom function to launch VS Code, that unset the VIRTUAL_ENV variable before launching Code, and reset the variable after that:

function code_with_venv_fix() {
    # Check if a virtual environment is currently active
    local current_venv="$VIRTUAL_ENV"
    # Unset the VIRTUAL_ENV variable to avoid issues in VS Code
    unset VIRTUAL_ENV

    # Launch VS Code
    code "$@"

    # Optionally, wait for VS Code to launch and then restore VIRTUAL_ENV
    # Uncomment the following line if you wish to restore VIRTUAL_ENV after launching VS Code
    # export VIRTUAL_ENV="$current_venv"
}

Then setup an alias:

alias code='code_with_venv_fix'