Python
Eco has never been short of package management and environmental management tools, from the classic pip
,virtualenv
until (a time) pip-tools
,conda
and then to the modernized Poetry
,PDM
And so on. Each tool has its areas of specialization, but they also often fragment and complicate a developer's toolchain.
Now, from Astral
Company (well known) Python
Linter. Ruff
(the creator of the uv
came out of nowhere with new possibilities. This program uses Rust
language-written tools that aspire to be a Fast, unified and developer-friendly Python
Package and Project Manager. Its goal is clear: to draw on Rust
ecologically sound Cargo
The successful experience of the company provides a one-stop solution.uv
Not only is it fast, it also integrates environment management, package installation, dependency resolution, project management, and more.
Why UV?
Compared to existing toolsuv
Offers a more modern, efficient option with a central highlight:
- Significant Speed Improvement: Based on
Rust
of compile-time optimizations and efficient concurrent processing capabilities.uv
In common operations such as dependency resolution and package installation, its speed is much faster than traditional tools such as thepip
maybePoetry
, which can often be orders of magnitude faster. The built-in efficient global caching mechanism also makes repetitive operations almost instantaneous. Behind thisRust
language features (e.g., fearless concurrency due to memory safety) and high-quality underlying libraries (e.g., theTokio
,Reqwest
) Credits. - Full functional integration::
uv
Intended to be a "Swiss Army Knife" in the hands of developers, it covers everything from creating and managing virtual environments to installing and locking down dependencies (native support).pyproject.toml
compatiblerequirements.txt
), to running scripts, managing global tools, and even installing specificPython
version of the complete development process. - Modernized project management: Native support
pyproject.toml
(PEP 517/518/621 standard), which is the modern-dayPython
The project's de facto standard configuration file.uv
Ability to clearly handle dependency groupings (e.g. development dependencies) and generate cross-platformuv.lock
Locked file. This lock file accurately records the specific versions and sources of all direct and indirect dependencies, ensuring that a completely consistent environment can be rebuilt on any machine, at any time, for a truly deterministic build. - Good compatibility::
uv
Provides a link to thepip
Highly compatible command interface (uv pip ...
) and can understandrequirements.txt
file format, which makes it possible to migrate existing projects to theuv
The process is relatively smooth. - Active Development and the Future:: By
Astral
The team actively maintains and rapidly iterates using theMIT
Open Source License. High community interest, great development potential and a promising future.
utilization uv
, developers are expected to experience similar Node.js
( npm
/ yarn
/ pnpm
) or Rust
( Cargo
) as fluid and harmonized dependency management workflows.
Installation of UV
mounting uv
Very simple. The official recommendation is to use the provided installation script, as it does not depend on the existing installer on your system. Python
Environment. Of course, by pip
or System Package Manager are also viable options.
- Recommended method (cross-platform scripting)::
# macOS / Linux (bash, zsh, etc.) curl -LsSf https://astral.sh/uv/install.sh | sh # Windows (PowerShell) powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"
take note of: The official script will by default set the
uv
Install to a specific location in the user directory (e.g.Linux
/macOS
(used form a nominal expression)~/.uv/bin
maybeWindows
(used form a nominal expression)%LOCALAPPDATA%\uv\bin
), which is usually located on the system disk (e.g.C:
(disk). - Using pip (requires an existing Python environment)::
pip install uv # 或推荐使用 pipx 进行隔离安装 # pipx install uv
If your
Python
Environmental orpipx
The environment itself is not on the system disk, and installing it in this wayuv
It usually follows their position as well. You can set this by setting thePIPX_HOME
Environment variables to controlpipx
The installation path of the - Using the System Package Manager (example)::
# macOS (Homebrew) brew install uv # Windows (Scoop) # 可以先将 Scoop 本身安装到非系统盘,然后用它安装 uv scoop install uv # Arch Linux pacman -S uv
If, as in the case of
Scoop
Such a package manager is itself configured on a non-system disk, then the applications it installs (including theuv
) are usually installed on the same drive as well. - Using Cargo (requires a Rust environment)::
cargo install uv --locked --git https://github.com/astral-sh/uv
uv
will be installed into theCargo
(used form a nominal expression)bin
Catalog. This can be done by setting theCARGO_HOME
The environment variable sets the entire.cargo
directory (contains downloadedcrates
and compiled products) migrated to a non-system disk.
After the installation is complete, run uv --version
maybe uv help
to verify that the installation was successful.
Configuring the UV Data Storage Location (Advanced)
By default, theuv
It will cache, download the Python
version as well as through the uv tool install
Installed global tools are stored in a default location in the user directory (usually located on the system drive). If you wish to store them on another drive (such as the D:
disk) to save space on the system disk or to reduce SSD
Write, which can be set by setting theenvironment variableto realize.
Here are a few key environment variables:
UV_CACHE_DIR
: Controluv
The location of the cache directory. The cache includes downloaded package files, builtwheel
etc., which may take up more space.UV_PYTHON_INSTALL_DIR
: Control throughuv python install
Downloaded and managedPython
The location where the interpreter will be installed.UV_TOOL_INSTALL_DIR
: Control throughuv tool install
Installed GlobalPython
Storage location for the tool and its isolated environment.
How to set environment variables (example):
Suppose the goal is to combine all uv
The data is stored in the D:\uvdata
Catalog.
- Windows (PowerShell - temporary setting, valid only for the current session):
$env:UV_CACHE_DIR = "D:\uvdata\cache" $env:UV_PYTHON_INSTALL_DIR = "D:\uvdata\python" $env:UV_TOOL_INSTALL_DIR = "D:\uvdata\tools" # 之后在此会话中运行 uv 命令,数据将写入新位置 uv pip install requests
- Windows (System environment variables - permanent settings):
- exist
Windows
Look for "environment variables" in the search bar. - Click "Edit System Environment Variables".
- In the "System Properties" dialog box, click the "Environment Variables..." button. button.
- In the "User Variables" or "System Variables" area (User Variables is recommended unless you need to set them for all users), click "New ..." .".
- Enter the variable name (e.g.
UV_CACHE_DIR
) and variable values (such asD:\uvdata\cache
). - Repeat this for the other two variables.
- Click "OK" to close all dialog boxes.
- crux: Requiredreopen
PowerShell
or command prompt window for the new environment variable to take effect.
- exist
- Linux / macOS (bash/zsh - temporary setup):
export UV_CACHE_DIR="/path/to/non_system_drive/uvdata/cache" export UV_PYTHON_INSTALL_DIR="/path/to/non_system_drive/uvdata/python" export UV_TOOL_INSTALL_DIR="/path/to/non_system_drive/uvdata/tools" # 之后在此会话中运行 uv 命令 uv pip install requests
- Linux / macOS (permanent setup):
topologicalexport
command to your shell configuration file (e.g.~/.bashrc
,~/.zshrc
,~/.profile
), then execute thesource ~/.your_config_file
or restart the terminal for the configuration to take effect.
Important Notes:
- After setting these environment variables, the
uv
The specified paths are automatically used. Make sure that these directories exist and that theuv
Have write access. - Virtual Environment (
.venv
) position:uv venv
Defaults in yourProject root directoryCreate.venv
folder. Therefore.As long as your project itself is located on a non-system disk (such as theD:\myproject
), then.venv
Naturally, it will also be on that disk. It is not usually necessary to provide a basis for.venv
Configure the paths individually to avoid the system disk. Of course, you can also avoid the system disk byuv venv /path/to/custom/env
Explicitly specify where the virtual environment is created, but this is more for customizing the environment path than solving system disk storage issues.
By configuring these environment variables appropriately, you can effectively manage the uv
generated, directing it to a storage location where space is more plentiful or more appropriate.
UV Core Concepts
in using uv
When managing a project, it is important to understand the following core concepts:
pyproject.toml
: ModernPython
Standard profile of the project (based on PEP 517/518/621).uv
Use it to define project metadata (name, version, description, etc.), requiredPython
Version (requires-python
) and the main dependencies of the project (dependencies
) and optional dependency groups (e.g.dev-dependencies
(b). It is the "single source of truth" for project configuration.uv.lock
:: Byuv
A locked file that is automatically generated and managed. It accurately records the specific version numbers and source hashes of all the project's dependencies (including indirect dependencies). Its core value is to ensure thatReproducibility of the environment: whenever and wherever it is based on the sameuv.lock
file installs the dependencies, you get exactly the same package combination.This file should not be edited manuallyThe- Virtual Environment (
.venv
)::uv
Highly recommended and simplifies the use of virtual environments. It defaults to creating a virtual environment in the project root directory called.venv
of isolated environments to house project dependencies. Most of theuv
command (e.g.add
,sync
,run
) are automatically detected and operations are performed in this environment, avoiding the need for globalPython
Pollution of the environment.
Managing Python Projects with UV
The following demonstrates, through a complete process, how to use the uv
to create and manage a Python
Project.
Initialize the project (uv init
)
utilization uv init
command can quickly build the basic structure of a new project.
# 确保在期望的驱动器上操作,例如在 D: 盘
# D:
# mkdir my_uv_project
# cd my_uv_project
# 初始化名为 my_uv_project 的项目
uv init my_uv_project
cd my_uv_project
After implementation.uv
will be in my_uv_project
directory is generated:
.git/
cap (a poem).gitignore
: Automatic initializationGit
repository, and provides a commonPython
sports event.gitignore
Documentation..python-version
: Documentation of project proposals or requests forPython
version (e.g.3.12
).uv
will refer to this document to select or install the appropriatePython
Interpreter.pyproject.toml
: The core configuration file for the project, containing the project name, version, and description,Python
Version requirements and emptydependencies
List.README.md
: an emptyREADME
Documentation.src/my_uv_project/__init__.py
: A basic source code structure (if using thesrc
(Layout). Or a simplehello.py
Example file.
# pyproject.toml 示例内容 (可能略有不同)
[project]
name = "my-uv-project"
version = "0.1.0"
description = "Add your description here"
readme = "README.md"
requires-python = ">=3.12" # 根据系统情况或指定版本生成
dependencies = []
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"
# uv 可能还会添加 tool.uv 相关配置
Create and synchronize the environment (uv venv
, uv sync
)
After the project is initialized, you need to create the virtual environment and synchronize the dependency state (even if it's an empty dependency, the first synchronization generates the uv.lock
).
- Create a virtual environment (
uv venv
)::
even thoughuv sync
and other commands automatically create.venv
, but can also be created explicitly:# 创建默认的 .venv 环境 (uv 会根据 .python-version 或系统查找合适的 Python) # 这个 .venv 会在当前项目目录下创建 uv venv # 创建时指定 Python 版本 uv venv --python 3.11 # 指定自定义环境名称 (不常用,因为 uv 生态默认与 .venv 配合) uv venv my_custom_env
If a manual operating environment is required (e.g., using a non
uv
managed tool), then you need to activate it:# Linux/macOS source .venv/bin/activate # Windows (PowerShell) .venv\Scripts\Activate.ps1 # Windows (CMD) .venv\Scripts\activate.bat
re-emphasize: For the vast majority of
uv
Command (add
,remove
,sync
,run
etc.).Manual activation of the environment is usually not required(math.) genusuv
will automatically find and use the.venv
The - Synchronization environment (
uv sync
)::
This is one of the core commands used to ensure that the state of the virtual environment is the same as the state of thepyproject.toml
(viauv.lock
documents) orrequirements.txt
The file is precisely consistent. The first time it is run, it will:- retrieve
pyproject.toml
of the dependency definition. - Performs dependency resolution.
- generating
uv.lock
Documentation. - exist
.venv
Install all necessary packages (initially only the project itself may be available as an editable package).
# 在项目根目录运行 uv sync
After execution, you will see
.venv
directory is created or updated, and auv.lock
Documentation. - retrieve
Managing dependencies (uv add
, uv remove
, uv lock
)
this is uv
The most commonly used functions, recommended for use based on the pyproject.toml
of the workflow.
- Add a dependency (
uv add
):
Add the package to thepyproject.toml
(used form a nominal expression)[project.dependencies]
section and automatically installs or updates to the.venv
environment. At the same timeuv.lock
It will also be updated.# 添加最新稳定版的 pandas uv add pandas # 添加 requests,并指定版本约束 uv add "requests>=2.20,<3.0" # 添加开发依赖 (如测试框架 pytest),会写入 [tool.uv.dev-dependencies] uv add pytest --dev uv add ruff --dev # 从 Git 仓库添加依赖 uv add git+https://github.com/psf/requests.git # 添加本地路径的包 (以可编辑模式安装) uv add -e ../my_local_library
- Remove dependencies (
uv remove
):
surname Congpyproject.toml
removes the specified package from the.venv
environment to uninstall it and downstream dependencies that are no longer needed.# 移除 pandas uv remove pandas # 移除开发依赖 pytest uv remove pytest --dev
- Updating dependencies:
- Update all dependencies to the
pyproject.toml
The latest version allowed by the constraints in and regenerate theuv.lock
::# 1. 更新 lock 文件 uv lock --upgrade # 2. 应用 lock 文件更新到环境 uv sync
- Update only specific packages to the latest version:
# 方法一:指定包更新 lock 文件,然后同步 uv lock --upgrade-package requests uv sync # 方法二:直接 'add' 最新版 (也会更新 lock 和环境) uv add requests@latest
- Update all dependencies to the
- Manual editing
pyproject.toml
empress:
If you directly modify thepyproject.toml
dependency list in the file, you need to perform the following two steps to make the changes take effect:uv lock
:: Based onpyproject.toml
The new content recalculates the dependencies and updates theuv.lock
Documentation.uv sync
:: Willuv.lock
The state in the file is synchronized to the.venv
Virtual environments.
Run the code and commands (uv run
)
uv run
be uv
An extremely convenient feature provided. It allows you to set the uv
Execution in the context of a managed virtual environment Python
scripts or any commands.No need to manually activate the environment beforehand. This is uv
One of the key features of a streamlined workflow that is well worth mastering.
Working Principle:
When you execute the uv run <command> [args...]
Hours:
- Automatic discovery of the environment::
uv
will automatically find the current directory and the parent directory of the.venv
Virtual environments. - Internal configuration environment execution:
- with regards to
uv run python your_script.py
Such an order.uv
will directly call the.venv
directory of thePython
Interpreter (.venv/bin/python
maybe.venv/Scripts/python.exe
) to run the script. - with regards to
uv run pytest tests/
maybeuv run ruff format .
Such an order.uv
be sure toInside the child process that executes the commandThe interim will be.venv/bin
(or.venv/Scripts
) directory is added to the systemPATH
at the top of the environment variables. This way, even if you don't activate the environment, the operating system will be able to find and execute the command line tools installed in the virtual environment (such as thepytest
,ruff
).
- with regards to
How do I run a Python file?
To run the project's Python
file (e.g. src/my_package/main.py
or the root directory of the app.py
), which is recommended:
uv run python src/my_package/main.py
# 或者
uv run python app.py
dominance:
- No manual activation required: eliminates the need to enter
source .venv/bin/activate
maybe.venv\Scripts\Activate.ps1
The hassle of the program is greatly simplified for day-to-day development and script execution. - Environmental Consistency Assurance: Ensure that your code and tools always run in the correct virtual environment for your project configuration.
- Simplifying CI/CD Scripting: In automated processes such as
GitHub Actions
,GitLab CI
) can be used directly in theuv run
Perform tasks such as testing, building, and deploying without having to deal with complex environment activation logic.
more uv run
typical example:
# 运行安装在环境中的 pytest 测试
uv run pytest tests/
# 运行安装在环境中的 ruff 代码格式化
uv run ruff format .
# 运行任意系统命令,uv 会确保 .venv/bin 在 PATH 中
uv run alembic upgrade head
# 向脚本传递参数
uv run python your_script.py --input data.csv --output results.json
When do I still need to activate manually?
Manual activation (source activate
or similar commands) has been greatly reduced. Probably mainly in the same Shell session you need:
- Frequent interactive running of multiple commands that depend on the virtual environment (e.g., directly typing the
python
Go to the interpreter and then thepytest
And again.ruff
). - Use some specific environment variables that depend on the activation script settings (other than the
PATH
(other than) the nonPython
Tools.
But for most day-to-day development tasks, theuv run
The automated environmental management provided is more convenient and efficient.
utilization requirements.txt
(workflow compatible)
even though uv
Recommended pyproject.toml
but it also fully supports traditional requirements.txt
workflows, and provides pip
Compatible command interface and faster.
- Install dependencies (
uv pip install
):# 安装单个包 uv pip install flask # 从 requirements 文件安装 uv pip install -r requirements.txt # 可以同时指定多个文件 uv pip install -r requirements.txt -r requirements-dev.txt # 安装当前项目 (以可编辑模式) uv pip install -e .
- Uninstalling dependencies (
uv pip uninstall
):uv pip uninstall flask # 从文件批量卸载 uv pip uninstall -r requirements-to-remove.txt
- Generate a list of dependencies (
uv pip freeze
):# 输出当前环境安装的所有包 (类似 pip freeze) uv pip freeze > requirements.lock.txt # 常用于生成锁定文件
- Compile dependencies (
uv pip compile
) (Recommendedrequirements
workflow):
This approach is similar topip-tools
. You maintain arequirements.in
file (which contains only direct dependencies), and then use theuv
Generate the exact version of therequirements.txt
Lock the file.# requirements.in 内容示例: # flask # requests>=2.25 # 生成 requirements.txt uv pip compile requirements.in -o requirements.txt # 为开发环境编译 (假设有 requirements-dev.in) # uv pip compile requirements-dev.in -o requirements-dev.txt
- Synchronization environment (
uv pip sync
):
Based on one or morerequirements.txt
file's contents, accurately synchronizing the virtual environment: installing missing packages and removing redundant packages.# 同步主依赖和开发依赖 uv pip sync requirements.txt requirements-dev.txt
- View Installed Packages (
uv pip list
,uv pip show
,uv pip tree
):uv pip list # 列出已安装的包和版本 uv pip show flask # 显示 flask 包的详细信息 uv pip tree # 以树状结构显示依赖关系
Managing Python Versions (uv python
)
uv
Built-in download, management and selection Python
version of the feature, similar to the pyenv
. (Remember that it is possible to pass UV_PYTHON_INSTALL_DIR
Environment variables configure these Python
(mounting position)
- List available and installed versions (
uv python list
):# 列出已安装和当前使用的版本 uv python list # 显示所有可供下载的补丁版本 # uv python list --all-versions # 只显示已安装的版本 uv python list --only-installed
- Install the Python version (
uv python install
):# 安装最新的稳定版 (如果尚未安装) uv python install # 安装特定版本 uv python install 3.11.5 # 安装 3.10 系列的最新可用版 uv python install 3.10
uv
will send the downloadedPython
Install into its managed directory (uv python dir
The path can be viewed, subject toUV_PYTHON_INSTALL_DIR
impact). - Uninstall the Python version (
uv python uninstall
):uv python uninstall 3.10.8 # 卸载 3.11 系列所有已安装版本 uv python uninstall 3.11
- Fixed project Python version (
uv python pin
):
Create or update in the current directory.python-version
file, which declares that the project should use thePython
Version.uv python pin 3.11
beyond
uv venv
,uv run
,uv sync
and other commands will prioritize finding and using this version. - Find the Python interpreter (
uv python find
):# 查找匹配 3.12 的 Python 解释器路径 uv python find 3.12
Manage global tools (uv tool
)
uv
It could be like pipx
As always, installing and running the global Python CLI
tools, and isolate each tool in a separate environment to avoid dependency conflicts. (Similarly, the storage location of the tools can be accessed through the UV_TOOL_INSTALL_DIR
environment variable configuration)
- Running tools (ad-hoc implementation,
uv tool run
maybeuvx
):
Temporarily downloads (if needed) and executes the tool, and does not retain it after execution. This is very handy for one-time use tools.uvx
beuv tool run
The abbreviated form of.# 运行 ruff 检查当前目录,临时下载 ruff uv tool run ruff check . # 使用简写 uvx uvx ruff check . # 如果命令名 (http) 和包名 (httpie) 不同,使用 --from uvx --from httpie http https://example.com
- Installation of global tools (
uv tool install
):
Install the tool and its dependencies into theuv
managed standalone environment and link its executable to the user path (may require restarting the terminal or manually configuring thePATH
(to be able to call it directly). This is similar to thepipx install
Theuv tool install black uv tool install httpie
Once installed, it can theoretically be run directly from anywhere
black .
maybehttp https://example.com
The - List installed tools (
uv tool list
):uv tool list
- Upgrade Tool (
uv tool upgrade
):uv tool upgrade black # 升级所有已安装工具 # uv tool upgrade --all
- Uninstallation Tools (
uv tool uninstall
):uv tool uninstall black
- View the tool installation directory (
uv tool dir
):
demonstrateuv
The root path where global tools and their environments are stored (subject to theUV_TOOL_INSTALL_DIR
impact).
Managing the cache (uv cache
)
uv
Use the global cache to speed up the package download and build process. (The cache location can be accessed via the UV_CACHE_DIR
environment variable configuration)
- Clearing the cache (
uv cache clean
):
Delete alluv
Cached content. This can be used to resolve potential cache pollution problems or to free up disk space.uv cache clean
- Display the cache directory (
uv cache dir
):
View currentuv
The location where the cache file is stored (subject toUV_CACHE_DIR
impact).
Single-script project management
For some simple widgets or scripts, theuv
Supports a very lightweight management approach: embedding project metadata and dependencies directly into the Python
in a special comment block in the script header.
- Initialization Script (
uv init --script
):# 创建一个名为 my_script.py 的脚本,并指定 Python 版本要求 uv init --script my_script.py --python ">=3.10"
This will be in the
my_script.py
A comment block similar to the following is generated at the beginning of the file:#!/usr/bin/env python # /// script # requires-python = ">=3.10" # dependencies = [ # ] # /// import sys def main() -> None: print(f"Hello from {sys.argv[0]}!") if __name__ == "__main__": main()
- Add/remove script dependencies (
uv add/remove --script
):
Can be used directlyadd
mayberemove
order, in conjunction with the--script
parameter to modify the dependency list in the script header.# 为 my_script.py 添加 requests 依赖 uv add --script my_script.py requests # 从 my_script.py 移除 requests 依赖 uv remove --script my_script.py requests
These commands directly modify the script file header's
dependencies
List. - Run the script (
uv run
):
Direct useuv run
The script can be executed.uv run my_script.py
uv
automatically reads the metadata in the script header, creates a temporary virtual environment on demand, installs the dependencies declared in it, and then executes the script. This approach is ideal for distributing single, self-containedPython
Tool Script.
Future prospects and recommendations
uv
It is undoubtedly an ambitious and extremely fast-growing project. It draws on Rust
The performance benefits and well-designed, harmonized interfaces are expected to significantly improve the Python
Developer's package and environment management experience. Its core values aretempocap (a poem)conformThe
(go ahead and do it) without hesitating uv
Relatively young, the ecosystem (e.g., IDE deep integration, third-party tutorial resources) is still growing rapidly, and commands or behaviors may be slightly tweaked between versions due to its active iteration (it is recommended to keep an eye on its changelog).
But for the time being.uv
The core functionality has been quite stable and robust.
suggestion:
- with regards toincoming
Python
sports eventIt is highly recommended that the direct adoption ofuv
. It delivers a refreshing and efficient management experience right from the start. - For thoseSuffering from existing toolchains (e.g.
pip
+virtualenv
+pip-tools
(Combined) complexity or performance issues plaguethe developers and teams thatuv
is a very attractive alternative and worth investing time in evaluating and migrating to try. - For those who have been deeply using
Poetry
maybePDM
and rely on their specific advanced features (e.g., complex plug-in systems, fine-grained release process management), the migration may require a more careful evaluation, weighing theuv
The speed and simplicity that comes with it versus the potential loss of specific features.
uv
is fast becoming Python
A force to be reckoned with in development workflows, its emergence may be as important as the ruff
Like, in the Python
The community has sparked a new wave of tool innovation. Its future deserves our continued attention.