Shell & Scripting15 min
Python One-Liners & Quick Patterns Cheat Sheet
Python quick reference — CLI one-liners, comprehensions, file I/O, data manipulation, common stdlib modules, and scripting patterns used in DevOps and automation.
Python at the Command Line
# Run a one-liner
python3 -c "print('hello')"
# Pretty-print JSON from stdin
echo '{"a":1}' | python3 -m json.tool
cat file.json | python3 -m json.tool
# Start an HTTP server in current directory
python3 -m http.server 8080
# Run a script
python3 script.py
# Interactive REPL
python3
# Check version
python3 --version
List Comprehensions
# Basic
squares = [x**2 for x in range(10)]
# Filtered
evens = [x for x in range(20) if x % 2 == 0]
# Nested
matrix = [[i*j for j in range(5)] for i in range(5)]
# Flatten nested list
flat = [x for row in matrix for x in row]
# Dict comprehension
word_len = {word: len(word) for word in ["apple", "banana", "cherry"]}
# Set comprehension
unique_lengths = {len(w) for w in ["apple", "banana", "cherry"]}
# Generator expression (lazy)
total = sum(x**2 for x in range(1_000_000))
Strings
s = " Hello, World! "
s.strip() # "Hello, World!"
s.lower() # " hello, world! "
s.upper() # " HELLO, WORLD! "
s.replace(",", ";") # " Hello; World! "
s.split(", ") # [" Hello", "World! "]
", ".join(["a","b","c"]) # "a, b, c"
s.startswith(" Hello") # True
s.count("l") # 3
len(s) # 18
# f-strings
name, age = "Alice", 30
f"Name: {name}, Age: {age}"
f"Pi: {3.14159:.2f}" # "Pi: 3.14"
f"Hex: {255:#x}" # "Hex: 0xff"
# Multiline
text = """
line one
line two
""".strip()
# Check / search
"world" in s.lower() # True
import re
re.findall(r"\d+", "a1b23c456") # ['1', '23', '456']
re.sub(r"\s+", " ", "a b c") # "a b c"
Lists & Tuples
lst = [3, 1, 4, 1, 5, 9]
lst.append(2) # add to end
lst.insert(0, 0) # insert at index
lst.pop() # remove + return last
lst.pop(0) # remove + return at index
lst.remove(4) # remove first occurrence of value
lst.sort() # in-place sort
sorted(lst) # returns new sorted list
sorted(lst, reverse=True)
lst.reverse()
lst.index(5) # index of first 5
lst.count(1) # how many 1s
lst[::-1] # reversed slice
lst[1:4] # slice [index 1, 2, 3]
any(x > 8 for x in lst) # True if any match
all(x > 0 for x in lst) # True if all match
Dictionaries
d = {"a": 1, "b": 2, "c": 3}
d["d"] = 4 # add/update
d.get("x", 0) # get with default
d.pop("b") # remove key
"a" in d # key membership check
d.keys()
d.values()
d.items() # (key, value) pairs
# Merge dicts (Python 3.9+)
merged = d1 | d2
d1 |= d2 # update in place
# Safely update
d.setdefault("new_key", []).append("value")
# Sort by value
sorted(d.items(), key=lambda kv: kv[1])
# Invert
inv = {v: k for k, v in d.items()}
File I/O
# Read entire file
with open("file.txt") as f:
content = f.read()
# Read lines
with open("file.txt") as f:
lines = f.readlines() # list of lines (with \n)
# Read line by line (memory-efficient)
with open("file.txt") as f:
for line in f:
print(line.strip())
# Write
with open("out.txt", "w") as f:
f.write("hello\n")
# Append
with open("log.txt", "a") as f:
f.write("new entry\n")
# JSON
import json
data = json.loads('{"key": "value"}')
json_str = json.dumps(data, indent=2)
with open("data.json") as f:
data = json.load(f)
with open("out.json", "w") as f:
json.dump(data, f, indent=2)
OS & Path Operations
import os
import pathlib
os.getcwd() # current directory
os.listdir(".") # list dir
os.makedirs("a/b/c", exist_ok=True)
os.path.exists("file.txt")
os.path.join("dir", "file.txt")
os.path.basename("/a/b/file.txt") # "file.txt"
os.path.dirname("/a/b/file.txt") # "/a/b"
os.path.splitext("file.txt") # ("file", ".txt")
os.environ.get("HOME", "/tmp")
os.getenv("MY_VAR", "default")
# pathlib (modern, recommended)
from pathlib import Path
p = Path("./data")
p.mkdir(parents=True, exist_ok=True)
p / "file.txt" # Path("./data/file.txt")
list(p.glob("*.json"))
list(p.rglob("*.py"))
p.read_text()
p.write_text("content")
p.exists()
p.stem # filename without extension
p.suffix # ".txt"
p.parent
Running Shell Commands
import subprocess
# Run and capture output
result = subprocess.run(["ls", "-la"], capture_output=True, text=True)
print(result.stdout)
print(result.returncode)
# Check for errors
result = subprocess.run(["git", "status"], capture_output=True, text=True, check=True)
# Shell pipeline equivalent
result = subprocess.run("ls -la | grep .py", shell=True, capture_output=True, text=True)
# Run and don't wait
proc = subprocess.Popen(["python3", "worker.py"])
proc.wait()
Common Stdlib Modules
# datetime
from datetime import datetime, timedelta
now = datetime.now()
now.strftime("%Y-%m-%d %H:%M:%S")
datetime.strptime("2025-01-20", "%Y-%m-%d")
now + timedelta(days=7)
# collections
from collections import Counter, defaultdict, deque
Counter("abracadabra") # {'a': 5, 'b': 2, ...}
d = defaultdict(list) # auto-creates lists
d["key"].append("value")
# itertools
from itertools import chain, islice, groupby
list(chain([1,2], [3,4])) # [1,2,3,4]
list(islice(range(100), 5)) # [0,1,2,3,4]
# functools
from functools import lru_cache, partial
@lru_cache(maxsize=128)
def fib(n): return n if n < 2 else fib(n-1) + fib(n-2)
# argparse (CLI scripts)
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--name", required=True)
parser.add_argument("--count", type=int, default=1)
args = parser.parse_args()
print(f"Hello {args.name} x{args.count}")
Useful One-Liners (CLI)
# Print line 10 of a file
python3 -c "import sys; print(open(sys.argv[1]).readlines()[9])" file.txt
# Count lines in file
python3 -c "print(sum(1 for _ in open('file.txt')))"
# CSV to JSON
python3 -c "import csv,json,sys; print(json.dumps(list(csv.DictReader(open(sys.argv[1])))))" data.csv
# Reverse a file line by line
python3 -c "import sys; print('\n'.join(reversed(open(sys.argv[1]).read().splitlines())))" file.txt
# Find duplicates
python3 -c "
from collections import Counter
import sys
c = Counter(open(sys.argv[1]).readlines())
for line, n in c.items():
if n > 1: print(f'{n}x: {line.strip()}')
" file.txt
