Skip to content

Instantly share code, notes, and snippets.

@dipenparmar12
Created December 8, 2025 05:37
Show Gist options
  • Select an option

  • Save dipenparmar12/0bd6e670482eb4f48fbda7ae5da0fe14 to your computer and use it in GitHub Desktop.

Select an option

Save dipenparmar12/0bd6e670482eb4f48fbda7ae5da0fe14 to your computer and use it in GitHub Desktop.
Pyenv and UV comprehensive quick reference (Cheatsheet)

The Ultimate Pyenv Cheatsheet

A comprehensive quick reference guide for pyenv, the simple Python version manager. This cheatsheet is designed for both beginners and advanced users, covering everything from basic Python version management to advanced workflows and plugin usage.

Author: MiniMax AgentDate: 2025-11-19

1. Quick Start

Get up and running with pyenv in minutes.

Task Command Notes
Install pyenv `curl https://pyenv.run bash` One-line installer for Unix-based systems (macOS/Linux).
List available versions pyenv install --list Shows all Python versions available for installation.
Install a Python version pyenv install 3.12.0 Installs Python 3.12.0 on your system.
List installed versions pyenv versions Shows all Python versions currently installed via pyenv.
Set global version pyenv global 3.12.0 Sets Python 3.12.0 as the default for all shells.
Set local version pyenv local 3.12.0 Creates .python-version file for current directory.
Set shell version pyenv shell 3.12.0 Sets Python 3.12.0 for current shell session only.
Check current version pyenv version Shows the Python version currently active.

2. Installation Guide

pyenv supports macOS, Linux, and Windows (via WSL or pyenv-win).

OS Method Command Notes
macOS Official Installer (Recommended) `curl https://pyenv.run bash` Includes pyenv and popular plugins.
Homebrew brew install pyenv Requires manual shell configuration.
Git Manual git clone https://github.com/pyenv/pyenv.git ~/.pyenv Manual installation, full control.
Linux Official Installer (Recommended) `curl https://pyenv.run bash` Works on most Linux distributions.
Git Manual git clone https://github.com/pyenv/pyenv.git ~/.pyenv For users who prefer manual setup.
Windows WSL (Recommended) Use Linux installation in WSL Full pyenv functionality in WSL environment.
pyenv-win choco install pyenv-win Native Windows version with limited functionality
Any OS pip pip install pyenv-win Only for Windows pyenv-win.

Shell Configuration

Add these lines to your shell configuration file (.bashrc, .zshrc, .bash_profile, etc.):

For Bash/Zsh:

export PYENV_ROOT="$HOME/.pyenv"
command -v pyenv >/dev/null || export PATH="$PYENV_ROOT/bin:$PATH"
eval "$(pyenv init -)"

For Fish:

set -Ux PYENV_ROOT $HOME/.pyenv
pyenv init - | source

Verifying Installation

# Check if pyenv is properly installed
pyenv --version
# Check current Python version
python --version
# Verify shell integration
pyenv init

3. Core Commands Reference

A quick lookup table for pyenv's primary commands.

Command Description Aliases
pyenv install Installs a specific Python version. -
pyenv uninstall Removes an installed Python version. pyenv uninstall
pyenv versions Lists all installed Python versions. pyenv version
pyenv version Shows the currently active Python version. -
pyenv versions Lists all installed Python versions with indicators. -
pyenv global Sets the global Python version. -
pyenv local Sets the local project Python version (creates .python-version). -
pyenv shell Sets the shell-specific Python version. -
pyenv which Shows the path to the Python executable being used. -
pyenv whence Lists all Python versions that contain a specific command. -
pyenv init Initializes pyenv for your shell. -
pyenv rehash Regenerates pyenv shims directory. -
pyenv update Updates pyenv and its plugins. -
pyenv doctor Checks for potential pyenv configuration problems. -

4. Python Version Management

Basic Version Operations

Task Command Example Notes
List available versions pyenv install --list pyenv install --list Shows all available Python versions for installation.
Install a specific version pyenv install <version> pyenv install 3.11.7 Downloads, compiles, and installs Python version.
Install latest patch pyenv install <major>.<minor> pyenv install 3.11 Installs the latest patch version for given major.minor.
Uninstall a version pyenv uninstall <version> pyenv uninstall 3.10.0 Removes an installed Python version.
List installed versions pyenv versions pyenv versions Shows all installed versions with current version marked.
Check current version pyenv version pyenv version Shows the currently active Python version.

Version Selection Strategies

