vscode-python: Deactivate environment command broken for venv

Workaround

This is a known issue, see https://github.com/microsoft/vscode-python/issues/22037#issuecomment-1736462876 for a workaround in bash.

Expected vs. Actual

Expected: running deactivate exits the venv in that particular shell context

Actual: running deactivate shows command isn’t found (data-loader-prototype-py3.10) [admin-smiller@UUE2OLY01L olympus]$ deactivate bash: deactivate: command not found

Behaviour

I would expect the environment to be properly sourced in my bash shell context. Instead commands like “deactivate” are not found given the inital shell context.

Steps to reproduce:

  1. Select a python interpreter via the python plugin
  2. Open an new terminal
  3. Try deactivating the default environment

About this issue

  • Original URL
  • State: closed
  • Created 9 months ago
  • Reactions: 2
  • Comments: 21

Most upvoted comments

Yes it works, adding this combined block of code into ~/.bashrc Thanks.

_OLD_VIRTUAL_PS1="${PS1:-}"
_OLD_VIRTUAL_PATH="$PATH"
if [ -n "${PYTHONHOME:-}" ] ; then
    _OLD_VIRTUAL_PYTHONHOME="${PYTHONHOME:-}"
fi

deactivate () {
    # reset old environment variables
    if [ -n "${_OLD_VIRTUAL_PATH:-}" ] ; then
        PATH="${_OLD_VIRTUAL_PATH:-}"
        export PATH
        unset _OLD_VIRTUAL_PATH
    fi
    if [ -n "${_OLD_VIRTUAL_PYTHONHOME:-}" ] ; then
        PYTHONHOME="${_OLD_VIRTUAL_PYTHONHOME:-}"
        export PYTHONHOME
        unset _OLD_VIRTUAL_PYTHONHOME
    fi

    # This should detect bash and zsh, which have a hash command that must
    # be called to get it to forget past commands.  Without forgetting
    # past commands the $PATH changes we made may not be respected
    if [ -n "${BASH:-}" -o -n "${ZSH_VERSION:-}" ] ; then
        hash -r 2> /dev/null
    fi

    if [ -n "${_OLD_VIRTUAL_PS1:-}" ] ; then
        PS1="${_OLD_VIRTUAL_PS1:-}"
        export PS1
        unset _OLD_VIRTUAL_PS1
    fi

    unset VIRTUAL_ENV
    unset VIRTUAL_ENV_PROMPT
    if [ ! "${1:-}" = "nondestructive" ] ; then
    # Self destruct!
        unset -f deactivate
    fi
}

Thanks, I’ve edited the original comments so that folks can easily focus on the workaround. Created https://github.com/microsoft/vscode-docs/issues/6590 so we officially document this limitation on VS Code docs.