uv run Installs a Script's Inline Dependencies in an Isolated Environment
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
- Post-Deploy Automation Must Treat Already Configured as Success - the kind of automation script this fits.
- Start a FastAPI Project with uv - uv in a full project instead.
- Programming Languages MOC - hub for Python notes.
- uv documentation: Running scripts -
uv run,uv add --script, the shebang and locking. - PEP 723: Inline script metadata - the specification of the block.
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.