win11优化pyenv-venv虚拟环境切换

问题

使用 pyenv-venv activate env_name 命令激活虚拟环境后

  • 无法使用tab自动完善命令

  • 无法上下键切换历史命令

image-20250320163925155

脚本

#!/usr/bin/bash


venvs="/d/JavaProgramFiles/pyenv-win/pyenv-win-venv/envs"
# #!/bin/bash

activate () {
  # 设置 PATH
  ORIGIN_PATH="${ORIGIN_PATH:-$PATH}"
  export PATH="$venvs/$curr_env/Scripts:$ORIGIN_PATH" # 加上虚拟环境路径
  # 设置 PYTHONHOME
  if [ -n "${PYTHONHOME:-}" ] ; then
      ORIGIN_PYTHONHOME="${ORIGIN_PYTHONHOME:-$PYTHONHOME}"
      unset PYTHONHOME
  fi
  # 设置 PS1
  if [[ "$PS1" != *"$curr_env"* ]]; then
      ORIGIN_PS1="${ORIGIN_PS1:-$PS1}"
      export PS1="curr_env: $curr_env$ORIGIN_PS1"
  fi
  echo "Virtual environment $curr_env activated."
}

deactivate () {
  # 重置 PATH
  if [ -n "${ORIGIN_PATH:-}" ] ; then
      PATH="${ORIGIN_PATH}"
      export PATH
      unset ORIGIN_PATH
  fi
  # 重置 PYTHONHOME
  if [ -n "${ORIGIN_PYTHONHOME:-}" ] ; then
      export PYTHONHOME="${ORIGIN_PYTHONHOME}"
      unset ORIGIN_PYTHONHOME
  fi
  # 重置 PS1
  if [ -n "${ORIGIN_PS1:-}" ]; then
      export PS1=$ORIGIN_PS1
      unset ORIGIN_PS1
  fi
  echo "Virtual environment $curr_env deactivated."
  unset curr_env
}

curr_env=$1

if [ -n "$curr_env" ]; then
  if [ -d "$venvs/$curr_env" ]; then
       activate
  else
    echo "Virtual environment '$curr_env' does not exist."
  fi
else
  deactivate
fi

原理

修改当前shell环境的环境变量PATH、PYTHONHOME、PS1

PATH: 查找命令的配置

PYTHONHOME: 防止python home变量影响(不确定是否有影响,抄官方的脚本)

PS1: 提示用户,当前正在使用的虚拟环境

前提

使用pyenv-venv管理虚拟环境,并且所有的虚拟环境都保存在一个目录下

参考文档

image-20250320164624397

使用

  1. 把上面的脚本复制到PATH范围内的目录中,脚本名称为 venv

    image-20250320165007549

  2. 任意打开一个bash脚本,在里面执行如下

    # 查看有哪些虚拟环境
    $ pyenv-venv list envs
    Envs installed:
    chatglm-6b
    global_env
    langchain_chatchat
    OCR2.0
    pytorch
    
    # 激活虚拟环境 pytorch,实际就是修改当前shell的PATH值,把虚拟环境的脚本目录添加到最前面了
    $ source venv pytorch
    Virtual environment pytorch activated.
    curr_env: pytorch
    # 可以直接切换其他虚拟环境
    $ source venv global_env
    Virtual environment global_env activated.
    curr_env: global_env
    # 退出虚拟环境,其实就是把PATH还原
    $ source venv 
    Virtual environment  deactivated.
    
posted @ 2025-03-20 16:56  菜阿  阅读(65)  评论(0)    收藏  举报