uv single file script
Python scripts that need external packages usually require setting up a virtual environment first. uv lets you skip that by declaring dependencies directly in the script.
Basic example
#!/usr/bin/env -S uv run
# /// script
# dependencies = [
# "openai",
# ]
# ///
from openai import OpenAI
import os
client = OpenAI(
api_key=os.environ.get("OPENAI_API_KEY"),
)
chat_completion = client.chat.completions.create(
messages=[
{
"role": "user",
"content": "Say this is a test",
}
],
model="gpt-4o",
)
print(chat_completion)
Make it executable and run:
chmod +x script.py
./script.py
When you run the script, uv automatically installs the dependencies in an isolated environment.
Adding dependencies
Instead of manually editing the comment block, use:
uv add --script script.py requests
This adds the dependency to the script’s metadata.
Python version requirements
You can specify which Python version the script needs:
# /// script
# requires-python = ">=3.12"
# dependencies = ["httpx"]
# ///
uv will download and use the correct Python version if needed.
Locking dependencies
For reproducible runs, lock the exact versions:
uv lock --script script.py
This creates a lock file that pins all dependencies to specific versions.