Scope Command Example Effect Priority
Global pyenv global <version> pyenv global 3.12.0 Sets default Python version for all shells and sessions. Lowest
Local pyenv local <version> pyenv local 3.11.0 Creates .python-version file in current directory. Medium
Shell pyenv shell <version> pyenv shell 3.10.0 Sets version for current shell session only. Highest
Clear pyenv global --unset pyenv global --unset Removes global version setting. -
Clear pyenv local --unset pyenv local --unset Removes local version setting (deletes .python-version). -
Clear pyenv shell --unset pyenv shell --unset Removes shell-specific version setting. -

Version Priority

pyenv resolves Python versions in this order (highest to lowest priority):

  1. Shell-specific (pyenv shell)

  2. Local project (.python-version file)

  3. Global (pyenv global)

# Example of priority in action
pyenv global 3.11.0      # Set global to Python 3.11
cd ~/my-project          # Switch to project directory
pyenv local 3.12.0       # Set local to Python 3.12 (creates .python-version)
pyenv shell 3.10.0       # Set shell to Python 3.10
python --version         # Returns Python 3.10.0 (shell takes priority)
# Exit shell and return
exit                    # Exit the shell
cd ~/my-project
python --version        # Returns Python 3.12.0 (local takes priority)
# Change to different directory
cd ~
python --version        # Returns Python 3.11.0 (global takes priority)

5. Advanced Installation Options

Build Dependencies

OS Dependencies Installation Command
macOS Xcode Command Line Tools xcode-select --install
Ubuntu/Debian build-essential, libssl-dev, zlib1g-dev, libbz2-dev, libreadline-dev, libsqlite3-dev, wget, curl, llvm, libncursesw5-dev, xz-utils, tk-dev, libxml2-dev, libxmlsec1-dev, libffi-dev, liblzma-dev, git sudo apt update && sudo apt install -y build-essential libssl-dev zlib1g-dev libbz2-dev libreadline-dev libsqlite3-dev wget curl llvm libncursesw5-dev xz-utils tk-dev libxml2-dev libxmlsec1-dev libffi-dev liblzma-dev
CentOS/RHEL gcc, openssl-devel, bzip2-devel, libffi-devel, readline-devel, sqlite-devel, wget sudo yum install gcc openssl-devel bzip2-devel libffi-devel readline-devel sqlite-devel wget
Fedora gcc, openssl-devel, bzip2-devel, libffi-devel, readline-devel, sqlite-devel, wget sudo dnf install gcc openssl-devel bzip2-devel libffi-devel readline-devel sqlite-devel wget
Arch Linux base-devel, openssl, zlib, readline, sqlite sudo pacman -S base-devel openssl zlib readline sqlite

Environment Variables for Custom Builds

# Set custom Python installation prefix
export PYTHON_BUILD_CURL_OPTS="--retry 5 --retry-delay 1"
export PYTHON_BUILD_WGET_OPTS="--tries 5 --wait=1"
# Use custom OpenSSL installation
export OPENSSL_ROOT_DIR=/usr/local/opt/openssl
export LDFLAGS="-L/usr/local/opt/openssl/lib"
export CPPFLAGS="-I/usr/local/opt/openssl/include"
# Use custom Python configuration
export PYTHON_CONFIGURE_OPTS="--enable-optimizations --with-openssl=/usr/local/opt/openssl"

Installing Specific Variants

# Install with debugging symbols
PYTHON_CONFIGURE_OPTS="--with-pydebug" pyenv install 3.12.0
# Install shared library
PYTHON_CONFIGURE_OPTS="--enable-shared" pyenv install 3.12.0
export LD_LIBRARY_PATH="$(pyenv root)/versions/3.12.0/lib"
# Install with custom optimization
MAKE_OPTS="-j4" pyenv install 3.12.0
# Skip installing optional modules
PYTHON_CONFIGURE_OPTS="--without-ensurepip" pyenv install 3.12.0

6. Plugin Management

pyenv plugins extend its functionality. Here are the most popular ones:

Popular Plugins

Plugin Purpose Installation Command
pyenv-virtualenv Virtual environment management git clone https://github.com/pyenv/pyenv-virtualenv.git $(pyenv root)/plugins/pyenv-virtualenv
pyenv-update Auto-update pyenv and plugins git clone https://github.com/pyenv/pyenv-update.git $(pyenv root)/plugins/pyenv-update
pyenv-which-ext Enhanced pyenv which command git clone https://github.com/pyenv/pyenv-which-ext.git $(pyenv root)/plugins/pyenv-which-ext
pyenv-doctor Troubleshooting and health checks git clone https://github.com/pyenv/pyenv-doctor.git $(pyenv root)/plugins/pyenv-doctor
python-build Advanced Python build options Usually included with pyenv
pyenv-pip-rehash Automatic shim rehashing after pip install git clone https://github.com/pyenv/pyenv-pip-rehash.git $(pyenv root)/plugins/pyenv-pip-rehash
pyenv-default-packages Auto-install packages for new Python versions git clone https://github.com/pyenv/pyenv-default-packages.git $(pyenv root)/plugins/pyenv-default-packages
pyenv-win Windows support Used for Windows pyenv-win installation

