Running Python scripts with uv shebang

#python#uv

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:

  1. Shebang: #!/usr/bin/env -S uv --quiet run --script tells the system to use uv to execute the script
  2. Script metadata: The # /// script block defines Python version requirements and dependencies using PEP 723 format
  3. Direct execution: Make the script executable with chmod +x script.py and run it directly with ./script.py

When executed, uv automatically:

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.

Top