Day 3: CLI Tools with typer – tidy
Goal: build a CLI
tidywith typer, pathlib and subprocess that cleans up a download folder by rules – as a dry run by default, with clean exit codes · Duration: approx. 120 min · Prerequisite: Day 2
Briefing
- typer turns functions with type hints into a CLI: arguments, options, help, validation and subcommands.
- pathlib replaces
os.path:Path("a") / "b",.suffix,.iterdir(),.move()(new in 3.14). - subprocess.run calls system commands safely:
argument list instead of a shell string,
check=True,capture_output=True. - Destructive tools show the plan first. They only act with
apply, after confirmation or with--yes.
tidy plan DIR ──► rules.plan() ──► [Move(src, dst), ...] ──► output (dry run)
tidy apply DIR ──► rules.plan() ──► confirm ──► Path.move() ──► Exit 0 | 1 (conflicts)
tidy du DIR ──► subprocess.run(["du", "-sk", ...])
Drill 1: Project and practice folder
cd ~/py-lab
uv init -q --package --name tidy tag03-tidy
cd tag03-tidy
uv add typer
uv add -q --dev pytest ruff
cat >> pyproject.toml <<'EOF'
[tool.ruff.lint]
extend-select = ["E501", "B", "UP", "SIM"]
EOFExpected (shortened):
+ rich==15.0.0
+ typer==0.27.3
Security: You practice on
lab/downloads, never directly on~/Downloads. A script rebuilds the practice folder at any time.
mkdir -p lab
cat > lab/reset.sh <<'EOF'
#!/usr/bin/env bash
# Rebuilds the practice folder lab/downloads – lab files only.
set -euo pipefail
cd "$(dirname "$0")"
rm -rf downloads
mkdir -p downloads/alter-ordner
cd downloads
touch rechnung-2026-09.pdf notizen.txt setup.dmg backup.tar.gz logs.gz \
screenshot.png "Mein Lebenslauf.docx" .DS_Store
head -c 300000 /dev/zero > urlaub.JPG
EOF
bash lab/reset.sh
ls -A lab/downloadsExpected:
.DS_Store
alter-ordner
backup.tar.gz
logs.gz
Mein Lebenslauf.docx
notizen.txt
rechnung-2026-09.pdf
screenshot.png
setup.dmg
urlaub.JPG
Save your progress? Sign up for free
Drill 2: pathlib and the rules
uv run python - <<'EOF'
from pathlib import Path
p = Path("lab/downloads") / "backup.tar.gz"
print(p.name, p.stem, p.suffix, p.suffixes)
print(p.parent, p.exists(), p.is_file())
print(p.with_name("neu.zip"))
print(sorted(x.name for x in p.parent.iterdir() if x.is_dir()))
print(len(list(p.parent.glob("*.pdf"))))
EOFExpected:
backup.tar.gz backup.tar .gz ['.tar', '.gz']
lab/downloads True True
lab/downloads/neu.zip
['alter-ordner']
1
/ joins paths platform-independently,
suffixes knows double extensions like .tar.gz.
The rule logic goes into a module of its own, without any CLI code –
that makes it easy to test:
cat > src/tidy/rules.py <<'EOF'
"""Regeln laden und einen Umzugsplan berechnen – ohne etwas anzufassen."""
import tomllib
from dataclasses import dataclass
from pathlib import Path
DEFAULT_RULES = {
"pdf": "Dokumente",
"docx": "Dokumente",
"txt": "Dokumente",
"jpg": "Bilder",
"png": "Bilder",
"dmg": "Installer",
"zip": "Archive",
"tar.gz": "Archive",
}
@dataclass(frozen=True)
class Move:
src: Path
dst: Path
@property
def conflict(self) -> bool:
return self.dst.exists()
def load_rules(path: Path | None) -> dict[str, str]:
"""Regeln aus einer TOML-Datei ([rules] endung = "Ordner") oder Defaults."""
if path is None:
return DEFAULT_RULES
with path.open("rb") as f:
data = tomllib.load(f)
return {ext.lower().lstrip("."): folder for ext, folder in data["rules"].items()}
def target_folder(file: Path, rules: dict[str, str]) -> str | None:
"""Erst die volle Endung (tar.gz), dann die letzte (gz) nachschlagen."""
full = "".join(file.suffixes).lower().lstrip(".")
last = file.suffix.lower().lstrip(".")
return rules.get(full) or rules.get(last)
def plan(directory: Path, rules: dict[str, str]) -> list[Move]:
"""Ein Move pro Datei mit bekannter Endung; Ordner und dotfiles bleiben."""
moves = []
for file in sorted(directory.iterdir()):
if not file.is_file() or file.name.startswith("."):
continue
folder = target_folder(file, rules)
if folder is not None:
moves.append(Move(file, directory / folder / file.name))
return moves
EOFplan()is a pure function: it reads the directory but changes nothing. Dry run and execution use the same plan – what you see is what happens.tomllibhas been in the standard library since 3.11 (read-only). It needs the file in binary mode"rb".rules.get(full) or rules.get(last):orreturns the first “truthy” value – a compact fallback.
Save your progress? Sign up for free
Drill 3: The typer app
cat > src/tidy/cli.py <<'EOF'
"""tidy – einen Download-Ordner nach Regeln aufräumen (Standard: Dry-Run)."""
import subprocess
from pathlib import Path
from typing import Annotated
import typer
from tidy.rules import load_rules, plan
app = typer.Typer(help=__doc__, no_args_is_help=True)
DirArg = Annotated[
Path, typer.Argument(exists=True, file_okay=False, help="Ordner zum Aufräumen")
]
RulesOpt = Annotated[
Path | None, typer.Option("--rules", "-r", exists=True, help="TOML-Regeldatei")
]
@app.command("plan")
def plan_cmd(directory: DirArg, rules: RulesOpt = None) -> None:
"""Zeigt, was verschoben würde. Ändert nichts."""
moves = plan(directory, load_rules(rules))
for m in moves:
mark = "!" if m.conflict else " "
typer.echo(f"{mark} {m.src.name:<28} -> {m.dst.parent.name}/")
conflicts = sum(m.conflict for m in moves)
typer.echo(f"{len(moves)} Dateien, {conflicts} Konflikte (Dry-Run)")
@app.command()
def apply(
directory: DirArg,
rules: RulesOpt = None,
yes: Annotated[bool, typer.Option("--yes", "-y", help="ohne Rückfrage")] = False,
) -> None:
"""Verschiebt die Dateien. Exit 1, wenn es Konflikte gab."""
moves = plan(directory, load_rules(rules))
if not moves:
typer.echo("Nichts zu tun.")
return
if not yes:
typer.confirm(f"{len(moves)} Dateien verschieben?", abort=True)
conflicts = 0
for m in moves:
if m.conflict:
typer.echo(f"Konflikt, übersprungen: {m.dst}", err=True)
conflicts += 1
continue
m.dst.parent.mkdir(exist_ok=True)
m.src.move(m.dst)
typer.echo(f"verschoben: {m.src.name} -> {m.dst.parent.name}/")
if conflicts:
raise typer.Exit(code=1)
@app.command()
def du(directory: DirArg) -> None:
"""Größe der Unterordner über das Systemkommando du."""
folders = sorted(str(p) for p in directory.iterdir() if p.is_dir())
if not folders:
typer.echo("Keine Unterordner.")
return
try:
result = subprocess.run(
["du", "-sk", *folders], capture_output=True, text=True, check=True
)
except subprocess.CalledProcessError as err:
typer.echo(f"du fehlgeschlagen ({err.returncode}): {err.stderr}", err=True)
raise typer.Exit(code=3) from err
for line in result.stdout.splitlines():
kb, path = line.split("\t", 1)
typer.echo(f"{int(kb):>8} KB {Path(path).name}/")
EOF
cat > src/tidy/__init__.py <<'EOF'
"""tidy – Ordner nach Regeln aufräumen."""
from tidy.cli import app
def main() -> None:
app()
EOF
cat > src/tidy/__main__.py <<'EOF'
from tidy import main
main()
EOF
uv run tidy plan lab/downloads; echo "exit=$?"Expected:
Mein Lebenslauf.docx -> Dokumente/
backup.tar.gz -> Archive/
notizen.txt -> Dokumente/
rechnung-2026-09.pdf -> Dokumente/
screenshot.png -> Bilder/
setup.dmg -> Installer/
urlaub.JPG -> Bilder/
7 Dateien, 0 Konflikte (Dry-Run)
exit=0
logs.gz, .DS_Store and
alter-ordner stay where they are: no rule, dotfile,
folder.
Annotated[Path, typer.Argument(...)]separates type and CLI metadata. typer converts the string into aPathand checksexists=Trueandfile_okay=Falsebefore your code runs.- Recurring parameters as type aliases (
DirArg,RulesOpt) keep the commands lean. - The docstring becomes the command’s help, the function name becomes
the command name (thanks to
@app.command("plan"),plan_cmdis still calledplanand does not collide with the imported function). typer.echo(..., err=True)writes tostderr.
uv run tidy plan gibt-es-nicht; echo "exit=$?"Expected:
Usage: tidy plan [OPTIONS] {directory}
Try 'tidy plan --help' for help.
╭─ Error ──────────────────────────────────────────────────────────────────────╮
│ Invalid value for 'directory': Directory 'gibt-es-nicht' does not exist. │
╰──────────────────────────────────────────────────────────────────────────────╯
exit=2
Save your progress? Sign up for free
Drill 4: Running with confirmation and exit codes
Create a conflict: there is already a notizen.txt in the
target.
mkdir -p lab/downloads/Dokumente
echo alt > lab/downloads/Dokumente/notizen.txt
uv run tidy plan lab/downloads | head -4
echo n | uv run tidy apply lab/downloads; echo "exit=$?"Expected:
Mein Lebenslauf.docx -> Dokumente/
backup.tar.gz -> Archive/
! notizen.txt -> Dokumente/
rechnung-2026-09.pdf -> Dokumente/
7 Dateien verschieben? [y/N]: Aborted.
exit=1
With echo n you answer the confirmation prompt from the
pipe. Now for real:
uv run tidy apply lab/downloads --yes; echo "exit=$?"
find lab/downloads -type f | sortExpected:
verschoben: Mein Lebenslauf.docx -> Dokumente/
verschoben: backup.tar.gz -> Archive/
Konflikt, übersprungen: lab/downloads/Dokumente/notizen.txt
verschoben: rechnung-2026-09.pdf -> Dokumente/
verschoben: screenshot.png -> Bilder/
verschoben: setup.dmg -> Installer/
verschoben: urlaub.JPG -> Bilder/
exit=1
lab/downloads/.DS_Store
lab/downloads/Archive/backup.tar.gz
lab/downloads/Bilder/screenshot.png
lab/downloads/Bilder/urlaub.JPG
lab/downloads/Dokumente/Mein Lebenslauf.docx
lab/downloads/Dokumente/notizen.txt
lab/downloads/Dokumente/rechnung-2026-09.pdf
lab/downloads/Installer/setup.dmg
lab/downloads/logs.gz
lab/downloads/notizen.txt
| Exit code | Meaning for tidy |
|---|---|
| 0 | everything done or nothing to do |
| 1 | conflicts skipped or aborted |
| 2 | wrong usage (typer/click) |
| 3 | system command failed |
Why not overwrite? A cleanup tool that silently replaces data is a data-loss tool. Skip conflicts, report them and signal them via exit code – then a cron job or script can react.
Tip:
Path.move()is new in Python 3.14 and also works across file system boundaries. On older versions you useshutil.move().
Save your progress? Sign up for free
Drill 5: subprocess – calling system commands safely
uv run tidy du lab/downloadsExpected (sizes may differ depending on the file system):
0 KB Archive/
296 KB Bilder/
4 KB Dokumente/
0 KB Installer/
0 KB alter-ordner/
The rules for subprocess.run:
- List instead of string:
["du", "-sk", *folders]passes every path as a separate argument. Spaces or; rm -rf ~in file names stay harmless.shell=Truewith assembled strings is command injection waiting to happen. check=True: an exit code other than 0 becomes aCalledProcessErrorexception – no silent carrying on like in Bash withoutset -e.capture_output=True, text=True:stdout/stderrend up asstrin the result instead of in the terminal.raise ... from errattaches the cause; in the traceback you see both errors.
uv run python - <<'EOF'
import subprocess
r = subprocess.run(["ls", "/gibt-es-nicht"], capture_output=True, text=True)
print(r.returncode, r.stderr.strip())
try:
subprocess.run(["false"], check=True)
except subprocess.CalledProcessError as err:
print("CalledProcessError, returncode", err.returncode)
EOFExpected:
1 ls: /gibt-es-nicht: No such file or directory
CalledProcessError, returncode 1
Save your progress? Sign up for free
Drill 6: Custom rules via TOML
bash lab/reset.sh
cat > lab/tidy.toml <<'EOF'
[rules]
pdf = "Belege"
".GZ" = "Archive"
dmg = "Installer"
EOF
uv run tidy plan lab/downloads --rules lab/tidy.tomlExpected:
backup.tar.gz -> Archive/
logs.gz -> Archive/
rechnung-2026-09.pdf -> Belege/
setup.dmg -> Installer/
4 Dateien, 0 Konflikte (Dry-Run)
load_rules normalizes the keys (".GZ"
becomes gz), and backup.tar.gz falls back to
gz for lack of a tar.gz rule. Custom rules
replace the defaults completely – this time PNG and TXT stay where they
are.
Save your progress? Sign up for free
Drill 7: Tests with tmp_path and CliRunner
mkdir -p tests
cat > tests/test_tidy.py <<'EOF'
from pathlib import Path
from typer.testing import CliRunner
from tidy.cli import app
from tidy.rules import DEFAULT_RULES, load_rules, plan, target_folder
runner = CliRunner()
def make_files(directory: Path, *names: str) -> None:
for name in names:
(directory / name).touch()
def test_target_folder():
assert target_folder(Path("A.PDF"), DEFAULT_RULES) == "Dokumente"
assert target_folder(Path("b.tar.gz"), DEFAULT_RULES) == "Archive"
assert target_folder(Path("c.md"), DEFAULT_RULES) is None
def test_plan_ignoriert_ordner_und_dotfiles(tmp_path):
make_files(tmp_path, "a.pdf", ".DS_Store", "x.unbekannt")
(tmp_path / "sub.pdf").mkdir()
moves = plan(tmp_path, DEFAULT_RULES)
assert [m.dst for m in moves] == [tmp_path / "Dokumente" / "a.pdf"]
def test_load_rules_aus_toml(tmp_path):
rules = tmp_path / "r.toml"
rules.write_text('[rules]\n".PDF" = "Belege"\n', encoding="utf-8")
assert load_rules(rules) == {"pdf": "Belege"}
def test_plan_cmd_aendert_nichts(tmp_path):
make_files(tmp_path, "a.pdf")
result = runner.invoke(app, ["plan", str(tmp_path)])
assert result.exit_code == 0
assert "1 Dateien, 0 Konflikte" in result.output
assert (tmp_path / "a.pdf").exists()
def test_apply_verschiebt(tmp_path):
make_files(tmp_path, "a.pdf", "b.png")
result = runner.invoke(app, ["apply", str(tmp_path), "--yes"])
assert result.exit_code == 0
assert (tmp_path / "Dokumente" / "a.pdf").exists()
assert (tmp_path / "Bilder" / "b.png").exists()
def test_apply_konflikt_gibt_exit_1(tmp_path):
make_files(tmp_path, "a.pdf")
(tmp_path / "Dokumente").mkdir()
(tmp_path / "Dokumente" / "a.pdf").write_text("alt", encoding="utf-8")
result = runner.invoke(app, ["apply", str(tmp_path), "-y"])
assert result.exit_code == 1
assert (tmp_path / "a.pdf").exists()
EOF
uv run pytest -q
uv run ruff check && uv run ruff format --check
uv run --with mypy mypy --strict srcExpected:
...... [100%]
6 passed in 0.02s
All checks passed!
6 files already formatted
Success: no issues found in 4 source files
tmp_pathis a pytest fixture: a fresh, empty folder per test that is cleaned up after the run. This way tests never touch real files (more on Day 4).CliRunner.invokestarts the CLI in the same process and returnsexit_codeandoutput– faster and more precise thansubprocessin a test.- Here
uv run --with mypyinstead ofuvx mypy: mypy has to see typer, otherwise all decorators count as untyped.
Save your progress? Sign up for free
Drill 8: The tool is done
bash lab/reset.sh
uv run tidy --help
uv run tidy apply lab/downloads -y > /dev/null; echo "exit=$?"
uv run tidy apply lab/downloads -y; echo "exit=$?"
uv run python -m tidy plan lab/downloadsExpected (shortened):
Usage: tidy [OPTIONS] COMMAND [ARGS]...
tidy – einen Download-Ordner nach Regeln aufräumen (Standard: Dry-Run).
╭─ Commands ───────────────────────────────────────────────────────────────────╮
│ plan Zeigt, was verschoben würde. Ändert nichts. │
│ apply Verschiebt die Dateien. Exit 1, wenn es Konflikte gab. │
│ du Größe der Unterordner über das Systemkommando du. │
╰──────────────────────────────────────────────────────────────────────────────╯
exit=0
Nichts zu tun.
exit=0
0 Dateien, 0 Konflikte (Dry-Run)
A second run changes nothing anymore: tidy is
idempotent. That is the property that makes a tool fit
for cron and CI.
Tip: For the real folder, read
uv run tidy plan ~/Downloadsfirst, then decide. From Day 5 on you install tools like this globally withuv tool install.
Save your progress? Sign up for free
Checkpoint
#!/usr/bin/env bash
check() { if eval "$2" >/dev/null 2>&1; then echo "✔ $1"; else echo "✘ $1"; fi; }
cd ~/py-lab/tag03-tidy
bash lab/reset.sh
check "plan findet 7 Dateien" \
"uv run tidy plan lab/downloads | grep -q '7 Dateien, 0 Konflikte'"
check "plan ändert nichts" "test -f lab/downloads/setup.dmg"
check "apply verschiebt" \
"uv run tidy apply lab/downloads -y && test -f lab/downloads/Installer/setup.dmg"
check "zweiter Lauf idempotent" "uv run tidy apply lab/downloads -y | grep -q Nichts"
check "Konflikt gibt Exit 1" "bash lab/reset.sh && mkdir lab/downloads/Bilder && \
touch lab/downloads/Bilder/screenshot.png && ! uv run tidy apply lab/downloads -y"
check "unbekannter Ordner gibt Exit 2" "uv run tidy plan /gibt/es/nicht; test \$? -eq 2"
check "du nutzt subprocess" "uv run tidy du lab/downloads | grep -q 'KB Bilder/'"
check "Tests grün" "uv run pytest -q"
check "ruff sauber" "uv run ruff check && uv run ruff format --check"
bash lab/reset.shExpected:
✔ plan findet 7 Dateien
✔ plan ändert nichts
✔ apply verschiebt
✔ zweiter Lauf idempotent
✔ Konflikt gibt Exit 1
✔ unbekannter Ordner gibt Exit 2
✔ du nutzt subprocess
✔ Tests grün
✔ ruff sauber
Challenge
Today a broken rules file ([regeln] instead of
[rules], rules = 42 or a TOML syntax error)
produces a long traceback. Turn it into a clear message on
stderr and exit code 2 – plus a test.
Hint: Catch the three possible exceptions in a small
function in cli.py and exit with
raise typer.Exit(code=2) from err.
Solution
In src/tidy/cli.py, add import tomllib at
the top and insert before plan_cmd:
def get_rules(path: Path | None) -> dict[str, str]:
"""Regeln laden; kaputte Datei -> klare Meldung und Exit 2."""
try:
return load_rules(path)
except (tomllib.TOMLDecodeError, KeyError, AttributeError) as err:
typer.echo(f"Regeldatei ungültig: {err!r}", err=True)
raise typer.Exit(code=2) from errIn plan_cmd and apply, replace
load_rules(rules) with get_rules(rules) each.
Append a test to tests/test_tidy.py:
def test_kaputte_regeln_geben_exit_2(tmp_path):
rules = tmp_path / "r.toml"
rules.write_text("[regeln]\n", encoding="utf-8")
result = runner.invoke(app, ["plan", str(tmp_path), "--rules", str(rules)])
assert result.exit_code == 2printf '[regeln]\npdf = "x"\n' > lab/kaputt.toml
uv run tidy plan lab/downloads -r lab/kaputt.toml; echo "exit=$?"
printf 'rules = 42\n' > lab/kaputt.toml
uv run tidy plan lab/downloads -r lab/kaputt.toml; echo "exit=$?"
rm lab/kaputt.toml
uv run pytest -qExpected:
Regeldatei ungültig: KeyError('rules')
exit=2
Regeldatei ungültig: AttributeError("'int' object has no attribute 'items'")
exit=2
....... [100%]
7 passed in 0.02s
Why exit 2 and not 1? A broken configuration is a usage error like a wrong option – the caller has to change something, a retry won’t help.
Save your progress? Sign up for free
Enterprise Note
- Destructive tools: dry run as the default, an explicit
--yesfor automation, and a log (which file went where) so that an undo is possible. - Never use
subprocesswithshell=Trueand user input; ruff detects this with the Bandit rules (S602,S603), which you enable on Day 5. - Check paths from configuration against breakouts (
.., symlinks):Path.resolve()andis_relative_to()before every write. - Document exit codes and keep them stable – monitoring, cron and CI depend on them.
- typer generates shell completion
(
tidy --install-completion); for teams, better ship it in the package than tinker with it in dotfiles.