Managing Plugins

# Update all plugins
pyenv update
# Update specific plugin
cd $(pyenv root)/plugins/pyenv-virtualenv
git pull
# List installed plugins
ls -la $(pyenv root)/plugins/
# Remove a plugin
rm -rf $(pyenv root)/plugins/plugin-name

7. Virtual Environment Integration

With pyenv-virtualenv plugin, you can create and manage virtual environments that automatically use pyenv-managed Python versions.

Basic Virtual Environment Management

Task Command Example Notes
Create virtualenv pyenv virtualenv <version> <name> pyenv virtualenv 3.12.0 myproject Creates virtual environment.
Create from current version pyenv virtualenv <name> pyenv virtualenv myproject Uses current Python version.
List virtualenvs pyenv virtualenvs pyenv virtualenvs Shows all virtual environments.
Activate virtualenv pyenv activate <name> pyenv activate myproject Activates the virtual environment.
Deactivate virtualenv pyenv deactivate pyenv deactivate Returns to system Python.
Delete virtualenv pyenv uninstall <name> pyenv uninstall myproject Removes the virtual environment.

Advanced Virtualenv Features

# Create virtualenv with site-packages from system
pyenv virtualenv --system-site-packages 3.12.0 myproject
# Set local Python version and create virtualenv in one command
pyenv local myproject
# Integrate with existing project structure
mkdir myproject && cd myproject
pyenv virtualenv 3.11.0 myproject
pyenv local myproject  # Creates .python-version and activates

Integration with Common Tools

With Poetry:

# Set Python version first
pyenv local 3.12.0
# Then use Poetry (it will use the pyenv version)
poetry init
poetry install

With Virtualenvwrapper:

# pyenv-virtualenvwrapper provides compatibility
pyenv virtualenvwrapper
mkvirtualenv myproject  # Uses pyenv's Python version

With Pipenv:

# Set Python version first
pyenv local 3.12.0
# Then use Pipenv (it will use the pyenv version)
pipenv --python 3.12.0

8. Shims and PATH Management

pyenv works by inserting a shims directory at the front of your PATH. These shims are lightweight wrapper scripts that intercept commands and redirect them to the appropriate Python version.

Understanding Shims

# Check where shims are located
pyenv init
# Output: export PATH="/home/user/.pyenv/shims:$PATH"
# List all shims
ls $(pyenv root)/shims/
# Check which Python version a command uses
pyenv which python
pyenv which pip
pyenv which pytest
# Check all Python versions that provide a command
pyenv whence python

Maintaining Shims

# Regenerate shims (run after installing new Python versions)
pyenv rehash
# Check shim health
pyenv doctor
# Manually refresh shims for a specific command
pyenv which python  # This forces rehash for python

PATH Debugging

# Check your current PATH
echo $PATH
# Verify shims are at the front
echo $PATH | tr ':' '\n' | grep pyenv
# Check which python is being used
which python
type python
command -v python
# Force pyenv to take precedence
export PATH="$(pyenv root)/shims:$PATH"

9. Project-Specific Configuration

.python-version File

The .python-version file contains the Python version specification for a project:

# Content of .python-version file
3.11.7
# Or with patch version specification
3.11
# Or with more complex specification (if using pyenv-ext plugin)
pypy3.9-7.3.12

Project Workflow Examples

Starting a new project:

mkdir my-new-project && cd my-new-project
pyenv local 3.12.0  # Creates .python-version and sets version
python --version    # Verify Python 3.12.0 is active

Cloning an existing project:

git clone https://github.com/user/project.git
cd project
python --version    # Automatically uses version from .python-version

Managing multiple project versions:

# Project 1 - Python 3.11
cd ~/projects/legacy-project
pyenv versions      # Shows: * 3.11.0 (set by /home/user/projects/legacy-project/.python-version)
# Project 2 - Python 3.12
cd ~/projects/new-project
pyenv versions      # Shows: * 3.12.0 (set by /home/user/projects/new-project/.python-version)

Advanced Configuration

Multiple versions fallback:

# .python-version file can specify multiple versions (pyenv-win behavior)
3.12.0
3.11.7
3.10.0
# pyenv will try versions in order

Development vs Production environments:

# Development
pyenv local 3.12.0-dev
# Production deployment
pyenv local 3.12.0
# Or use different Python implementations
pyenv local pypy3.9-7.3.12

10. Integration with Development Tools

