Snippets for CLI scripts

(, en)

My valid filename check (for me: all normal letters/numbers + Portuguese + German special characters)

VALID_NAME_RE = r"[^-0-9A-Za-z_.%~äßöüħÖÜ€áàâãéêíóôõúçÁÀÂÃÉÊÍÓÔÕÚÇ]+"
re.sub(VALID_NAME_RE, "-", v)

Unpacking arrays & tuples

first, second, *rest = sys.argv[1:]
oldest, *others, youngest = car_ages_descending
oldest, second_oldest, *others = car_ages_descending

(see also Item 13: Prefer Catch-All Unpacking Over Slicing of Effective Python, 2nd ed.)

Parsing Dutch (or localised) date format

import locale
locale.setlocale(locale.LC_ALL, "nl_NL")
from datetime import datetime as dt

dutch_date = "donderdag 24 februari 2022 om 06:00:00"
dt.strptime(dutch_date, "%A %d %B %Y om %H:%M:%S").strftime("%Y-%m-%d")

Prompt user

def prompt(msg, default=None):
    msg_fmt = f"{msg} [{default}] " if default is not None else f"{msg} "

    res = input(msg_fmt).strip().lower()
    if len(res) == 0 and default is not None:
        return default
    return res

print(prompt("abc (y/n)?", "n"))