Skip to content
Visual explainer 4h to learn 5 steps

subprocess, pathlib & OS automation

Run and check system commands safely from Python.

By Invicly Tech, , in Full DevOps with Python. About 11 minutes to read.

Topic 8 of 34

In short

pathlib handles file paths cleanly and subprocess runs system commands from Python. Passing arguments as a list and checking return codes keeps automation safe and predictable.

Explained simply

Automation scripts constantly touch the operating system: they find files, delete old ones, create folders and run other programs like git, docker or df. Python has two tools that make this clean: pathlib for file paths and subprocess for running commands.

pathlib treats a path as an object instead of a plain string. You join parts with a slash, Path("/var/log") / "app", and ask questions like .exists() or .suffix. It handles the differences between Linux and Windows paths for you.

subprocess.run starts another program, waits for it, and tells you how it went. The exit code (also called the return code) is the program's answer: 0 means success, anything else means something went wrong. A good script always checks it.

The big safety rule: pass the command as a list of words, not as one long string. Then no shell reads your text, so a strange file name cannot sneak in an extra command. This one habit prevents a whole class of security bugs.

Press Play on a diagram to walk through it one step at a time.

CompareRunning a command
List args (safe)
  • run(["du", "-sh", path])
  • No shell involved
  • Spaces and symbols are safe
  • Use by default
shell=True (risky)
  • run(f"du -sh {path}", shell=True)
  • Shell parses the string
  • Input can inject commands
  • Only for trusted fixed strings
MapPython's OS automation toolbox
Standard library
  • pathlib
    • Build and inspect paths
    • glob, rglob, read_text, stat
  • shutil
    • copy2, move, rmtree
    • disk_usage, which
  • os
    • environ, getuid
    • replace, chmod
  • subprocess
    • run with a list of args
    • Popen to stream output
  • shlex
    • split a trusted string
    • quote an untrusted value

In depth

pathlib and shutil methods you will use every day

Build paths with /: base / "logs" / "app.log". Pull them apart with .name (app.log), .stem (app), .suffix (.log) and .parent (the folder). Path.home() gives your home folder, and Path(__file__).resolve().parent gives the folder of the current script, which is the right base for files that ship next to it.

folder.mkdir(parents=True, exist_ok=True) works like mkdir -p. path.unlink(missing_ok=True) deletes a file without failing if it is already gone. folder.glob("*.log") matches one level and rglob("*.log") searches every subfolder. p.stat() returns the size (st_size) and the last modified time (st_mtime).

For work pathlib does not cover, use shutil: copy2 copies a file with its timestamps, move moves it, rmtree deletes a whole folder tree, disk_usage reports free space, and which finds a program on PATH.

  • Path(__file__).resolve().parent / "config.yaml" finds a file next to the script
  • shutil.disk_usage("/").free gives free bytes without running df
  • shutil.which("docker") returns None if docker is not installed

What subprocess.run does under the hood

With a list like ["git", "pull"], Python asks the operating system to start the program directly. The OS looks up git on PATH and hands it the list as its arguments. No shell is involved, so quotes, *, $ and ; have no special meaning. Python then waits until the child exits and returns a CompletedProcess with args, returncode, stdout and stderr.

If the program does not exist, you get FileNotFoundError before anything runs. If you pass timeout=30 and the command takes longer, Python kills the child and raises TimeoutExpired, so a hung command cannot freeze your job forever.

The child inherits your environment variables and current folder. Change them per call with cwd="/srv/app" and env={**os.environ, "LANG": "C"}. Passing env without copying os.environ first wipes PATH and everything else.

Sequencesubprocess.run(["git", "pull"], capture_output=True, check=True)
Python script
Operating system
git process
  1. 1Start git with argv [git, pull]
    Python script to Operating system: Start git with argv [git, pull]
  2. 2Run it with inherited env and cwd
    Operating system to git process: Run it with inherited env and cwd
  3. 3Write output into pipes
    git process to Operating system: Write output into pipes
  4. 4Exit with a return code
    git process to Operating system: Exit with a return code
  5. 5Return code and captured output
    Operating system to Python script: Return code and captured output

