Python CLI
Command-line interface patterns with argparse and click.
JSON Processing
# Pretty print JSON
cat file.json | python -m json.tool
# Compact JSON (remove whitespace)
cat file.json | python -c "import sys,json; print(json.dumps(json.load(sys.stdin),separators=(',',':')))"
# Extract single key
echo '{"key":"value"}' | python -c "import sys,json; print(json.load(sys.stdin)['key'])"
# Extract nested key
echo '{"a":{"b":"value"}}' | python -c "import sys,json; print(json.load(sys.stdin)['a']['b'])"
# Extract from array
echo '[{"name":"a"},{"name":"b"}]' | python -c "import sys,json; print([x['name'] for x in json.load(sys.stdin)])"
# Filter array
echo '[{"status":"ok"},{"status":"fail"}]' | python -c "import sys,json; print([x for x in json.load(sys.stdin) if x['status']=='ok'])"
# Transform keys to list
echo '{"a":1,"b":2}' | python -c "import sys,json; print(list(json.load(sys.stdin).keys()))"
# Merge JSON files
python -c "import json; print(json.dumps({**json.load(open('a.json')), **json.load(open('b.json'))}, indent=2))"
HTTP Server and Client
# Simple HTTP server (current directory)
python -m http.server 8000
# HTTP server on specific interface
python -m http.server 8000 --bind 127.0.0.1
# HTTP server with directory
python -m http.server 8000 --directory /path/to/serve
# Quick GET request
python -c "import urllib.request; print(urllib.request.urlopen('https://example.com').read().decode())"
# GET with headers
python -c "
import urllib.request
req = urllib.request.Request('https://example.com', headers={'User-Agent': 'curl/7.0'})
print(urllib.request.urlopen(req).read().decode())
"
# Download file
python -c "import urllib.request; urllib.request.urlretrieve('https://example.com/file.zip', 'file.zip')"
# POST JSON (stdlib only)
python -c "
import urllib.request, json
data = json.dumps({'key': 'value'}).encode()
req = urllib.request.Request('https://api.example.com', data=data, headers={'Content-Type': 'application/json'})
print(urllib.request.urlopen(req).read().decode())
"
Encoding and Decoding
# Base64 encode
python -c "import base64; print(base64.b64encode(b'secret').decode())"
# Base64 decode
python -c "import base64; print(base64.b64decode('c2VjcmV0').decode())"
# Base64 file
python -c "import base64,sys; print(base64.b64encode(open(sys.argv[1],'rb').read()).decode())" file.bin
# URL encode
python -c "import urllib.parse; print(urllib.parse.quote('hello world & stuff'))"
# URL encode full
python -c "import urllib.parse; print(urllib.parse.quote_plus('hello world & stuff'))"
# URL decode
python -c "import urllib.parse; print(urllib.parse.unquote('hello%20world'))"
# HTML escape
python -c "import html; print(html.escape('<script>alert(1)</script>'))"
# HTML unescape
python -c "import html; print(html.unescape('<script>'))"
# Hex encode
python -c "print('secret'.encode().hex())"
# Hex decode
python -c "print(bytes.fromhex('736563726574').decode())"
Cryptographic Operations
# Generate random password
python -c "import secrets,string; print(''.join(secrets.choice(string.ascii_letters+string.digits) for _ in range(24)))"
# Generate random hex token
python -c "import secrets; print(secrets.token_hex(32))"
# Generate URL-safe token
python -c "import secrets; print(secrets.token_urlsafe(32))"
# SHA256 hash of string
python -c "import hashlib; print(hashlib.sha256(b'password').hexdigest())"
# SHA256 hash of file
python -c "import hashlib,sys; print(hashlib.sha256(open(sys.argv[1],'rb').read()).hexdigest())" file.bin
# MD5 (not for security, for checksums)
python -c "import hashlib; print(hashlib.md5(b'data').hexdigest())"
# UUID generation
python -c "import uuid; print(uuid.uuid4())"
# HMAC
python -c "import hmac; print(hmac.new(b'key', b'message', 'sha256').hexdigest())"
Date and Time
# Current timestamp
python -c "import time; print(int(time.time()))"
# ISO format now
python -c "from datetime import datetime; print(datetime.now().isoformat())"
# UTC now
python -c "from datetime import datetime,timezone; print(datetime.now(timezone.utc).isoformat())"
# Parse timestamp
python -c "from datetime import datetime; print(datetime.fromtimestamp(1709251200))"
# Parse ISO string
python -c "from datetime import datetime; print(datetime.fromisoformat('2026-02-27T10:30:00'))"
# Date arithmetic
python -c "from datetime import datetime,timedelta; print((datetime.now() + timedelta(days=30)).isoformat())"
# Format date
python -c "from datetime import datetime; print(datetime.now().strftime('%Y-%m-%d %H:%M:%S'))"
# Time ago
python -c "from datetime import datetime,timedelta; ago=datetime.now()-timedelta(hours=2); print(f'{int((datetime.now()-ago).total_seconds()/3600)}h ago')"
Text Processing
# Simple regex match
echo "email@example.com" | python -c "import sys,re; m=re.search(r'[\w.-]+@[\w.-]+', sys.stdin.read()); print(m.group() if m else '')"
# Extract all matches
echo "a@b.com and c@d.com" | python -c "import sys,re; print(re.findall(r'[\w.-]+@[\w.-]+', sys.stdin.read()))"
# Replace with regex
echo "Hello World" | python -c "import sys,re; print(re.sub(r'World', 'Python', sys.stdin.read().strip()))"
# Split and join
echo "a,b,c" | python -c "import sys; print('-'.join(sys.stdin.read().strip().split(',')))"
# Reverse string
python -c "print('hello'[::-1])"
# Capitalize words
echo "hello world" | python -c "import sys; print(sys.stdin.read().strip().title())"
# Remove whitespace
echo " spaced " | python -c "import sys; print(repr(sys.stdin.read().strip()))"
# Count occurrences
echo "banana" | python -c "import sys; print(sys.stdin.read().strip().count('a'))"
Math and Numbers
# Calculator
python -c "print(2**10)"
python -c "print(100/7)"
python -c "print(round(100/7, 2))"
# Hex/binary conversion
python -c "print(hex(255))" # 0xff
python -c "print(bin(255))" # 0b11111111
python -c "print(int('ff', 16))" # 255
python -c "print(int('11111111', 2))" # 255
# IP address math
python -c "import ipaddress; print(ipaddress.ip_network('10.50.1.0/24').num_addresses)"
python -c "import ipaddress; print(list(ipaddress.ip_network('10.50.1.0/30').hosts()))"
# Subnet calculations
python -c "import ipaddress; n=ipaddress.ip_network('10.50.1.0/24'); print(f'Network: {n.network_address}, Broadcast: {n.broadcast_address}')"
# Check if IP in network
python -c "import ipaddress; print(ipaddress.ip_address('10.50.1.50') in ipaddress.ip_network('10.50.1.0/24'))"
# Statistics
python -c "import statistics; print(statistics.mean([1,2,3,4,5]))"
python -c "import statistics; print(statistics.stdev([1,2,3,4,5]))"
System Information
# Platform info
python -c "import platform; print(platform.system(), platform.release())"
# Python version
python -c "import sys; print(sys.version)"
# Current working directory
python -c "import os; print(os.getcwd())"
# Environment variable
python -c "import os; print(os.environ.get('HOME', 'not set'))"
# List directory
python -c "import os; print(os.listdir('.'))"
# File size
python -c "import os; print(os.path.getsize('file.txt'))"
# Check if file exists
python -c "import os; print(os.path.exists('/etc/passwd'))"
# Get user info
python -c "import os,pwd; print(pwd.getpwuid(os.getuid()).pw_name)"
Infrastructure Patterns
# Parse ISE API response
curl -sk https://ise-01/api/v1/sessions | python -c "
import sys,json
data = json.load(sys.stdin)
for s in data.get('response', []):
print(f\"{s['macAddress']} - {s['userName']} - {s['nasIpAddress']}\")
"
# Extract Vault token expiry
curl -sk -H "X-Vault-Token: $VAULT_TOKEN" $VAULT_ADDR/v1/auth/token/lookup-self | python -c "
import sys,json
from datetime import datetime, timedelta
data = json.load(sys.stdin)['data']
ttl = data['ttl']
print(f'Expires in: {ttl//3600}h {(ttl%3600)//60}m')
"
# Parse k8s JSON
kubectl get pods -o json | python -c "
import sys,json
pods = json.load(sys.stdin)['items']
for p in pods:
name = p['metadata']['name']
phase = p['status']['phase']
print(f'{name}: {phase}')
"
# DNS lookup
python -c "import socket; print(socket.gethostbyname('vault-01.inside.domusdigitalis.dev'))"
# Reverse DNS
python -c "import socket; print(socket.gethostbyaddr('10.50.1.60'))"
# Port check
python -c "import socket; s=socket.socket(); s.settimeout(2); print('open' if s.connect_ex(('10.50.1.60', 8200))==0 else 'closed'); s.close()"
Click/Typer CLI Patterns
#!/usr/bin/env python3
"""Quick CLI with Typer (netapi pattern)"""
import typer
from typing import Optional
app = typer.Typer()
@app.command()
def show(
name: str = typer.Argument(..., help="Item name"),
format: str = typer.Option("table", "-f", "--format", help="Output format"),
verbose: bool = typer.Option(False, "-v", "--verbose"),
):
"""Show an item."""
if verbose:
typer.echo(f"Fetching {name} in {format} format...")
typer.echo(f"Result for: {name}")
@app.command()
def list(
filter: Optional[str] = typer.Option(None, "-F", "--filter"),
limit: int = typer.Option(10, "-l", "--limit"),
):
"""List items."""
typer.echo(f"Listing {limit} items" + (f" matching {filter}" if filter else ""))
if __name__ == "__main__":
app()
# Usage
./cli.py show myitem -f json -v
./cli.py list --filter "active" --limit 20
Common Gotchas
# WRONG: Forgetting quotes around Python code
python -c import json # Fails
# CORRECT: Quote the code
python -c "import json; print(json.dumps({}))"
# WRONG: Shell expansion in Python string
python -c "print('$HOME')" # Prints literal $HOME
# CORRECT: Use double quotes for shell expansion
python -c "import os; print(os.environ['HOME'])"
# WRONG: Newlines in -c
python -c "
import json # Works in some shells but not all
"
# CORRECT: Use semicolons or here-doc
python -c "import json; import sys; print(json.load(sys.stdin))"
# Or use here-doc for complex scripts
python << 'EOF'
import json
import sys
data = json.load(sys.stdin)
print(data)
EOF
# WRONG: Mixing Python 2/3 syntax
python -c "print 'hello'" # Python 2
# CORRECT: Python 3 syntax
python -c "print('hello')"