问题
使用 pyenv-venv activate env_name 命令激活虚拟环境后
-
无法使用tab自动完善命令
-
无法上下键切换历史命令
脚本
#!/usr/bin/bashvenvs="/d/JavaProgramFiles/pyenv-win/pyenv-win-venv/envs"
# #!/bin/bashactivate () {# 设置 PATHORIGIN_PATH="${ORIGIN_PATH:-$PATH}"export PATH="$venvs/$curr_env/Scripts:$ORIGIN_PATH" # 加上虚拟环境路径# 设置 PYTHONHOMEif [ -n "${PYTHONHOME:-}" ] ; thenORIGIN_PYTHONHOME="${ORIGIN_PYTHONHOME:-$PYTHONHOME}"unset PYTHONHOMEfi# 设置 PS1if [[ "$PS1" != *"$curr_env"* ]]; thenORIGIN_PS1="${ORIGIN_PS1:-$PS1}"export PS1="curr_env: $curr_env$ORIGIN_PS1"fiecho "Virtual environment $curr_env activated."
}deactivate () {# 重置 PATHif [ -n "${ORIGIN_PATH:-}" ] ; thenPATH="${ORIGIN_PATH}"export PATHunset ORIGIN_PATHfi# 重置 PYTHONHOMEif [ -n "${ORIGIN_PYTHONHOME:-}" ] ; thenexport PYTHONHOME="${ORIGIN_PYTHONHOME}"unset ORIGIN_PYTHONHOMEfi# 重置 PS1if [ -n "${ORIGIN_PS1:-}" ]; thenexport PS1=$ORIGIN_PS1unset ORIGIN_PS1fiecho "Virtual environment $curr_env deactivated."unset curr_env
}curr_env=$1if [ -n "$curr_env" ]; thenif [ -d "$venvs/$curr_env" ]; thenactivateelseecho "Virtual environment '$curr_env' does not exist."fi
elsedeactivate
fi
原理
修改当前shell环境的环境变量PATH、PYTHONHOME、PS1
PATH: 查找命令的配置
PYTHONHOME: 防止python home变量影响(不确定是否有影响,抄官方的脚本)
PS1: 提示用户,当前正在使用的虚拟环境
前提
使用pyenv-venv管理虚拟环境,并且所有的虚拟环境都保存在一个目录下
参考文档
使用
-
把上面的脚本复制到PATH范围内的目录中,脚本名称为 venv
-
任意打开一个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.