uv usage guide

UV 简易使用指南

UV 简介

今天介绍的uvAstral 公司推出的一款基于 Rust 编写的 Python 包管理工具,旨在成为 “Python 的 Cargo”。

它提供了快速、可靠且易用的包管理体验,在性能、兼容性和功能上都有出色表现,为Python项目的开发和管理带来了新的选择。

为什么用uv

与其他Python中的包管理工具相比,uv更像是一个全能选手,它的优势在于:

  • 速度快:得益于Rust,uv工具的速度让人惊艳,比如安装依赖,速度比其他工具快很多
  • 功能全面:uv 是“一站式服务”的工具,从安装 Python、管理虚拟环境,到安装和管理包,再到管理项目依赖,它统统都能处理得很好
  • 前景光明:背后有风投公司Astral支持,且采用了MIT许可,即使未来出现问题,社区也有应对的办法
  • 使用uv,也可以像NodeJS或者Rust项目那样方便的管理依赖

如何安装

安装uv 非常简单,可以使用官方提供的安装脚本,也可以通过pip来安装

1
2
3
4
5
6

macOS/Linux: curl -LsSf https://astral.sh/uv/install.sh | sh

Windows: powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"

使用 pip 安装:pip install uv

安装之后,可以通过uv help 命令检查是否安装成功

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
An extremely fast Python package manager.

Usage: uv [OPTIONS] <COMMAND>

Commands:
run Run a command or script
init Create a new project
add Add dependencies to the project
remove Remove dependencies from the project
sync Update the project's environment
lock Update the project's lockfile
export Export the project's lockfile to an alternate format
tree Display the project's dependency tree
tool Run and install commands provided by Python packages
python Manage Python versions and installations
pip Manage Python packages with a pip-compatible interface
venv Create a virtual environment
build Build Python packages into source distributions and wheels
publish Upload distributions to an index
cache Manage uv's cache
self Manage the uv executable
version Display uv's version
generate-shell-completion Generate shell completion
help Display documentation for a command

如何使用

用一个简单的new_app项目演示如何管理python项目

使用uv之前,创建一个Python项目对我来说就是创建一个文件夹而已。

使用uv之后,终于有了一些项目的感觉,对于uv,我使用时间也不长,疏漏或错误的地方欢迎指正!

接下来,从创建一个项目开始,演示我使用uv时常用的一些功能。

首先,介绍uv工具主要使用的两个文件:

  • pyproject.toml:定义项目的主要依赖,包括项目名称、版本、描述、支持的 Python 版本等信息
  • uv.lock:记录项目的所有依赖,包括依赖的依赖,且跨平台,确保在不同环境下安装的一致性。这个文件由 uv 自动管理,不要手动编辑

3.1 创建项目

接下来,创建一个项目,使用uv init <project dir>命令。

通过init创建项目之后,uv工具贴心地帮助我们生成了一些默认文件。

其中 hello.py 只是一段演示用的代码,

随后我们可以根据实际的项目需要删除这个代码文件,换成自己的实际代码。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
bot_name = 'Bob'
print(f"Hello, I am {bot_name} How can I assist you?")

while True:
user_input:str = input('You:').lower()

if user_input in ['hi','hello']:
print(f"bot: Hi, how can I help you?")
elif user_input in ['bye','goodbye']:
print(f"bot: Goodbye, have a nice day!")
break
elif user_input in ["+",'add']:
print(f"{bot_name}: I can add two numbers for you.")
try:
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
result = num1 + num2
print(f"{bot_name}: The sum of {num1} and {num2} is {result}")
except ValueError:
print(f"{bot_name}: Please enter valid numbers.")
elif user_input in ["-",'minus']:
print(f"{bot_name}: I can minus two numbers for you.")
try:
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
result = num1 - num2
print(f"{bot_name}: The sum of {num1} and {num2} is {result}")
except ValueError:
print(f"{bot_name}: Please enter valid numbers.")
else:
print(f"{bot_name}: I'm sorry, I don't understand that command.")

注意,uv init创建项目之后,会自动将项目使用Git来管理。

3.2 同步项目依赖:

uv sync

1
2
3
4
5

Using CPython 3.11.4 interpreter at: C:\Python311\python.exe
Creating virtual environment at: .venv
Resolved 1 package in 22ms
Audited in 0.00ms

3.3 运行项目:

uv run <script file>

3.4 添加依赖:

uv add <package>

3.5 删除依赖:

uv remove <package>

3.6 区分开发环境和生产环境:

  • 添加开发依赖:
    uv add --group dev <package>

  • 添加生产依赖:
    uv add --group production <package>

其他

  1. UV 设置环境变量解决Failed to hardlink files警告
1
2
3
4

warning: Failed to hardlink files; falling back to full copy. This may lead to degraded performance.
If the cache and target directories are on different filesystems, hardlinking may not be supported.
If this is intentional, set `export UV_LINK_MODE=copy` or use `--link-mode=copy` to suppress this warning.

解决方案,设置UV_CACHE_DIR环境变量

1
UV_CACHE_DIR = D:/AppData/uv/cache

坚持原创技术分享,您的支持将鼓励我继续创作!
0%