← all cheat sheets
OPERATOR REFERENCE · PYTHON

Python Field Reference
Scripting & Automation

env → syntax → files/OS → automation → data — the scripting-for-ops slice, not the whole language
SCRIPT · .py
interpreter (CPython)
STDOUT / FILESYSTEM / NETWORK
01 Environment & Packages

Virtual Environments

python -m venv .venv source .venv/bin/activate .venv\Scripts\activate # Windows
📦

Packages

pip install requests pip freeze > requirements.txt pip install -r requirements.txt

Version Management

python --version pyenv install 3.12.0 pyenv local 3.12.0
02 Core Syntax Quick Reference
$

Types & f-strings

name = "web01" port: int = 8080 msg = f"{name} on {port}"
[]

Comprehensions

up = [h for h in hosts if h.ok] by_id = {h.id: h for h in hosts}
ƒ

Functions

def ping(host: str, timeout: int = 5) -> bool: return True

Control Flow

for host in hosts: if not host.ok: continue print(host.name)

try / except

try: resp = call() except TimeoutError as e: log.error(e) finally: cleanup()

Classes (light)

class Host: def __init__(self, name): self.name = name
03 File & OS Operations
📄

Read / Write Files

with open("out.txt") as f: data = f.read()
with guarantees the file handle is closed even on exception.
🗂

pathlib

from pathlib import Path p = Path("/etc/app.conf") p.exists() p.read_text()

subprocess

import subprocess r = subprocess.run( ["systemctl", "status", "nginx"], capture_output=True, text=True )
⚠ never pass shell=True with untrusted input
04 Automation Essentials

argparse

import argparse p = argparse.ArgumentParser() p.add_argument("--host", required=True) args = p.parse_args()
📝

logging

import logging logging.basicConfig(level=logging.INFO) log = logging.getLogger(__name__) log.info("starting run")
Prefer logging over print() in anything that runs unattended (cron, CI).
🌐

requests (HTTP)

import requests r = requests.get(url, timeout=5) r.raise_for_status() data = r.json()

Environment Variables

import os token = os.environ["API_TOKEN"] region = os.environ.get("REGION", "us-east-1")
Prefer env vars over hardcoded secrets — pair with a .env file kept out of git.
05 Data Handling
{}

json

import json data = json.loads(text) json.dumps(data, indent=2)

csv

import csv with open("hosts.csv") as f: for row in csv.DictReader(f): print(row["hostname"])
.*

re (regex)

import re m = re.search(r"(\d+\.\d+\.\d+\.\d+)", line) if m: ip = m.group(1)
06 Common Errors & Quick Reference
SymptomFix
ModuleNotFoundErrorvenv not activated, or pip install missing
IndentationErrormixed tabs/spaces — pick one, use 4 spaces
Script uses global site-packages unexpectedlyvenv not activated before pip install
UnicodeDecodeError on file readopen(..., encoding="utf-8")
Silent failure in cron jobno logging configured — add logging.basicConfig
requests hangs forevermissing timeout= on the call
ToolPurpose
python -m pdb script.pydebug step through interactively
python -i script.pydrop into a REPL after the script runs
pip list --outdatedsee which installed packages have updates
black . / ruff check .formatting and linting
pytestrun a test suite
deactivatesafe exit the active virtualenv