问题:如何使用pyenv+uv进行python依赖管理?
解决:使用uv时,如果需要指定python版本,就必须先在系统安装相应的python版本,但有时候无法直接使用apt install命令安装,这时候可以使用pyenv进行python版本管理
方法:
安装pyenv
1、ubuntu安装pyenv需要的依赖
sudo apt update
sudo apt install -y make build-essential libssl-dev zlib1g-dev \
libbz2-dev libreadline-dev libsqlite3-dev wget curl llvm \
libncursesw5-dev xz-utils tk-dev libffi-dev liblzma-dev
rocky安装pyvenv需要的依赖
sudo dnf install -y \
git \
gcc \
make \
zlib-devel \
bzip2-devel \
libffi-devel \
openssl-devel \
readline-devel \
sqlite-devel \
xz-devel \
tk-devel
2、安装pyenv
curl https://pyenv.run | bash
3、配置 shell,编辑 ~/.bashrc,在末尾添加:
# Load pyenv automatically by appending
# the following to
# ~/.bash_profile if it exists, otherwise ~/.profile (for login shells)
# and ~/.bashrc (for interactive shells) :
export PYENV_ROOT="$HOME/.pyenv"
[[ -d $PYENV_ROOT/bin ]] && export PATH="$PYENV_ROOT/bin:$PATH"
eval "$(pyenv init - bash)"
# Restart your shell for the changes to take effect.
# Load pyenv-virtualenv automatically by adding
# the following to ~/.bashrc:
eval "$(pyenv virtualenv-init -)"
配置国内python镜像源,编辑 ~/.bashrc,在末尾添加:
export PYTHON_BUILD_MIRROR_URL=https://registry.npmmirror.com/binary.html?path=python/
或
export PYTHON_BUILD_MIRROR_URL=https://mirrors.tuna.tsinghua.edu.cn/python/
然后重载配置:
source ~/.bashrc
4、安装 Python 3.12
# 查看可安装的python3.12版本,你还可以使用pyenv管理conda等其它软件
pyenv install --list | grep 3.12
# 安装(如 3.12.12)
pyenv install 3.12.12
安装uv
1、安装 uv
# 使用官方脚本(推荐)
curl -LsSf https://astral.sh/uv/install.sh | sh
# 或使用 pip(但此时需已有 Python,注此处不是pyenv内的python)
pip install uv2、安装后,重新加载 shell 配置
source ~/.bashrc3、查看uv版本
uv --version使用pyenv+uv管理软件包
1、进入项目目录,指定使用的python版本
cd myproject
pyenv local 3.12.12 # 创建 .python-version 文件2、创建虚拟环境(会自动使用当前 pyenv 指定的 Python)
python -m venv .venv3、激活虚拟环境
source .venv/bin/activate4、使用 uv 安装包
# 安装单个包
uv pip install requests
# 从 requirements.txt 安装
uv pip install -r requirements.txt -i http://mirrors.aliyun.com/pypi/simple/ --trusted-host mirrors.aliyun.com
# 安装开发依赖(带 extras)
uv pip install -e ".[dev]"
# 同步依赖(类似 pip-sync)
uv pip sync requirements.txt
# 查看已安装包
uv pip list
拓展:
1、查看pyenv版本pyenv --version
2、查看pyenv已经安装的python版本pyenv versions