IDE Integration

VS Code:

// .vscode/settings.json
{
    "python.defaultInterpreterPath": "~/.pyenv/shims/python",
    "python.terminal.activateEnvironment": false
}

PyCharm:

  • Go to Project Interpreter settings

  • Add Local interpreter

  • Point to ~/.pyenv/versions/{version}/bin/python

Vim/Neovim:

" .vimrc or init.vim
let g:python_host_prog = expand('~/.pyenv/shims/python')
let g:python3_host_prog = expand('~/.pyenv/shims/python3')

Docker Integration

# Dockerfile
RUN pyenv install 3.12.0 && pyenv global 3.12.0
ENV PYENV_ROOT="/root/.pyenv"
ENV PATH="$PYENV_ROOT/bin:$PATH"
RUN pyenv rehash

CI/CD Integration

GitHub Actions:

steps:
  - uses: actions/checkout@v4
  - name: Set up Python
    uses: actions/setup-python@v4
    with:
      python-version: '3.12'
      # Or use a specific version
      python-version: '3.11.7'

GitLab CI:

image: ubuntu:22.04
before_script:
  - apt-get update
  - apt-get install -y curl git gcc make libssl-dev zlib1g-dev libbz2-dev libreadline-dev libsqlite3-dev wget xz-utils tk-dev libxml2-dev libxmlsec1-dev libffi-dev liblzma-dev
  - curl https://pyenv.run | bash
  - echo 'export PYENV_ROOT="$HOME/.pyenv"' >> ~/.bashrc
  - echo 'command -v pyenv >/dev/null || export PATH="$PYENV_ROOT/bin:$PATH"' >> ~/.bashrc
  - echo 'eval "$(pyenv init -)"' >> ~/.bashrc
  - . ~/.bashrc
  - pyenv install 3.12.0
  - pyenv global 3.12.0
test:
  script:
    - python --version
    - pip install -r requirements.txt
    - python -m pytest

11. Troubleshooting

Common Issues and Solutions

Issue Symptom Solution
Wrong Python version python --version shows unexpected version 1. Check pyenv versions2. Check current directory for .python-version3. Check pyenv shell --unset
Command not found pyenv: command not found 1. Ensure pyenv is in PATH2. Run eval "$(pyenv init -)" in shell3. Check shell config files
Build failures Python installation fails during make 1. Install build dependencies2. Check logs in /tmp/python-build*.log3. Try with verbose mode
Shim issues which python doesn't show pyenv path 1. Run pyenv rehash2. Check PATH order3. Verify shims directory exists
Virtualenv not activating Virtualenv commands not working 1. Install pyenv-virtualenv plugin2. Run pyenv virtualenvs3. Try pyenv activate instead
Global version not working Local settings override global 1. Check pyenv versions2. Remove local settings with pyenv local --unset3. Check for .python-version files
Shell restart required Changes to config not taking effect 1. Restart shell: exec "$SHELL"2. Source config: source ~/.bashrc3. Check shell: echo $SHELL

Diagnostic Commands

# Comprehensive health check
pyenv doctor
# Check pyenv installation
pyenv --version
pyenv root
echo $PYENV_ROOT
# Check shell integration
pyenv init
echo $PATH | grep pyenv
which python
pyenv which python
# Debug version selection
pyenv version
pyenv versions
cat .python-version 2>/dev/null || echo "No local version file"
pyenv shell --unset
pyenv local --unset
# Check build logs
ls -la /tmp/python-build*.log
tail -50 /tmp/python-build.log

Environment Variables

# Check environment variables that affect pyenv
echo $PYENV_VERSION
echo $PYENV_SHELL
echo $PYENV_DIR
# Check pyenv settings
pyenv vars

12. Performance and Optimization

Build Optimization

# Parallel compilation
MAKE_OPTS="-j$(nproc)" pyenv install 3.12.0
# Use system libraries where available
export PYTHON_CONFIGURE_OPTS="--with-openssl=$(brew --prefix openssl)"
# Cache build dependencies
export PYTHON_BUILD_CURL_OPTS="--retry 3 --retry-delay 5"
export PYTHON_BUILD_WGET_OPTS="--tries 3 --wait=5"

Cache Management