Return codes, output, and commands that bend the rules

capture_output=True collects stdout and stderr, and text=True decodes them to strings. check=True raises CalledProcessError on any non-zero exit; the exception carries .returncode, .stdout and .stderr, so log stderr when you catch it.

Some commands use non-zero codes for normal answers. grep exits 1 when nothing matched and 2 on a real error. diff exits 1 when files differ. systemctl is-active exits non-zero when a unit is not running. For these, skip check=True and test result.returncode yourself.

capture_output waits until the program finishes and keeps all output in memory. For a long build whose output you want to see live, leave output uncaptured (it goes straight to your terminal) or use subprocess.Popen and read line by line. To feed data to the command's stdin, pass input="text".

  • grep: 0 found, 1 not found, 2 error
  • stderr=subprocess.STDOUT merges both streams into stdout
  • Do the filtering in Python instead of using shell=True for a pipe

Injection, concretely

Imagine a user supplies the file name report; rm -rf ~. With run(f"wc -l {name}", shell=True), the shell sees two commands and runs both. With run(["wc", "-l", name]), wc simply receives one strange file name and reports that it does not exist.

A quieter cousin is argument injection: a file named -rf or --help is read as an option even in list form. Put -- before user-supplied names (rm -- name), which tells most tools that options have ended, or prefix relative paths with ./ so they cannot start with a dash.

If you truly need shell features like pipes or globs, prefer doing them in Python (glob, sorted, filtering lines). When a shell string is unavoidable, quote every untrusted piece with shlex.quote. To turn a trusted command string from a config file into a safe list, use shlex.split("rsync -av src/ dst/").

Scripting a disk clean-up responsibly

Clean-up scripts are where automation does real damage, so build in brakes. First, make dry-run the default and require an explicit --apply flag to delete anything. Second, restrict scope: resolve the target folder, refuse to run on / or the home folder, and only touch files that match a pattern. Third, do not follow symlinks out of the folder; check that each resolved path is still inside the base with path.resolve().is_relative_to(base) (Python 3.9 and later).

Log every file you delete together with its size, and print a summary of freed space at the end. Handle files that disappear while you run (FileNotFoundError) and files you cannot delete (PermissionError) without stopping the whole job.

Finally, measure free space before and after with shutil.disk_usage, and exit non-zero if it is still below your threshold, so monitoring notices.

FlowA safe clean-up run
  1. 1
    Parse args

    Dry run unless --apply is given

  2. 2
    Resolve base

    Refuse / and the home folder

  3. 3
    Find candidates

    Name pattern and age filter

  4. 4
    Check each path

    Still inside base, not a symlink

  5. 5
    Delete or report

    Log the name and size

  6. 6
    Summarise

    Freed space and exit code

Learn it in 5 short steps

About 50m each. Track them with a timer in your plan.

  1. 1
    Build paths portably with pathlib~50m
  2. 2
    Run commands with subprocess.run~50m
  3. 3
    Capture output and check return codes~50m
  4. 4
    Avoid shell=True and injection risks~50m
  5. 5
    Script a disk-cleanup task~50m

Key points

  • pathlib joins paths with / and works on Linux, macOS and Windows.
  • check=True raises an error when a command fails instead of continuing silently.
  • capture_output=True and text=True give you stdout and stderr as strings.
  • Never build shell strings from user input; pass a list of arguments.

Key terms

Tap a card to flip it. 0/4 known

Examples

python
import subprocess, time
from pathlib import Path

log_dir = Path("/var/log/myapp")
cutoff = time.time() - 7 * 86400
for f in log_dir.glob("*.log.gz"):
    if f.stat().st_mtime < cutoff:
        print("Deleting", f)
        f.unlink()

result = subprocess.run(["df", "-h", str(log_dir)],
                        capture_output=True, text=True, check=True)
print(result.stdout)

Delete week-old compressed logs, then report disk usage.

Pre-deploy checks: tools present, git tree clean

Before deploying, the script makes sure the needed tools exist and that nobody is deploying uncommitted code. Step 1: shutil.which checks each tool without running it. Step 2: git rev-parse gives the short commit SHA for the release name. Step 3: git status --porcelain prints nothing when the tree is clean, so any output means stop. sys.exit with a string prints it to stderr and exits with code 1, which CI shows as a failure.

python
import shutil, subprocess, sys

for tool in ["git", "docker", "kubectl"]:
    if shutil.which(tool) is None:
        sys.exit(f"missing tool: {tool}")

def git(*args):
    return subprocess.run(["git", *args], capture_output=True,
                          text=True, check=True, timeout=30).stdout.strip()

sha = git("rev-parse", "--short", "HEAD")
if git("status", "--porcelain"):
    sys.exit("working tree has uncommitted changes")
print(f"deploying {sha}")

Delete old logs with a dry-run default

Step 1: take the folder as an argument and resolve it to an absolute path. Step 2: refuse dangerous targets. Step 3: walk the tree with rglob and pick regular files (not symlinks) older than 14 days. Step 4: without --apply, only print what would happen; with it, delete. Step 5: report how much space was or would be freed. Run it once without --apply and read the list before trusting it.

python
import argparse, time
from pathlib import Path

p = argparse.ArgumentParser()
p.add_argument("base", type=Path)
p.add_argument("--apply", action="store_true")
a = p.parse_args()
base = a.base.resolve()
if base in (Path("/"), Path.home()): raise SystemExit("refusing to clean this folder")
cutoff, freed = time.time() - 14 * 86400, 0
for f in base.rglob("*.log*"):
    if f.is_file() and not f.is_symlink() and f.stat().st_mtime < cutoff:
        freed += f.stat().st_size
        print("delete" if a.apply else "would delete", f)
        if a.apply: f.unlink(missing_ok=True)

Quick reference

  • Path(__file__).resolve().parent is the folder your script lives in
  • p.mkdir(parents=True, exist_ok=True) is the Python version of mkdir -p
  • run(cmd, capture_output=True, text=True, check=True) is the safe default
  • timeout=60 stops a hung command and raises TimeoutExpired
  • env={**os.environ, "KEY": "v"} adds a variable without losing PATH
  • grep returns 1 for no match; check returncode yourself for such commands
  • shlex.split turns a trusted string into a list; shlex.quote escapes one value
  • Put -- before user-supplied file names so they cannot be read as options

Common mistakes

  • Ignoring the return code, so a failed command looks like success.
  • Using shell=True with an f-string that contains a user-supplied file name.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1What does subprocess.run(["grep", "x", "f.txt"], check=True) do when grep finds no match?

Question 2

2You pass env={"APP_ENV": "prod"} to subprocess.run and now the command is "not found". Why?

Question 3

3What does Path("backup.tar.gz").suffix return?

Question 4

4Why can run(["rm", name]) still be risky if name comes from a user?

0/4 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Print the 5 largest files under a folder with their sizes in MB, using only pathlib.

  2. Exercise 2medium

    Write a helper sh(*args) that logs the command, runs it with a 60 second timeout, returns stdout, and on failure raises RuntimeError containing the exit code and stderr.

  3. Exercise 3hard

    Find every git repository under ~/code (folders containing .git) and report which ones have uncommitted changes or commits not yet pushed to their upstream branch.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

When is shell=True acceptable?
Only for fixed command strings you wrote yourself that genuinely need shell features, with no outside input mixed in. Even then, doing the pipe or glob in Python is usually cleaner.
Should I use os.path or pathlib?
pathlib for new code. os.path works with plain strings and still appears in older scripts, but pathlib is easier to read and most standard library functions accept Path objects.
How do I see a command's output live while it runs?
Do not capture it: subprocess.run(cmd, check=True) lets the output go straight to your terminal. If you need to process lines as they arrive, use subprocess.Popen with stdout=subprocess.PIPE and loop over proc.stdout.
Why does my script work in the terminal but fail under cron?
cron runs with a tiny PATH and a different working folder. Use absolute paths for files and commands, or set PATH at the top of the crontab.

Go deeper

ShareXLinkedInWhatsApp