uv run Installs a Script's Inline Dependencies in an Isolated Environment

In progress

A single-file Python script can declare the packages it needs in a comment block at its top, the inline script metadata format of PEP 723. uv run script.py reads that block, installs the packages into a cached environment of their own, and runs the script there. A helper script then needs no virtual environment, no requirements.txt and no global pip install. It is also reproducible on another machine as long as uv is installed.

The Metadata Block

The block is a TOML comment between # /// script and # /// lines:

#!/usr/bin/env python3
# /// script
# requires-python = ">=3.11"
# dependencies = [
#     "requests",
# ]
# ///

import requests

uv add --script configure-app.py requests writes or updates the block for you. uv run configure-app.py then creates (or reuses from its cache) an environment with a matching Python and those packages, separate from any project's .venv.

Making It Executable

With the shebang #!/usr/bin/env -S uv run --script and chmod +x, the script runs as ./configure-app.py, and uv still handles its dependencies. Without uv on the machine, the shebang fails immediately, which is better than running with whatever happens to be installed.

When a Project Is Better

Inline metadata suits standalone tools: post-deploy automation, a one-off migration, a report. As soon as several modules share code or need tests, a project with pyproject.toml and uv.lock keeps the dependency tree in one place.

References

Review cards

Flashcard What does uv run do with a script that has an inline metadata block?

It reads the block, installs the listed packages into a cached environment of their own (separate from any project's .venv), and runs the script there.

Flashcard Why use the shebang #!/usr/bin/env -S uv run --script?

The script then runs as ./script.py with uv handling its dependencies. Without uv installed it fails immediately, instead of running with whatever packages happen to be there.

Flashcard Why add version bounds, or uv lock --script, to an inline-metadata script?

An unbounded "requests" installs whatever release is latest on the first run, so the same script can behave differently next year.