# Check cache directory
pyenv root/cache
# Clear Python source downloads
rm -rf $(pyenv root)/cache/*
# Set custom cache directory
export PYTHON_BUILD_CACHE_DIR=/path/to/cache

Network Optimization

# Use specific mirror for faster downloads
export PYTHON_BUILD_MIRROR_URL=https://www.python.org/ftp/python
# Skip certificate verification (not recommended for production)
export PYTHON_BUILD_SKIP_MIRROR=1

13. Migration and Backup

Exporting/Importing Versions

# List all installed versions
pyenv versions > pyenv-versions.txt
# Export current environment
pyenv versions --bare > my-python-versions.txt
# Script to install from list
cat my-python-versions.txt | while read version; do
  pyenv install $version
done

Project Migration

# For each project directory
find . -name ".python-version" -exec cat {} \;
# Backup project Python versions
find . -name ".python-version" -exec sh -c 'echo "{}: $(cat {})"' \;
# Create migration script
cat > migrate-python.sh << 'EOF'
#!/bin/bash
while IFS= read -r line; do
  project=$(dirname "$line")
  version=$(cat "$line")
  echo "Project: $project, Python: $version"
  cd "$project"
  pyenv install "$version"
  pyenv local "$version"
  cd -
done < <(find . -name ".python-version")
EOF

14. Automation and Scripts

Automatic Version Switching

# Auto-switch based on requirements.txt
cat > .auto-version << 'EOF'
#!/bin/bash
if [ -f requirements.txt ]; then
  # Parse Python version from requirements.txt
  version=$(grep -E '^python[-~]?=?.*[0-9]' requirements.txt | head -1)
  if [ ! -z "$version" ]; then
    # Extract version number and set it
    pyenv install -s $(echo "$version" | sed 's/python[-~]?=//')
    pyenv local $(echo "$version" | sed 's/python[-~]?=//')
  fi
fi
EOF
# Add to git hook
chmod +x .auto-version
echo ".auto-version" >> .git/hooks/pre-commit

Pre-commit Hooks

# .git/hooks/pre-commit
#!/bin/bash
# Ensure Python version consistency
current_version=$(pyenv version-name)
required_version=$(cat .python-version 2>/dev/null)
if [ ! -z "$required_version" ] && [ "$current_version" != "$required_version" ]; then
  echo "Warning: Python version mismatch"
  echo "Required: $required_version"
  echo "Current: $current_version"
  echo "Switching to required version..."
  pyenv local "$required_version"
fi

15. Security Considerations

Safe Installation Practices

# Verify pyenv installer authenticity
# Download installer and check signature before running
curl -s https://pyenv.run | sh -s -- --verify-download-signatures
# Use specific pyenv version
git clone https://github.com/pyenv/pyenv.git ~/.pyenv
cd ~/.pyenv
git checkout v2.3.32  # Use latest stable release

Build Security

# Verify checksums (when available)
export PYTHON_BUILD_VERIFY_CHECKSUM=1
# Use trusted mirrors only
export PYTHON_BUILD_MIRROR_URL=https://www.python.org/ftp/python
# Avoid running as root
# Always use pyenv as regular user

Sources

This cheatsheet was synthesized from the following official and community resources:


Quick Reference Card

Essential Commands at a Glance:

Task Command Example
Install pyenv `curl https://pyenv.run bash` -
List versions pyenv install --list `pyenv install --list grep 3.12`
Install Python pyenv install <version> pyenv install 3.12.0
Set global pyenv global <version> pyenv global 3.12.0
Set local pyenv local <version> pyenv local 3.11.0
Set shell pyenv shell <version> pyenv shell 3.10.0
List installed pyenv versions -
Check version pyenv version -
Create virtualenv pyenv virtualenv <ver> <name> pyenv virtualenv 3.12.0 venv
Activate virtualenv pyenv activate <name> pyenv activate venv
Update pyenv pyenv update -
Rehash shims pyenv rehash -

Path Priority (Highest to Lowest):

  1. pyenv shell <version>

  2. pyenv local <version> (.python-version file)

  3. pyenv global <version>

  4. System Python (fallback)

The Ultimate uv Cheatsheet

A comprehensive quick reference guide for uv, the fast Python package and project manager. This cheatsheet is designed for both beginners and advanced users, covering everything from basic commands to advanced workflows.

Author: MiniMax Agent Date: 2025-11-05

1. Quick Start

Get up and running with uv in minutes.

Task Command Notes
Install uv curl -LsSf https://astral.sh/uv/install.sh | sh Recommended standalone installer for macOS/Linux.
Create a new app uv init --app myapp Scaffolds a new application project.
Add a dependency uv add requests Adds to pyproject.toml and updates uv.lock.
Add a dev dependency uv add --dev pytest Adds to the dev dependency group.
Run a command uv run python main.py Executes in the managed virtual environment. Implicitly syncs.
Sync environment uv sync Installs dependencies from uv.lock.
Run a temporary tool uvx ruff check . Runs a CLI tool in an ephemeral environment (like pipx run).

2. Installation Guide

uv supports macOS, Linux, and Windows. The standalone installer is recommended for most users.

OS Method Command
macOS Standalone (Recommended) curl -LsSf https://astral.sh/uv/install.sh | sh
Homebrew brew install uv
MacPorts sudo port install uv
Linux Standalone (Recommended) curl -LsSf https://astral.sh/uv/install.sh | sh
Windows PowerShell (Recommended) powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"
WinGet winget install --id=astral-sh.uv -e
Scoop scoop install main/uv
Any OS pipx pipx install uv
pip pip install uv
Docker docker run ghcr.io/astral-sh/uv
Cargo (from source) cargo install --git https://github.com/astral-sh/uv uv

Upgrading

  • Standalone Installer: uv self update
  • Package Managers: Use the manager's upgrade command (e.g., brew upgrade uv).

Shell Autocompletion

Add the following to your shell's configuration file (e.g., .bashrc, .zshrc).

  • Bash: eval "$(uv generate-shell-completion bash)"
  • Zsh: eval "$(uv generate-shell-completion zsh)"
  • Fish: uv generate-shell-completion fish | source

3. Core Commands Reference

A quick lookup table for uv's primary commands.

Command Description
uv init Initializes a new Python project (pyproject.toml).
uv add Adds a dependency to the project.
uv remove Removes a dependency from the project.
uv lock Resolves dependencies and creates/updates uv.lock.
uv sync Synchronizes the virtual environment with uv.lock.
uv run Runs a command within the project's virtual environment.
uv venv Creates a virtual environment.
uv tree Displays the dependency tree.
uv pip install pip-compatible command to install packages.
uv pip compile pip-tools-compatible command to compile requirements.in files.
uv tool install Installs a CLI tool permanently in a shared uv environment (like pipx install).
uvx Executes a CLI tool in an ephemeral environment (like pipx run).
uv python install Installs a specific Python version.
uv build Builds a source distribution and wheel for the project.
uv publish Publishes the project to a package index.
uv cache clean Clears the global uv cache.
uv self update Updates uv itself (if installed via standalone installer).

4. Project Management Workflow

From project creation to execution.

  1. Initialize the Project:

    # For an application
    uv init --app my-project
    cd my-project
    
    # For a library
    uv init --lib my-library

    This creates pyproject.toml, a virtual environment (.venv), and other project files.

  2. Add Dependencies:

    # Add a production dependency
    uv add "fastapi[all]"
    
    # Add a development dependency
    uv add --dev "pytest>=8.0"
    
    # Add from a Git repository
    uv add "ruff @ git+https://github.com/astral-sh/ruff"
  3. Run Commands:

    # Run a Python script
    uv run python src/main.py
    
    # Run a tool installed as a dependency
    uv run pytest

    uv run automatically creates and syncs the environment if needed.

  4. Lock & Sync Manually (Optional):

    # Regenerate the lockfile from pyproject.toml
    uv lock
    
    # Install dependencies from the lockfile into the environment
    uv sync

5. Dependency Management

uv provides both a native project-based workflow and a pip-compatible interface.

Native Workflow

Command Example Description
uv add <pkg> uv add requests Add a production dependency.
uv add --dev <pkg> uv add --dev ruff Add a development dependency.
uv add --group test <pkg> uv add --group test pytest-xdist Add a dependency to a specific group.
uv remove <pkg> uv remove requests Remove a dependency and its sub-dependencies.
uv sync --group dev uv sync --group dev Sync main dependencies and the dev group.
uv sync --no-deps uv sync --no-deps Sync only the packages specified, ignoring their dependencies.
uv tree uv tree View the resolved dependency tree.

pip-Compatible Workflow

Use uv pip for traditional requirements.txt-based workflows. It's 10-100x faster than pip.

Command Example Description
uv pip install <pkg> uv pip install "Django<5.0" Install one or more packages.
uv pip install -r <file> uv pip install -r requirements.txt Install packages from a requirements file.
uv pip compile <file> uv pip compile requirements.in -o requirements.txt Compile a requirements.txt from a requirements.in file.
uv pip freeze uv pip freeze > requirements.txt Output installed packages in requirements format.
uv pip list uv pip list --outdated List installed packages and check for outdated ones.
uv pip uninstall <pkg> uv pip uninstall Django Uninstall one or more packages.

6. Environment Management

uv automatically manages a .venv in your project directory.

Command Example Description
uv venv uv venv Create a virtual environment in the current directory (.venv).
uv venv --python <version> uv venv -p 3.11 Create a virtual environment with a specific Python version. uv will install it if not found.
uv venv my-env uv venv my-env Create a virtual environment with a custom name.
uv venv --seed uv venv --seed Add pip and setuptools to the new environment.
uv run <cmd> uv run which python Run a command inside the managed environment without activating it.
source .venv/bin/activate source .venv/bin/activate Manually activate the virtual environment (standard practice).

7. Python Version Management

uv can install and manage Python versions for you, acting as a lightweight pyenv alternative.

Command Example Description
uv python install <ver> uv python install 3.12 Install a specific version of Python.
uv python list uv python list List all Python versions installed by uv.
uv python pin <ver> uv python pin 3.12 Create a .python-version file to lock the project's Python version.
uv run -p <ver> <cmd> uv run -p 3.10 -- python --version Run a command with a specific Python version for a single invocation.

8. Tool Execution (uvx and uv tool)

Execute CLI tools without polluting your project's dependencies.

Ephemeral Tools (uvx)

uvx is a pipx run replacement. It runs a tool in a temporary, cached environment.

Command Example Use Case
uvx <tool> uvx ruff check . Run a linter or formatter.
uvx <tool>@<ver> uvx black@23.11.0 . --check Run a specific version of a tool.
uvx --py <v> <t> uvx --python 3.10 cookiecutter ... Run a tool with a specific Python version.

Permanent Tools (uv tool)

uv tool is a pipx install replacement. It installs tools in a centralized, shared uv environment.

Command Example Description
uv tool install <tool> uv tool install cruft Install a tool for frequent use.
uv tool list uv tool list List all installed tools.
uv tool run <tool> uv tool run cruft --help Run an installed tool.
uv tool uninstall <tool> uv tool uninstall cruft Uninstall a tool.
uv tool upgrade <tool> uv tool upgrade --all Upgrade one or all installed tools.

9. Build and Publish

uv provides a complete build and publish workflow, replacing build and twine.

  1. Configure pyproject.toml:

    [build-system]
    requires = ["setuptools>=61.0"]
    build-backend = "setuptools.build_meta"
  2. Build the Package:

    # Build both a wheel and a source distribution (sdist)
    uv build
    
    # Build only a wheel
    uv build --wheel
    
    # Build only an sdist
    uv build --sdist

    Artifacts are placed in the dist/ directory.

  3. Publish the Package:

    # Publish to PyPI
    uv publish --token <pypi-token>
    
    # Publish to a custom repository
    uv publish --repository-url https://my-repo.org/legacy/ --token <my-token>

10. Configuration

Configure uv using pyproject.toml, uv.toml, or environment variables.

  • Project-level: pyproject.toml ([tool.uv]) or uv.toml in the project root.
  • User-level: ~/.config/uv/uv.toml (Linux/macOS) or %APPDATA%\\uv\\uv.toml (Windows).

Example pyproject.toml:

[tool.uv]
# Exclude older Python versions
requires-python = ">=3.9"

[tool.uv.pip]
# Use a custom package index
index-url = "https://my-internal-pypi.com/simple"
extra-index-url = ["https://pypi.org/simple"]

[tool.uv.dev-dependencies]
pytest = ">=8.0"

Precedence Order (Highest to Lowest):

  1. Command-line flags (e.g., --index-url)
  2. Environment variables (e.g., UV_INDEX_URL)
  3. Project uv.toml
  4. Project pyproject.toml
  5. User uv.toml

11. Advanced Features

Workspaces

Manage multiple packages within a single monorepo.

pyproject.toml at the workspace root:

[tool.uv.workspace]
members = ["packages/*"]

All projects in the packages/ directory will share a single lockfile and virtual environment.

Scripting with Inline Dependencies

Run single-file scripts with dependencies defined in the file (inspired by PEP 723).

my_script.py:

# /// script
# dependencies = [
#   "requests",
#   "rich",
# ]
# ///

import requests
from rich import print

print(requests.get("https://api.github.com").json())

Run it:

uv run my_script.py

uv will create a temporary environment with requests and rich to run the script.


12. Migration Guide

Migrating from other tools is straightforward.

  • From pip and requirements.txt:

    • Create a virtual environment: uv venv
    • Install dependencies: uv pip install -r requirements.txt
    • From here, you can continue using uv pip or migrate to uv's native project management.
  • From pip-tools:

    • uv pip compile requirements.in -o requirements.txt is a drop-in, faster replacement for pip-compile.
    • uv sync --from-requirements requirements.txt can replace pip-sync.
  • From Poetry:

    1. Initialize uv in your Poetry project: uv init
    2. Let uv import dependencies from pyproject.toml: uv lock
    3. You can now use uv sync and uv run. uv and Poetry can coexist in the same project.

13. Troubleshooting

Issue Solution
Windows Installer Fails Run the PowerShell command with -ExecutionPolicy ByPass.
Proxy or Certificate Errors Use the --native-tls flag to use the system's certificate store. Set HTTPS_PROXY environment variable.
Cache Corruption Run uv cache clean to safely clear the global cache, then re-run your command.
"Tool not found" Ensure ~/.local/bin (or equivalent) is in your PATH. Use uv tool list to verify installation.
"Environment out of sync" Run uv sync to reinstall dependencies from the lockfile.

14. Performance Tips

uv is fast by default, but you can make it even faster.

  • Use the Global Cache: uv caches everything. In CI, cache the uv cache directory (uv cache dir) between runs for massive speedups.
  • Leverage Linking: On filesystems that support it, uv uses CoW/reflinks/hardlinks. This makes creating new virtual environments nearly instant if the dependencies are already cached.
  • Use --no-deps: When you are certain dependencies are met, uv sync --no-deps can speed up installation by skipping the dependency resolution step.
  • Optimize Docker Builds: Use multi-stage builds. Have one stage for installing dependencies to leverage Docker's layer caching, and a final, smaller stage for your application code. Use UV_LINK_MODE=copy in containers for deterministic behavior.

Sources

This cheatsheet was synthesized from the following official and community resources:


DeepSeek reponse

uv is an all-in-one, extremely fast Python package and project manager written in Rust. It integrates the functionalities of tools like pip, virtualenv, poetry, pipx, and pyenv into a single, high-performance tool.

Here is a quick-reference table of the most common uv commands for different use cases.

πŸš€ Getting Started with uv

Purpose Command
Install uv (macOS/Linux) curl -LsSf https://astral.sh/uv/install.sh | sh
Install uv (Windows) powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"
Install via pip pip install uv
Update uv uv self update
Get general help uv --help

πŸ“¦ Project & Dependency Management

Purpose Command
Create new project uv init <project-name>
Initialize as package uv init --package
Add dependency uv add <package-name>
Add dev dependency uv add --dev <package-name>
Install all deps (from pyproject.toml) uv sync
Remove dependency uv remove <package-name>
View dependency tree uv tree
Update lockfile uv lock
Upgrade all dependencies uv lock --upgrade

🐍 Python & Virtual Environment Management

Purpose Command
Install Python version uv python install <version>
List Python versions uv python list
Pin Python for project uv python pin <version>
Create virtual env uv venv
Create venv with specific Python uv venv --python <version>
Activate venv (Linux/macOS) source .venv/bin/activate
Activate venv (Windows) .venv\Scripts\activate

πŸ› οΈ Tool & Script Management

Purpose Command
Run tool once (ephemeral) uvx <tool-name>
Run tool from specific package uvx --from <package-name> <command>
Run tool at specific version uvx <tool-name>@<version>
Install tool globally uv tool install <tool-name>
List installed tools uv tool list
Upgrade a tool uv tool upgrade <tool-name>
Upgrade all tools uv tool upgrade --all
Run script in project env uv run <script.py>
Run script with temp deps uv run --with <package> <script.py>

πŸ“€ Building & Publishing

Purpose Command
Build package uv build
Publish to PyPI uv publish
Publish to TestPyPI uv publish --publish-url https://test.pypi.org/legacy/
Bump project version uv version --bump <major|minor|patch>

πŸ”§ Useful Utility Commands

Purpose Command
Export to requirements.txt uv pip compile pyproject.toml -o requirements.txt
Install from requirements.txt uv add -r requirements.txt
Clean cache uv cache clean
Get help for a command uv help <command>
Remove all packages `uv pip uninstall $(uv pip list --format=columns
Remove all packages `uv remove $(uv pip list --format=columns

πŸ’‘ Common Workflow Examples

Here's how to combine these commands into common, real-world workflows:

  • Starting a new project from scratch:
    uv init my_new_project
    cd my_new_project
    uv add requests pandas  # Add your main dependencies
    uv add --dev pytest ruff  # Add development tools
    uv run python main.py  # Run your script
  • Working with an existing project:
    git clone <repository>
    cd <project-directory>
    uv sync  # Install all project dependencies
    uv run pytest  # Run tests using the project's environment
  • Quickly running a one-off tool: Need to format code with ruff or run a linter without adding it to your project? Use uvx.
    uvx ruff check .  # Run Ruff without installing it
    uvx --from httpie http  # Run a command where the package name differs from the command

πŸ“ Key pyproject.toml Structure

uv uses the modern pyproject.toml file for configuration. Here's a basic look at its structure:

[project]
name = "myproject"
version = "0.1.0"
dependencies = [
    "requests>=2.28.0",
    "pandas>=2.0.0"
]

[tool.uv]
dev-dependencies = [
    "pytest>=7.0",
    "ruff>=0.1.0"
]

# For publishable packages:
[project.scripts]
my-script = "my_module:main"

[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment