Automating the system
Once a shell script needs real error handling, options and logic, Python is usually the better tool. This chapter covers the standard-library modules that replace everyday shell work (files, environment variables, running commands, copying and archiving) and how to wrap them into a proper command-line tool with options, logs and exit codes.
pathlib: paths as objects
pathlib.Path replaces string juggling with os.path. The / operator joins path parts, and methods do the file work:
from pathlib import Path
logs = Path("/var/log/myapp")
report = Path.home() / "reports" / "daily.txt" # /home/demee/reports/daily.txt
report.parent.mkdir(parents=True, exist_ok=True) # like mkdir -p
for f in sorted(logs.glob("*.log")): # rglob() searches subfolders too
print(f"{f.name:<20} {f.stat().st_size / 1024:8.1f} KB")
report.write_text("all good\n") # create / overwrite
text = report.read_text()
p = Path("/etc/nginx/sites-available/site.conf")
p.name, p.stem, p.suffix # ('site.conf', 'site', '.conf')
p.parent # PosixPath('/etc/nginx/sites-available')
p.exists(), p.is_file(), p.is_dir()
p.with_suffix(".bak") # PosixPath('/etc/nginx/sites-available/site.bak')
Path("old.tmp").unlink(missing_ok=True) # delete, no error if already gone
f.stat() gives file details: st_size in bytes and st_mtime, the last-modified time in seconds since 1970, which you compare with time.time() to find old files.
Environment variables
import os
db_host = os.environ["DB_HOST"] # KeyError if missing: fail early and loudly
port = int(os.environ.get("PORT", "8080")) # default if missing; values are ALWAYS strings
debug = os.environ.get("DEBUG", "").lower() in ("1", "true", "yes")
Watch the last line: bool("false") is True, because any non-empty string is truthy, so compare the text explicitly. Assigning os.environ["X"] = "1" affects your script and the commands it starts, never the shell that ran it.
Running commands with subprocess
import subprocess
result = subprocess.run(
["systemctl", "is-active", "nginx"], # a list: program, then each argument
capture_output=True, # collect stdout/stderr instead of printing them
text=True, # give str, not bytes
)
result.returncode # 0 if active, non-zero otherwise
result.stdout.strip() # 'active', 'inactive', 'failed'...
try:
commit = subprocess.run(
["git", "rev-parse", "--short", "HEAD"],
capture_output=True, text=True, check=True, timeout=30,
).stdout.strip()
except FileNotFoundError:
print("git is not installed")
except subprocess.CalledProcessError as e: # raised by check=True on a non-zero exit
print(f"git failed ({e.returncode}): {e.stderr.strip()}")
except subprocess.TimeoutExpired:
print("git took too long")
- Without
check=Truea failing command is silently ignored unless you look atreturncodeyourself. It's the Python version ofset -e. - Pass arguments as a list.
shell=Truewith a string lets the shell interpret it, so a file name likex; rm -rf ~coming from user input would run as a command. Only use it for fixed strings where you really need pipes or wildcards. shutil.which("docker")returns the path of a command orNone, handy to check before calling it.
shutil: copying, moving, archiving, disk space
import shutil
shutil.copy2("app.conf", "app.conf.bak") # copy a file, keeping timestamps
shutil.copytree("site", "site-backup", dirs_exist_ok=True) # copy a whole folder
shutil.move("report.txt", "archive/") # move or rename
shutil.make_archive("backup-2026-09-27", "gztar", root_dir="app")
# -> backup-2026-09-27.tar.gz with the contents of app/
usage = shutil.disk_usage("/") # total, used, free (bytes)
print(f"{usage.free / 1e9:.1f} GB free")
shutil.rmtree("build") # rm -r: no confirmation, no undo
argparse: a real command-line interface
sys.argv is the raw list of arguments; argparse turns it into named options with types, defaults, validation and an automatic --help. The full script at the end of this chapter uses it; the core is:
import argparse
from pathlib import Path
p = argparse.ArgumentParser(description="Delete old log files.")
p.add_argument("directory", type=Path) # positional, required
p.add_argument("--days", type=int, default=14) # optional, converted to int
p.add_argument("--dry-run", action="store_true") # flag: False unless given
args = p.parse_args() # --dry-run becomes args.dry_run
Bad input is handled for you: --days abc prints error: argument --days: invalid int value: 'abc' and exits with code 2. One quirk: help texts are %-formatted, so a literal percent sign must be written %%.
logging instead of print
import logging
logging.basicConfig(level=logging.INFO,
format="%(asctime)s %(levelname)s %(message)s")
log = logging.getLogger("backup")
log.debug("hidden: DEBUG is below the INFO level")
log.info("backing up %s", "/srv/app") # values passed separately, formatted by logging
log.warning("disk is %d%% full", 85)
try:
1 / 0
except ZeroDivisionError:
log.exception("backup failed") # ERROR level plus the full traceback
2026-09-27 10:15:02,114 INFO backing up /srv/app
2026-09-27 10:15:02,114 WARNING disk is 85% full
2026-09-27 10:15:02,114 ERROR backup failed
Traceback (most recent call last):
...
ZeroDivisionError: division by zero
Levels from least to most serious: DEBUG, INFO, WARNING, ERROR, CRITICAL. Only messages at or above the configured level appear, so you can turn on detail with level=logging.DEBUG without touching the rest of the code. Without basicConfig only warnings and above are shown. Logging writes to stderr by default, which systemd captures into the journal and cron sends wherever you redirected 2>&1; add filename="app.log" to write to a file instead.
Exit codes with sys.exit
Like a shell script, a Python script tells the caller whether it worked through its exit code. sys.exit(0) is success, sys.exit(1) (or any other number) is failure, and sys.exit("message") prints the message to stderr and exits with 1. An unhandled exception also exits with 1. The clean pattern is a main() that returns the code.
Putting it together: log cleanup with a disk alert
#!/usr/bin/env python3
"""Delete old rotated log files, then warn if the disk is still too full."""
import argparse
import logging
import shutil
import sys
import time
from pathlib import Path
log = logging.getLogger("cleanup")
def parse_args():
p = argparse.ArgumentParser(description=__doc__)
p.add_argument("directory", type=Path, help="folder to clean, e.g. /var/log/myapp")
p.add_argument("--days", type=int, default=14,
help="delete files older than this many days (default: 14)")
p.add_argument("--pattern", default="*.gz",
help="which files may be deleted (default: *.gz)")
p.add_argument("--threshold", type=int, default=90,
help="disk usage %% that counts as a problem (default: 90)")
p.add_argument("--dry-run", action="store_true",
help="only show what would be deleted")
return p.parse_args()
def old_files(directory, pattern, days):
cutoff = time.time() - days * 24 * 60 * 60
for path in directory.glob(pattern):
if path.is_file() and path.stat().st_mtime < cutoff:
yield path
def main():
args = parse_args()
logging.basicConfig(level=logging.INFO,
format="%(asctime)s %(levelname)s %(message)s")
if not args.directory.is_dir():
log.error("%s is not a directory", args.directory)
return 2
freed = 0
for path in old_files(args.directory, args.pattern, args.days):
size = path.stat().st_size
if args.dry_run:
log.info("would delete %s (%d KB)", path, size // 1024)
else:
try:
path.unlink()
except PermissionError:
log.warning("no permission to delete %s", path)
continue
log.info("deleted %s", path)
freed += size
log.info("%s %.1f MB", "would free" if args.dry_run else "freed", freed / 1_000_000)
usage = shutil.disk_usage(args.directory)
percent = usage.used / (usage.used + usage.free) * 100 # same formula as df
if percent >= args.threshold:
log.error("disk is %.0f%% full (threshold %d%%)", percent, args.threshold)
return 1
log.info("disk is %.0f%% full, ok", percent)
return 0
if __name__ == "__main__":
sys.exit(main())
$ python3 cleanup_logs.py /var/log/myapp --days 30 --dry-run
2026-09-27 10:20:11,482 INFO would delete /var/log/myapp/app.log.5.gz (292 KB)
2026-09-27 10:20:11,482 INFO would delete /var/log/myapp/app.log.6.gz (288 KB)
2026-09-27 10:20:11,483 INFO would free 0.6 MB
2026-09-27 10:20:11,483 INFO disk is 29% full, ok
# happy with the list? schedule it (crontab -e) and keep its log:
30 4 * * * /usr/bin/python3 /opt/scripts/cleanup_logs.py /var/log/myapp --days 30 >> /var/log/cleanup.log 2>&1
Design choices worth copying: a --dry-run flag for anything that deletes, one exit code per outcome (0 fine, 1 disk still full, 2 bad input, the same code argparse uses), a permission problem on one file logged instead of crashing the whole run, and only the standard library, so it runs with the system python3 and needs no virtual environment on the server. The disk percentage uses used / (used + free) because that's how df computes Use%: part of the disk is reserved for root, so used / total would look lower than what df shows.