Calmcode - uv: run

Running scripts with UV

1 2 3 4

Let's suppose that you have this script:

import requests
from rich.pretty import pprint

resp = requests.get("https://peps.python.org/api/peps.json")
data = resp.json()
pprint([(k, v["title"]) for k, v in data.items()][:10])

Normally, if you wanted to run this script you'd have to create a virtual environment first. With uv you can just run it directly by declaring the dependencies from the command line.

uv run --with requests --with rich script.py

This will create a seperate environment, install the dependencies, and run the script. This is a great way to run scripts without polluting your main virtual environment with dependencies. A lot of rarely run scripts might fit this category.

Metadata

But you can also add metadata to your script such that you do not need to add the dependencies from the command line.

# /// script
# requires-python = ">=3.12"
# dependencies = [
#   "requests<3",
#   "rich",
# ]
# ///

import requests
from rich.pretty import pprint

resp = requests.get("https://peps.python.org/api/peps.json")
data = resp.json()
pprint([(k, v["title"]) for k, v in data.items()][:10])

To run this script, because of the metadata on top, you can just run uv run directly.

uv run script.py