2025-07-16

Cheeky Python shell script

Bash has so many gotchas (the most recent one I've learnt) that some people recommend jumping to Python at some complexity threshold. One of those people is me, and I'd set the threshold pretty low.

Assuming you have uv installed (you should), the new scripts directives make the jump to Python even easier than before.

Here's an example script with:

A lot of not-using-Python comes down to friction, so make your own skeleton script with your favourite tidbits, then add the equivalent to your .zshrc or whatever:

function py-script(){curl https://raw.githubusercontent.com/leontrolski/leontrolski.github.io/refs/heads/master/code/my-script > $1 && chmod +x ./$1;}

Then just

py-script foo
./foo --help

bang!


The script - it's not the most performant (eg. it reads everything into memory everywhere), but it gets the job done.

#!/usr/bin/env -S uv run --script
# /// script
# requires-python = "==3.13"
# dependencies = [
#   "typer==0.16.0",
# ]
# ///
from pathlib import Path
import re
from subprocess import check_output
import typer

app = typer.Typer()


def sh(cmd: str) -> str:
    return check_output(cmd, shell=True).decode()


def main(counts: list[int], *, name: str = "Oli"):
    for txt in Path().glob("*.txt"):
        for line in txt.read_text().splitlines():
            if match := re.search(r"==([\d.]+)", line):
                print(match.groups()[0])
    commits = sh('git log --pretty=format:"%H" | head -10').splitlines()
    print(f"Hello {name} {counts=} {' '.join(commits)}")


typer.run(main)