Topic 4 of 12

Python and scripting for ops

Learn when to reach for Bash or Python, and write small ops scripts that read files, parse config, call APIs and run commands without surprises.

After this topic you can: You can write a short Python script that reads config, calls an API, runs a command, logs what it did and exits with an honest exit code.

7 lessons · 61 min · 0 of 7 done

Best read after: Linux and the shell

Draft. This lesson is written and waiting for a person to run every command and review it. It is safe to learn from, but check the official documentation for anything you depend on.

Lessons, in order

  1. 1Bash or Python: picking the right toolCoreLearn how to decide between a Bash script and a Python script for an ops task, and what both must do so cron and CI can trust them.6 min
  2. 2Python environments: venv and requirementsCoreLearn why each Python project gets its own virtual environment, how to create one, and how requirements.txt rebuilds it anywhere.8 min
  3. 3Reading and writing files with pathlibCoreLearn to read and write text files in Python with pathlib, stay independent of the working directory, and write output so readers never see half a file.9 min
  4. 4Parsing JSON and YAML config safelyCoreLearn to load JSON and YAML into Python, why yaml.safe_load is the only loader to use on config, and how to catch bad or surprising values early.9 min
  5. 5Running commands with subprocessCoreLearn to run other programs from Python with subprocess.run, read their output and exit codes, set timeouts, and avoid shell injection.9 min
  6. 6Calling HTTP APIs with requestsCoreLearn to call an HTTP API from Python with requests: read status codes and JSON, send a token safely, set timeouts, and retry transient failures.11 min
  7. 7Errors, logging and honest exit codesCoreLearn to handle exceptions with useful messages, set up the logging module, and exit non-zero so cron and CI can tell when a script failed.9 min

Keep these open while you learn

Next topic

Git and collaborationUnderstand how git records history, how branches, remotes and pull requests work, and how to undo mistakes and keep secrets out of a repository.

Search

Search cheat sheets and projects