Python
Python for scripts and automation: the environment, text and files, data structures, errors and the standard library you use most.
Environment
python3 -m venv .venv && source .venv/bin/activateA private set of packages for this project
pip install requestsInstall a package into the active environment
pip freeze > requirements.txt | pip install -r requirements.txtSave and restore the packages
python3 script.py arg1 arg2Run a script with arguments
python3 -m http.server 8000Serve the current folder over HTTP
python3 -m pytest -qRun the tests
Strings and numbers
name = "Ann"; f"Hello {name}, {3 * 1.5:.2f}"f-strings, with number formatting
"a,b,c".split(",") | ",".join(["a", "b"])Split a string into a list and join it back
s.strip() s.lower() s.replace("x", "y") s.startswith("a")Common string methods
int("42") float("1.5") str(7)Convert between types
divmod(17, 5) | 17 // 5 | 17 % 5Integer division and remainder
Lists, dicts, sets
squares = [n * n for n in range(10) if n % 2 == 0]A list comprehension
for i, item in enumerate(items, start=1):Loop with a counter
sorted(users, key=lambda u: u["age"], reverse=True)Sort by a field
d.get("key", "default") | d.items() | {**a, **b}Safe lookup, pairs, and merging dictionaries
{k: v for k, v in pairs} | set(items)A dict comprehension, and unique items
a, *rest = [1, 2, 3, 4]Unpack the first item and the rest
from collections import Counter Counter(words).most_common(3)Count things
Files and data
with open("a.txt", encoding="utf-8") as f: for line in f: print(line.rstrip())Read a file line by line (it closes by itself)
Path("out").mkdir(exist_ok=True)from pathlib import Path: create a folder safely
Path("a.txt").read_text() | Path("a.txt").write_text("hi")Read or write a small file
import json data = json.load(open("a.json")) json.dump(data, open("b.json", "w"), indent=2)JSON in and out
import csv for row in csv.DictReader(open("a.csv")): print(row["name"])Read a CSV with column names
Functions and errors
def greet(name: str, shout: bool = False) -> str: return name.upper() if shout else nameA function with defaults and type hints
try: value = int(text) except ValueError as e: print(f"not a number: {e}") else: print(value)Handle a specific error
raise ValueError("port must be 1-65535")Signal a problem
if __name__ == "__main__": main()Run main() only when the file is executed, not imported
assert total >= 0, "total cannot be negative"A quick check while developing
Scripts and the system
import argparse p = argparse.ArgumentParser() p.add_argument("path") p.add_argument("--count", type=int, default=1) args = p.parse_args()Command-line options
import subprocess out = subprocess.run(["ls", "-l"], capture_output=True, text=True, check=True).stdoutRun a command and read its output
import os os.environ.get("HOME") | sys.argv | sys.exit(1)Environment variables, arguments, and an exit code
import logging logging.basicConfig(level=logging.INFO) logging.info("started")Logging instead of print
import requests r = requests.get(url, timeout=10) r.raise_for_status() r.json()Call an HTTP API (always set a timeout)
Nothing matches that search.
Cheatsheet for the Python path · Deboistech · All cheatsheets