
Recall first from A command-line tool
- argparse gives you parsing, help text, types and exit code 2 on bad input; click and typer trade less boilerplate for an extra dependency.
- Type hints and docstrings are read by tools such as typer, editors and mypy, so write them for machines, not just humans.
- Exit codes are the contract a CI or factory script branches on: 0 means success, 2 means misuse, 130 means an interrupt, and a failed tool must return non-zero.
When Bash stops being enough
3 min readEarlier lessons had you build shell pipelines by hand and treat a return code of 0 as success. This lesson answers when those one-liners stop being enough, and how pathlib turns paths into objects you can join, glob, and inspect.
In earlier modules you built pipelines like this one, which lists the ten largest logs:
find /home/learner/logs -name '*.log' -printf '%s %p\n' | sort -rn | head -10
That line is good. It is short, it uses tools that already exist, and it does one job. Keep writing lines like this. The trouble starts when the job grows. Suppose the factory script must now retry a failed flash three times, give up after a timeout, parse the tool's JSON report, and write a summary that a test dashboard can read. In Bash, every one of those steps fights the language. Data is only text, so you cut it with awk and sed. Errors are only exit codes, so you check $? after every command or trust set -e, which has well-known corner cases. And the script must run on the build host, on a colleague's laptop, and inside a CI container, where the available shell may differ.
Python answers each of those pains directly. Data lives in real structures: lists, dicts, sets, and the json module. Errors raise exceptions you can catch, retry, or turn into a clean exit code. The same script runs unchanged anywhere Python runs. That is the trade this lesson teaches: Bash for quick glue, Python for tools with logic.
The standard library pieces you will use have a history worth knowing. Pipes themselves date to early-1970s UNIX, and Bash arrived in 1989 as the GNU replacement for the Bourne shell. Early Python could only run commands through os.system and os.popen, which were thin and awkward. PEP 324 added the subprocess module in Python 2.4 (2004), and it is still the right interface today. PEP 282 added the logging module in Python 2.3 (2003), modelled on log4j's ideas of levels and handlers. PEP 428 added pathlib in Python 3.4 (2014), replacing string surgery on paths with objects. Each of these replaced a generation of fragile glue code, and each is what this lesson covers.
The embedded angle is concrete. A provisioning script that flashes SensorNode boards on a factory line is a real program: it must handle a board that does not answer, a serial port that disappears, and a report that quality engineers read months later. That is Python work. Meanwhile the board itself may run only BusyBox ash, a small shell without Bash's arrays and [[ ]] tests, so a Bash script written on your laptop may not even run there. A Python tool on the host sidesteps the problem: you cross-compile firmware on the host, and the host's shell differences stop mattering.
Here is the rule of thumb you should leave with. Reach for Bash when the job is a short pipeline of existing tools, run once, by you. Reach for Python when the job has branches, loops over structured data, retries, timeouts, or output another program must parse. The rest of this lesson builds the four skills that make the switch: paths, files, subprocesses, and logging.
pathlib: paths as objects
4 min readStart with the object itself. Path represents a filesystem path, and the / operator joins pieces onto it:
from pathlib import Path
logs = Path("/home/learner/logs")
boot = logs / "2026" / "boot.log"
print(boot) # /home/learner/logs/2026/boot.log
print(boot.name) # boot.log
print(boot.stem) # boot
print(boot.suffix) # .log
print(boot.parent) # /home/learner/logs/2026
Notice what you did not do: no os.path.join, no manual slashes, no string concatenation. The result of / is a new Path, so you can keep chaining. Two class methods give you starting points: Path.home() is the current user's home directory, and Path.cwd() is the current working directory. Path() with no argument is the same as Path.cwd().
A path object also knows how to ask questions and do small jobs:
p = Path("/home/learner/logs/boot.log")
p.exists() # True if anything is there
p.is_file() # True only for a regular file
p.is_dir() # True only for a directory
p.with_suffix(".txt") # /home/learner/logs/boot.txt, a new Path
p.stat().st_size # size in bytes
p.stat().st_mtime # last modification time, seconds since the epoch
with_suffix is the clean way to derive an output name from an input name: boot.with_suffix(".json") gives the report path next to the log. stat() returns the file's metadata, the same information the stat command shows.
Finding files is where pathlib replaces find. iterdir() yields the immediate children of a directory. glob(pattern) matches children against a shell-style pattern, and rglob(pattern) does the same recursively through all subdirectories:
for path in logs.rglob("*.log"):
size = path.stat().st_size
kind = "large" if size > 1_000_000 else "small"
print(f"{kind:5} {size:>10} {path}")
That loop is the heart of the lab: it replaces a find plus awk one-liner with code you can extend. Add a branch for symlinks, a date filter, or a JSON report, and you are writing a tool, not a line. Note that rglob does not descend into symlinked directories by default, which keeps it from wandering out of the tree you pointed it at. A a directory entry that points to another path by name, rather than to the file's data directly is followed by most operations, but resolve() shows you the real target: it returns an absolute path with every symlink expanded. Since Python 3.6 it tolerates paths that do not exist yet, which is what you want when computing an output path before creating it.
Build and resolve the paths from this section below:
For quick content I/O, pathlib has shortcuts that open, read or write, and close in one call:
text = boot.read_text(encoding="utf-8")
boot.with_suffix(".txt").write_text(text.upper(), encoding="utf-8")
raw = boot.read_bytes() # bytes, no decoding
Path("out.bin").write_bytes(raw)
Path("reports/2026").mkdir(parents=True, exist_ok=True)
Use these for small files: a config, a report, a device tree overlay. For large files or fine control over buffering, use open() directly, which is the next section. And when you maintain older code that passes paths as strings, os.path still works and accepts Path objects in most functions, so you can migrate one call at a time instead of all at once.
Key takeaways
- Bash still wins for quick pipes and one-liners; Python wins when logic, errors, and structured data appear.
- pathlib turns paths into objects: / joins, glob finds, stat inspects, and read_text or write_text does the I/O in one call.
- rglob does not descend into symlinked directories by default, so a tree walk stays inside the tree you named.
Reflect
- Explain to a colleague, in two sentences: decide when Python should replace a Bash script and when a shell one-liner is still the right tool.
- Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
- What surprised you when you ran the commands yourself?
On a real board
Repeat the key commands on your Raspberry Pi or lab board over SSH or the serial console. Note anything that behaves differently from your PC, such as missing tools, a BusyBox shell or a read-only filesystem.
References and further reading
Official documentation first. Links checked when the lesson was published.