← 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
python -m venv .venv
source .venv/bin/activate
.venv\Scripts\activate # Windows
pip install requests
pip freeze > requirements.txt
pip install -r requirements.txt
python --version
pyenv install 3.12.0
pyenv local 3.12.0
02 Core Syntax Quick Reference
name = "web01"
port: int = 8080
msg = f"{name} on {port}"
up = [h for h in hosts if h.ok]
by_id = {h.id: h for h in hosts}
def ping(host: str, timeout: int = 5) -> bool:
return True
for host in hosts:
if not host.ok:
continue
print(host.name)
try:
resp = call()
except TimeoutError as e:
log.error(e)
finally:
cleanup()
class Host:
def __init__(self, name):
self.name = name
03 File & OS Operations
with open("out.txt") as f:
data = f.read()
with guarantees the file handle is closed even on exception.
from pathlib import Path
p = Path("/etc/app.conf")
p.exists()
p.read_text()
import subprocess
r = subprocess.run(
["systemctl", "status", "nginx"],
capture_output=True, text=True
)
⚠ never pass shell=True with untrusted input
04 Automation Essentials
import argparse
p = argparse.ArgumentParser()
p.add_argument("--host", required=True)
args = p.parse_args()
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).
import requests
r = requests.get(url, timeout=5)
r.raise_for_status()
data = r.json()
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
import json
data = json.loads(text)
json.dumps(data, indent=2)
import csv
with open("hosts.csv") as f:
for row in csv.DictReader(f):
print(row["hostname"])
import re
m = re.search(r"(\d+\.\d+\.\d+\.\d+)", line)
if m: ip = m.group(1)
06 Common Errors & Quick Reference
| Symptom | Fix |
| ModuleNotFoundError | venv not activated, or pip install missing |
| IndentationError | mixed tabs/spaces — pick one, use 4 spaces |
| Script uses global site-packages unexpectedly | venv not activated before pip install |
| UnicodeDecodeError on file read | open(..., encoding="utf-8") |
| Silent failure in cron job | no logging configured — add logging.basicConfig |
| requests hangs forever | missing timeout= on the call |
| Tool | Purpose |
| python -m pdb script.py | debug step through interactively |
| python -i script.py | drop into a REPL after the script runs |
| pip list --outdated | see which installed packages have updates |
| black . / ruff check . | formatting and linting |
| pytest | run a test suite |
| deactivate | safe exit the active virtualenv |