Python 包管理器 uv

0. Why uv?

一直在用 Miniconda 作为 Python 项目的虚拟环境管理工具。但实际上,Miniconda 文档里有这样的 声明:Is Anaconda still free?,其中对使用场景有了限制。

比较下来,决定使用 uv,逐步切换,以下是一些记录。

先配置 https_proxy,解决网络问题。

从下载页面 https://github.com/astral-sh/uv/releases 找到最新版本程序。

另外,由于 uv 的子命令比较多,可以先运行 uv generate-shell-completion bash 生成 completion 文件,提高操作效率。

1. 下载指定版本的 Python

子命令 python

$ uv python --help
Manage Python versions and installations

Usage: uv python [OPTIONS] <COMMAND>

Commands:
  list       List the available Python installations
  install    Download and install Python versions
  find       Search for a Python installation
  pin        Pin to a specific Python version
  dir        Show the uv Python installation directory
  uninstall  Uninstall Python versions

...

比如 uv python dir 查看下载安装目录,uv python install xxx 用来下载并安装指定版本,uv python list 查看已经下载并安装的 Python 版本,等等。

2. 创建虚拟环境

子命令 venv

$ uv venv --help
Create a virtual environment

Usage: uv venv [OPTIONS] [PATH]

Arguments:
  [PATH]  The path to the virtual environment to create

...

比如 uv venv -p <version> --prompt <name>

3. 使用

激活虚拟环境:

source path/to/.venv/bin/activate

可以通过 python3 --version 或者 which python3 等方式,确认环境是否正确启用。

退出虚拟环境:

deactivate

4. 管理并安装包

$ uv pip --help
Manage Python packages with a pip-compatible interface

Usage: uv pip [OPTIONS] <COMMAND>

Commands:
  compile    Compile a `requirements.in` file to a `requirements.txt` file
  sync       Sync an environment with a `requirements.txt` file
  install    Install packages into an environment
  uninstall  Uninstall packages from an environment
  freeze     List, in requirements format, packages installed in an environment
  list       List, in tabular format, packages installed in an environment
  show       Show information about one or more installed packages
  tree       Display the dependency tree for an environment
  check      Verify installed packages have compatible dependencies

...

这里的用法跟 pip 是一致的,加上 uv 前缀即可,比如 uv pip freeze

注意有坑:

如果虚拟环境已经激活,uv pip freeze 肯定是针对当前的虚拟环境,这没有疑问。

在没有激活虚拟环境时,uv 会从当前目录开始,往上级目录、再上级目录 ……,寻找 Python 解释器;如果没有,会指向默认的 $HOME/.local/share/uv/python。所以可能会出现所运行的操作发生在其他虚拟环境上面的问题。为了避免出现这样的指向问题,可以加上 -v 选项,比如:

$ uv pip freeze -v
DEBUG uv x.x.x
DEBUG Searching for default Python interpreter in virtual environments, managed installations, or search path
DEBUG Searching for managed installations at `/home/xxx/.local/share/uv/python`
DEBUG Found managed installation `cpython-x.x.x-linux-x86_64-gnu`
DEBUG Found `cpython-x.x.x-linux-x86_64-gnu` at `/home/xxx/.local/share/uv/python/... ... ...
Using Python 3.x.x environment at: /home/xxx/.local/share/uv/python/cpython-x.x.x-linux-x86_64-gnu
pip @ file:///build/pip-24.3.1-py3-none-any.whl

从 DEBUG 信息里,可以看到 Python 解释器的位置,从而确保所有的操作对应到恰当的虚拟环境上面。

Read More: