在使用uv管理python环境后, 需要在进入不同项目时 执行source .venv/bin/activate
使用 direnv 工具
-
安装
direnv:
apt install direnv -
配置 Shell 环境(以 Bash 为例):
编辑~/.bashrc文件,添加配置, 如果已配置PS1, 可在现有配置上添加${VIRTUAL_ENV_PROMPT}变量:
然后运行eval "$(direnv hook bash)" export VIRTUAL_ENV_DISABLE_PROMPT=y # 禁用uv修改PS1 export PS1='${VIRTUAL_ENV_PROMPT:+($VIRTUAL_ENV_PROMPT)}${debian_chroot:+($debian_chroot)}\u@\h:\w\$ 'source ~/.bashrc使配置生效。 -
在目标目录创建
.envrc文件:
cd /path/to/target_directory vim .envrc
source .venv/bin/activate
if [ -z "${VIRTUAL_ENV_PROMPT:-}" ] && [ -n "${VIRTUAL_ENV}" ]; then
VIRTUAL_ENV_PROMPT=$(basename "${VIRTUAL_ENV}")
fi
export VIRTUAL_ENV_PROMPT -
授权
.envrc:
首次进入目录时需执行此命令以允许direnv allow.envrc生效。 -
验证:
进入目录时,direnv会自动执行.envrc中的命令。
PS1告警信息可通过export VIRTUAL_ENV_DISABLE_PROMPT=y去除# cd /path/to/target_directory direnv: loading ~/path/to/target_directory/.envrc direnv: PS1 cannot be exported. For more information see https://github.com/direnv/direnv/wiki/PS1 direnv: export ~PATH