在日常 Python 开发中,这些痛点是否让你头疼不已?
🔥 多版本切换复杂 - 项目间 Python 版本冲突频发
🔥 环境管理繁琐 - 手动创建/激活虚拟环境效率低下
🔥 依赖安装缓慢 - 每次 pip install
都像在抽盲盒
🔥 协作体验糟糕 - 团队环境不一致导致"在我机器上是好的"问题
现在,让 uv 彻底改变你的开发体验!
(Astral 团队出品,GitHub 47k+ ⭐ 的新一代 Python 工具链)
✨ 五大核心优势 ✨
🚀 秒级环境创建 - 从 python -m venv
的"漫长等待"到"瞬间完成"
🧠 智能版本控制 - 一句 --python 3.x
精准锁定所需版本
⚡ 闪电依赖安装 - Rust 引擎驱动,速度碾压传统 pip 10 倍+
🔒 严格环境隔离 - 系统/项目环境智能区分,杜绝误操作
🔄 流畅工作流 - 从 uv env
到 uv add
,一套命令搞定全流程
感兴趣的小伙伴不妨一试:
1 集成uv
工具包
pipx
是专门用于安装和隔离Python CLI工具的工具包,其可以确保每个工具独立安装在自己的虚拟环境中,确保不同工具之间的依赖不冲突,适用于CLI工具管理(如 black
、httpie
、tox
、poetry
)。显而易见uv
是个典型的CLI工具。
值得注意的是,uv
官方文档在描述安装时有这样一句话:If installing from PyPI, we recommend installing uv into an isolated environment, e.g., with pipx
,官方文档推荐使用pipx安装,看起来使用pipx
安装是局部最佳实践。
uv
核心功能是管理Python包和虚拟环境的工具,最优做法是本地全局环境集成(本地全局安装) ,这与前端的npm
、pnpm
、yarn
等殊途同归,理由如下:
✅避免重复安装:如果局部安装于每个虚拟环境,则每次创建环境都需重新安装,浪费空间和时间。全局安装一次即可在系统任意位置使用,方便管理多个项目。
✅提升执行效率 :uv
是用 Rust 编写的,速度快、依赖少,适合作为全局工具使用。全局安装能加速包安装和虚拟环境初始化。
✅全局安装不影响环境隔离性 :uv
只用于创建和管理虚拟环境,安装在全局环境不会影响各项目的依赖,每个项目的依赖仍然被隔离在自己的虚拟环境中
1.1 安装(★★★★★)
shell
# 更新你的pip
python -m pip install --upgrade pip
# 如果没有安装好pipx,你需要安装并添加到环境变量
python -m pip install pipx
python -m pipx ensurepath # 添加到用户环境变量
pipx --version
# 安装uv
pipx install uv
# 如果网络不通或者安装失败,可以尝试修改超时时间或者更换镜像源等方法解决,此处不赘述
pipx install uv --pip-args="--index-url https://pypi.tuna.tsinghua.edu.cn/simple"
1.2 验证(★★★)
- 方式1(推荐指数:★★):执行
pipx list
查看
shell
C:\Users\[your_pc_username]>pipx list
venvs are in C:\Users\chengyong\pipx\venvs
apps are exposed on your $PATH at C:\Users\[your_pc_username]\.local\bin
manual pages are exposed at C:\Users\[your_pc_username]\.local\share\man
package uv 0.6.9, installed using Python 3.13.0
- uv.exe
- uvx.exe
- 方式2(推荐指数:★):
cd C:\Users\[your_pc_username]\.local\bin
查看,大概会看到如下结果:
- 方式3(推荐指数:★★★★★):
uv --version
查询是否可以获得版本信息【推荐】
2 uv使用指南
2.1 不同版本Python编译器管理(★★★★)
不同的业务场景使用不同python版本进行适配性开发是很常见的,这就涉及到python多版本管理的问题,Docker容器化是一种解决思路,uv则可以在非容器环境下有所表现,与前端中大家都比较熟悉的nvm
异曲同工。特性如下:
✅ uv 支持系统安装python版本自动发现/自动识别
✅ uv 支持隔离环境多个版本下载、更新、删除及启用
✅ uv 自动识别缺失版本/找不到的版本并在隔离环境安装
✅ 系统python托管时优先生效第一个兼容版本,而uv托管的python优先生效最新的
✅ 多版本管理最核心的应用是在创建python虚拟环境时指定隔离环境下的python版本 (注意:- uv
不能直接修改系统 Python 版本,但可以通过修改系统环境变量或使用工具 pyenv-win
实现。后续补充)
uv python --help:查询帮助
shell
Manage Python versions and installations
Usage: uv.exe 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
Cache options:
-n, --no-cache Avoid reading from or writing to the cache, instead using a temporary directory for the duration of the operation [env:
UV_NO_CACHE=]
--cache-dir <CACHE_DIR> Path to the cache directory [env: UV_CACHE_DIR=]
Python options:
--managed-python Require use of uv-managed Python versions [env: UV_MANAGED_PYTHON=]
--no-managed-python Disable use of uv-managed Python versions [env: UV_NO_MANAGED_PYTHON=]
--no-python-downloads Disable automatic downloads of Python. [env: "UV_PYTHON_DOWNLOADS=never"]
Global options:
-q, --quiet Do not print any output
-v, --verbose... Use verbose output
--color <COLOR_CHOICE> Control the use of color in output [possible values: auto, always, never]
--native-tls Whether to load TLS certificates from the platform's native certificate store [env: UV_NATIVE_TLS=]
--offline Disable network access [env: UV_OFFLINE=]
--allow-insecure-host <ALLOW_INSECURE_HOST> Allow insecure connections to a host [env: UV_INSECURE_HOST=]
--no-progress Hide all progress outputs [env: UV_NO_PROGRESS=]
--directory <DIRECTORY> Change to the given directory prior to running the command
--project <PROJECT> Run the command within the given project directory
--config-file <CONFIG_FILE> The path to a `uv.toml` file to use for configuration [env: UV_CONFIG_FILE=]
--no-config Avoid discovering configuration files (`pyproject.toml`, `uv.toml`) [env: UV_NO_CONFIG=]
-h, --help Display the concise help for this command
-V, --version Display the uv version
Use `uv help python` for more details.
uv python dir:查询默认安装路径及其修改方法
- windows操作系统通常在C盘
shell
C:\Users\[your_pc_username]>uv python dir
C:\Users\[your_pc_username]\AppData\Roaming\uv\python
- 修改默认安装路径的方法:配置环境变量
UV_PYTHON_INSTALL_DIR
(指定用于存储托管 Python 安装的目录)。强烈建议python编译器集中管理及配置,避免出现不必要的冲突及混乱情况。
uv python list:获取python版本列表
- 如果系统上已经安装了Python,
uv
将 detect 并使用它,无需配置。
uv python install:安装最新版本python
uv python install [版本号]:安装指定版本python
注意:uv python install安装python并非全局安装立即生效,仍然是"虚拟环境"隔离安装。
- 安装多个版本python编译器
shell
C:\Users\[your_pc_username]>uv python install 3.12 3.11
Installed 2 versions in 6.78s
+ cpython-3.11.11-windows-x86_64-none
+ cpython-3.12.9-windows-x86_64-none
uv python list
确认下是否安装成功
- 编译器安装在包的默认目录中 ,如
C:\Users\[your_pc_username]\AppData\Roaming\uv\python
,如需修改上文有教程,此处不赘述
uv python list --only-installed
查询已经安装的版本uv python list --managed-python
查询uv托管的python版本(排除系统版本)uv python list --no-managed-python
查询系统python版本
uv python install [包体及版本]
- 如
uv python install [email protected]
,pypy 指的是 PyPy,它是一个高性能的 Python 实现,使用即时编译(JIT)技术来加速 Python 代码的执行。
uv python install --reinstall:重装最新版本python
指定python版本创建虚拟环境
shell
uv venv --python 3.12
uv python uninstall [版本号]:删除不需要版本
指定版本执行(如不存在自动安装Python编译器)
python
uvx [email protected] -c "print('hello world')":
2.2 脚本运行(★)
这个功能我感觉其实没什么用,特别一点的或者"自动化"一点就是uv
可以自动初始化脚本、自动"处理依赖",不感兴趣可以跳过:
shell
uv run --with rich example.py # rich就是具体的依赖项
uv run --with 'rich>12,<13' example.py # 可以对依赖的版本进行指定
uv add --script example.py 'requests<3' 'rich' # 初始化python脚本并指明依赖
2.3 工具(★★★★★)
与前端npx
很像,主要解决的问题是免安装运行,减少对系统环境的混淆及污染。uvx
命令等同于uv tool run
,只是个别名而已。使用 uvx
时,工具会安装到临时的隔离环境中,使用完自动清理。特性如下:
✅ 主要用于快速测试验证(无需激活虚拟环境),无永久环境要求
✅ 涉及的包并不会真的安装或者集成
✅ 功能类似于python -m
但更简洁,执行效率也更高
✅ 一旦工具执行完毕,临时环境会被清理,包不会被永久安装
查询及配置工具目录
shell
# 存放工具本体:UV_TOOL_DIR
# 默认:C:\Users\[your_pc_name]\AppData\Roaming\uv\tools
uv tool dir
查询及配置工具二进制目录
shell
# 存放二进制工具:UV_TOOL_BIN_DIR
# 默认:C:\Users\[your_pc_name]\.local\bin
# uv.exe、uvx.exe就在这个目录
uv tool dir --bin
案例实操
需求:调用
yt-dlp
下载B站指定链接视频。yt-dlp
是一个强大的命令行视频下载工具。
- 确认当前系统环境是否有
yt-dlp
:不存在yt-dlp
shell
pip show yt-dlp # WARNING: Package(s) not found: yt-dlp
-
执行命令
uvx yt-dlp -o "~/Downloads/%(title)s.%(ext)s" --format "bv*[height<=1080]+ba" "https://www.bilibili.com/video/BV1GJ411x7h7"
-o "~/Downloads/%(title)s.%(ext)s"
:保存到用户下载目录,文件名格式为视频标题.扩展名--format "bv*[height<=1080]+ba"
:优先选择1080P及以下画质(避免高画质需要登录)
-
成功执行完成后确认当前系统环境是否有
yt-dlp
:不存在yt-dlp
shell
pip show yt-dlp # WARNING: Package(s) not found: yt-dlp
2.4 项目及依赖管理(★★★★★)
uv
可以像npm/pnpm/yarn
一样初始化及管理你的项目,添加、更新、移除依赖也较为方便。特性如下:
✅ 自动创建虚拟环境(可按需指定python编译器版本)
✅ 自动管理版本锁
✅ 初始化速度较快
✅ 为虚拟环境添加依赖无需显式激活
查询帮助(uv init --help)
shell
C:\Users\[your_pc_username]>uv init --help
Create a new project
Usage: uv init [OPTIONS] [PATH]
Arguments:
[PATH] The path to use for the project/script
Options:
--name <NAME> The name of the project
--bare Only create a `pyproject.toml`
--package Set up the project to be built as a Python package
--no-package Do not set up the project to be built as a Python package
--app Create a project for an application
--lib Create a project for a library
--script Create a script
--description <DESCRIPTION> Set the project description
--no-description Disable the description for the project
--vcs <VCS> Initialize a version control system for the project [possible values: git, none]
--build-backend <BUILD_BACKEND> Initialize a build-backend of choice for the project [possible values: hatch,
flit, pdm, setuptools, maturin, scikit]
--no-readme Do not create a `README.md` file
--author-from <AUTHOR_FROM> Fill in the `authors` field in the `pyproject.toml` [possible values: auto, git,
none]
--no-pin-python Do not create a `.python-version` file for the project
--no-workspace Avoid discovering a workspace and create a standalone project
Python options:
-p, --python <PYTHON> The Python interpreter to use to determine the minimum supported Python version. [env:
UV_PYTHON=]
--managed-python Require use of uv-managed Python versions [env: UV_MANAGED_PYTHON=]
--no-managed-python Disable use of uv-managed Python versions [env: UV_NO_MANAGED_PYTHON=]
--no-python-downloads Disable automatic downloads of Python. [env: "UV_PYTHON_DOWNLOADS=never"]
Cache options:
-n, --no-cache Avoid reading from or writing to the cache, instead using a temporary directory for the
duration of the operation [env: UV_NO_CACHE=]
--cache-dir <CACHE_DIR> Path to the cache directory [env: UV_CACHE_DIR=]
Global options:
-q, --quiet
Do not print any output
-v, --verbose...
Use verbose output
--color <COLOR_CHOICE>
Control the use of color in output [possible values: auto, always, never]
--native-tls
Whether to load TLS certificates from the platform's native certificate store [env: UV_NATIVE_TLS=]
--offline
Disable network access [env: UV_OFFLINE=]
--allow-insecure-host <ALLOW_INSECURE_HOST>
Allow insecure connections to a host [env: UV_INSECURE_HOST=]
--no-progress
Hide all progress outputs [env: UV_NO_PROGRESS=]
--directory <DIRECTORY>
Change to the given directory prior to running the command
--project <PROJECT>
Run the command within the given project directory
--config-file <CONFIG_FILE>
The path to a `uv.toml` file to use for configuration [env: UV_CONFIG_FILE=]
--no-config
Avoid discovering configuration files (`pyproject.toml`, `uv.toml`) [env: UV_NO_CONFIG=]
-h, --help
Display the concise help for this command
-V, --version
Display the uv version
项目初始化
- 方式1:
shell
uv init [your_project_name]
- 方式2:
shell
cd [your_project_name_dir]
uv init
项目目录结构及说明
实战(操作示例)1:创建一个完成项目
- 先看下本地python版本:本地有两个版本,一个是系统安装的(3.13),一个是uv托管的(3.12)
shell
执行:uv python list --only-installed
# 结果
cpython-3.13.0-windows-x86_64-none D:\software\Python\Python313\python.exe
cpython-3.12.9-windows-x86_64-none D:\uv_env\cpython-3.12.9-windows-x86_64-none\python.exe
- 指定3.12创建一个项目
shell
uv init uv_demo --python 3.12
- 查看项目目录结构
- 运行
uv run main.py
观察项目变化,哪些特性需要注意
🎈需要注意,虚拟环境并不会在初始化项目时就具备,而是运行代码时才会自动集成
🎈虚拟环境集成非常快,代码运行并不需要显式的激活
、停用
虚拟环境
shell
uv run main.py
- 给虚拟环境添加
fastapi
依赖:运行uv add fastapi[standard]
或者uv add fastapi --extra standard
- 项目运行:这两个命令是等效的:
uv run fastapi dev main.py
、uv run fastapi dev
(推荐)
python
# main.py
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def home():
return {
"message": "Hello world"
}
- 无需显式地激活虚拟环境就可以获取这些有效信息(省去不必要的麻烦)
shell
uv pip list
uv pip list --format json
uv pip freeze
实战(操作示例)2:仅使用uv创建虚拟环境功能
- 新建一个空文件夹
uv_demo2
- 创建虚拟环境
uv venv --python 3.12
(注意此处使用的是默认的虚拟环境名称也即.venv,uv会自动查找到这个环境)
- 给虚拟环境添加依赖项:
uv pip install fastapi[standard]
- 新建main.py
- 运行命令
- 由于并没有使用uv初始化项目,所以直接运行
fastapi dev main.py
是无法执行的,因为当前运行环境并不具备 - 激活虚拟环境
.\.venv\Scripts\activate
后再执行fastapi dev main.py
即可,使用完毕后退出deactivate
- 由于并没有使用uv初始化项目,所以直接运行
2.5 包发布(★★★)
TestPyPI、PyPI账号(后续使用TestPyPI发布测试)
- 必要条件,不赘述。
- 为了减少对PyPI的污染,后续示例使用TestPyPI账号测试
- Github Action授信认证,会比token方便些,如果是PyPI发布,强烈建议集成好Git Action
发布到TestPyPI
TestPyPI生成token
uv publish
已不支持username+password鉴权,可以使用--token
替代(如果集成好了github会更方便些),创建并拷贝即可
创建一个完整的工程项目(随机生成福利彩票双色球)
uv init pyssq
:项目初始化- 配置
project.toml
,因为要发布到TestPyPI,在这里自定义了tool.uv.index
,后续发布会用到,不赘述
toml
[project]
name = "pyssq"
version = "0.1.0"
description = "Add your description here"
readme = "README.md"
requires-python = ">=3.12"
dependencies = []
[build-system]
requires = ["setuptools>=65", "wheel>=0.38"]
build-backend = "setuptools.build_meta"
# 添加隔离构建配置
[tool.setuptools]
zip-safe = false
[[tool.uv.index]]
name = "testpypi"
url = "https://test.pypi.org/simple/"
publish-url = "https://test.pypi.org/legacy/"
explicit = true
包目录结构及核心代码
- 目录结构
shell
pyssq/
├── pyssq/
│ ├── __init__.py
│ ├── doublecolor.py # 双色球功能
│ └── utils.py # 工具函数
├── tests/
│ ├── test_doublecolor.py
│ └── test_utils.py
├── setup.py
├── README.md
├── LICENSE
└── pyproject.toml
- doublecolor.py代码
python
import random
from typing import List, Dict, Union
from .utils import format_number
class DoubleColorBall:
"""
中国福利彩票双色球生成器
规则:
- 红球: 从1-33中选6个不重复数字
- 蓝球: 从1-16中选1个数字
"""
RED_RANGE = (1, 33)
RED_COUNT = 6
BLUE_RANGE = (1, 16)
BLUE_COUNT = 1
@classmethod
def generate(cls) -> Dict[str, List[int]]:
"""生成一注双色球"""
red = sorted(random.sample(range(*cls.RED_RANGE), cls.RED_COUNT))
blue = random.randint(*cls.BLUE_RANGE)
return {"red": red, "blue": blue}
@classmethod
def generate_batch(cls, n: int = 5) -> List[Dict[str, Union[List[int], int]]]:
"""生成多注双色球"""
if n <= 0:
raise ValueError("注数必须大于0")
return [cls.generate() for _ in range(n)]
@classmethod
def pretty_print(cls, result: Dict[str, Union[List[int], int]]) -> str:
"""美化输出单注结果"""
red = " ".join(format_number(num) for num in result["red"])
blue = format_number(result["blue"])
return f"红球: {red} | 蓝球: {blue}"
@classmethod
def validate(cls, red: List[int], blue: int) -> bool:
"""验证号码是否有效"""
if len(red) != cls.RED_COUNT or len(set(red)) != cls.RED_COUNT:
return False
if any(not (cls.RED_RANGE[0] <= num <= cls.RED_RANGE[1]) for num in red):
return False
if not (cls.BLUE_RANGE[0] <= blue <= cls.BLUE_RANGE[1]):
return False
return True
打包
- 执行
uv build
,默认会将打包好的文件放到dist
目录
发布
--index testpypi
已经提前在pyproject.toml
配置好了,[your_TestPyPI_token]
则拷贝自你自己TestPyPI设置的token
shell
uv publish --index testpypi --token [your_TestPyPI_token]
在新项目中引用发布在TestPyPI的包pyssq
- 项目初始化
shell
uv init pyssq_test
uv venv
cd pyssq_test
- 添加pyssq依赖:注意指定包源
https://test.pypi.org/simple/
shell
uv add --default-index https://test.pypi.org/simple/ pyssq
- 编写
main.py
测试
python
from pyssq import DoubleColorBall
def main():
print(DoubleColorBall.pretty_print(DoubleColorBall.generate()))
if __name__ == "__main__":
main()
# 输出结果:红球: 02 11 16 24 29 31 | 蓝球: 07
集成GitHub Actions并发布到PyPI
创建一个完整python项目
基本沿用发布到TestPyPI的代码,但做了如下修改
- 修改
pyproject.toml
,注释或者删除tool.uv.index
(因为uv默认会发布到PyPI)
toml
[project]
name = "pyssq"
version = "0.1.1"
description = "Add your description here"
readme = "README.md"
requires-python = ">=3.12"
dependencies = []
[build-system]
requires = ["setuptools>=65", "wheel>=0.38"]
build-backend = "setuptools.build_meta"
# 添加隔离构建配置
[tool.setuptools]
zip-safe = false
# [[tool.uv.index]]
# name = "testpypi"
# url = "https://test.pypi.org/simple/"
# publish-url = "https://test.pypi.org/legacy/"
# explicit = true
- 增加
.github\workflows\workflow.yml
,UV_PUBLISH_TOKEN: ${{ secrets.PYPI_API_TOKEN }}
为需要配置的action配置,后续会给出详细示例
yml
name: Publish Python Package
on:
release:
types: [created]
jobs:
build-and-publish:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: '3.x'
- name: Install uv
run: |
python -m pip install --upgrade pip
python -m pip install pipx
pip install uv
- name: Sync dependencies
run: uv venv
- name: Build package
run: uv build
- name: Publish package to PyPI
env:
UV_PUBLISH_TOKEN: ${{ secrets.PYPI_API_TOKEN }}
run: uv publish --token $UV_PUBLISH_TOKEN
uv build编译
PyPI配置GitHub Actions
- OpenID Connect (OIDC) 提供了一种灵活的无凭证机制,用于将 PyPI 包的发布权限委托给可信的第三方服务,如 GitHub Actions。PyPI 用户和项目可以使用受信任的发布者来自动化他们的发布流程,而无需使用 API 令牌或密码。简单说就是配置GitHub Actions后RELEASE会自动同步到PyPI不需要每次都使用uv进行发布,按照提示完成如下配置即可
配置GitHub Actions变量
- 创建github项目并将PyPI账户生成的token按照
.github\workflows\workflow.yml
所要求的配置变量方便后续GitHub Actions使用
git初始化、代码提交
shell
git init
git remote add origin [your_git_rep_rul]
git add .
git commit -m "init commit"
git push -u origin main
uv publish --token [your_pypi_token]发布
对代码进行修改并打tag
- 修改README.md部分内容,测试是否会同步发布到PyPI
shell
git add .
git commit -m "update README.md"
git push -u origin main
git tag -a v0.1.1 -m "Release version v0.1.1"
git push origin v0.1.1
创建RELEASE触发GitHub Actions workflow
- 必须通过 GitHub 界面手动创建
Release
,或者使用gh release create
命令才能触发workflow - 错误方式 :仅仅
git push --tags
不会触发 Actions。
确认GitHub Actions workflow是否正确执行
PyPI确认是否自动同步
在新项目中引用发布在PyPI的包pyssq
- 初始化
shell
uv init uv_publish_test
code uv_publish_test #使用vscode打开项目
uv add pyssq
- 编写
main.py
并测试
python
from pyssq import DoubleColorBall
def main():
print(DoubleColorBall.pretty_print(DoubleColorBall.generate()))
if __name__ == "__main__":
main()
# 执行代码:uv run .\main.py
# 测试结果:红球: 04 09 13 17 25 32 | 蓝球: 10
3 填坑或拓展
3.1 uv自由切换系统环境python版本
💔 问题描述:uv
不能像nvm
那样自由切换系统环境python版本
✅ 解决办法:不要指望uv
为你做所有事情,建议考虑使用py
或者pyenv-win
解决,不赘述。
3.2 uv venv版本混乱的问题
💔 问题描述:uv env
可能会"缓存"你最近一次创建虚拟环境时指定的版本,后续使用uv env
创建默认的虚拟环境时默认会优先调用缓存的虚拟环境而不是系统环境的Python版本
✅ 解决办法:不要指望uv
为你做所有事情,保险期间,每次创建虚拟环境都显式地指定Python版本,如uv init --python 3.13 [your_project_name]