Running Python scripts with uv shebang
uv supports running Python scripts directly with their dependencies declared inline, eliminating the need for virtual environments or separate requirements files for simple scripts.
By also using a specific shebang line you can make Python scripts executable, too:
#!/usr/bin/env -S uv --quiet run --script
# /// script
# requires-python = ">=3.12"
# dependencies = [
# "requests",
# "typer",
# ]
# ///
import requests
import typer
def fetch_url(url: str):
"""Fetch and display a URL."""
response = requests.get(url)
print(response.text)
if __name__ == "__main__":
typer.run(fetch_url)
The key components:
- Shebang:
#!/usr/bin/env -S uv --quiet run --scripttells the system to useuvto execute the script - Script metadata: The
# /// scriptblock defines Python version requirements and dependencies using PEP 723 format - Direct execution: Make the script executable with
chmod +x script.pyand run it directly with./script.py
When executed, uv automatically:
- Creates an isolated environment
- Installs the specified dependencies (quietly)
- Runs the script with the correct Python version
This is perfect for utility scripts, automation tasks, or any small script that may need external dependencies without the overhead of managing virtual environments manually and doesn’t warrant a Python package creating to use a tool like pipx.