Ben Chuanlong Du's Blog

It is never too late to learn.

Manage Python Projects Using uv

Things on this page are fragmentary and immature notes/thoughts of the author. Please read with your own judgement!

Installation

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

curl -LsSf https://astral.sh/uv/install.sh | env UV_INSTALL_DIR="/usr/local/bin" sh

Usage

Ad-hoc Python Shell & Scripts

  1. You can start an ad-hoc Python shell ( e.g., Python 3.13 with 3rd-party packages dockeree and aituil ) using the following command.

    uv run --python 3.13 --with dockeree aiutil python
    
  2. Initialize a uv managed Python script.

    uv init --python 3.13 --script example.py
    

    Notice that if the script example.py already exists, uv will just append metadata lines into it.

  3. You can add dependencies to a uv managed Python scripts using the following command.

    uv add --script example.py 'requests<3' 'rich'
    
  4. You can run a uv managed Python script using the following command.

    uv run /path/to/uv_init_pyscript
    

    This can be simplified by add the shebang #!/usr/bin/env -S uv run --script or #!/usr/bin/env -S uv run python (preferred as it's easy to pass options to control the python executable) into the Python script, so that you can invoke the script as an executable directly.

Manage Projects

  1. Migrate from other Python projects to uv.

    uvx migrate-to-uv
    
  2. Initialize a new uv project with the given name.

    uv init --package new_project_name
    
  3. Initialize the current project as a uv project.

    uv init --package
    
  4. Update the lock file (changing as little as possible).

    uv lock
    
  5. Update the lock file ensuring that dependencies are the newest version allowed by the spec.

    uv lock --upgrade
    
  6. Create a virtual environment if one doesn't already exist and install all dependencies.

    uv sync
    

    Install all dependencies including optional ones.

    uv sync --all-extras
    

    Install all dependencies but not the current project.

    uv sync --no-install-project
    
  7. Build the project.

    uv build
    
  8. Publish the project.

    uv publish
    

References

Comments