Automation & scripting
CLI tools, scheduled jobs, filesystem tasks, and glue scripts that save time.
Automate Tweeting New Blog Posts in Python
A mock script that fetches new blog posts from a CMS and tweets them via a simulated Twitter API, outputting JSON results.
import json
import time
from datetime import datetime
def fetch_new_blog_posts():
"""Mock function to simulate fetching latest blog posts from a CMS."""
return [
{
"id": 1,
"title": "Getting Started with Python",
"url": "https://blog.example.com/python-start",
…
Benchmark Disk Write Speed in Python with tempfile
Benchmark raw disk write performance by writing a temporary file in 1MB chunks and measuring throughput in MB/s.
import os
import tempfile
import time
def benchmark_write(size_mb=50):
size_bytes = size_mb * 1024 * 1024
chunk = b'x' * 1024 * 1024 # 1 MB chunk
with tempfile.NamedTemporaryFile(delete=True) as tmp:
start = time.perf_counter()
written = 0
while written < size_bytes:
…
Fill PDF Form Fields from a Mock Template in Python
Fills a PDF-style form template dictionary with user data, preserving template fields and formatting output as JSON.
import json
template = {
"first_name": "",
"last_name": "",
"email": "",
"phone": "",
"date_of_birth": "",
"address": "",
"city": "",
"state": "",
"zip_code": "",
"agree_to_terms": False
}
def fill_pdf_form(template: dict, data: dict) -> dict:
for key, value in data.items…
How to Build a CLI with argparse in Python
Create a beginner-friendly command-line tool in Python that processes multiple filenames with optional flags for verbose output and uppercase conversion.
import argparse
def main():
parser = argparse.ArgumentParser(
description="A simple CLI to process files with optional verbose mode."
)
parser.add_argument("filenames", nargs="+", help="Files to process")
parser.add_argument("-v", "--verbose", action="store_true", help="Print extra details")
…
How to Build a Simple Python CLI with argparse
Create a friendly command-line greeting tool with argparse that accepts a positional name and optional flags for custom greetings and uppercase output.
import argparse
def greet(name, greeting="Hello", uppercase=False):
message = f"{greeting}, {name}!"
return message.upper() if uppercase else message
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="A simple greeting tool to demonstrate argparse basics."
)
parser.…
How to Build a Simple argparse CLI in Python
Build a beginner-friendly command-line tool with argparse that greets a user, with optional greeting text and uppercase output.
import argparse
def greet(name, greeting="Hello", uppercase=False):
message = f"{greeting}, {name}!"
if uppercase:
message = message.upper()
return message
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Simple CLI greeting tool")
parser.add_argument("name", help=…
How to Build an argparse Command-Line Tool in Python
Create a simple file-info CLI with argparse that counts lines and prints file size, with optional verbose and output flags.
import argparse
import os
from pathlib import Path
def process_file(filepath, verbose=False):
"""Read a file and report its size and line count."""
path = Path(filepath)
if not path.exists():
raise FileNotFoundError(f"File not found: {filepath}")
content = path.read_text()
lines = conten…
How to Create a Mock Headless Browser Screenshot Stub in Python
This code provides a deterministic stub that simulates capturing webpage screenshots with a headless browser, returning formatted output without real browser dependencies.
import subprocess
import sys
def mock_screenshot_webpage(url: str, width: int = 1280, height: int = 800) -> str:
"""Stub that simulates taking a screenshot of a webpage using headless browser."""
# In real implementation, you would use playwright/selenium/headless chrome
result = {
"url": url,
…
How to Mock a Whisper API Transcription Stub in Python
Simulate an OpenAI Whisper-style transcription response with a dataclass request model and a mock function that returns structured audio transcription output.
import json
from dataclasses import dataclass
from typing import Optional
@dataclass
class AudioRequest:
file_path: str
language: Optional[str] = None
def to_api_payload(self) -> dict:
return {"file": self.file_path, "language": self.language}
def mock_whisper_transcribe(payload: dict) -> dict:
…
How to Mock subprocess Calls in Python with unittest.mock
A Python script that wraps Vagrant up/destroy commands using subprocess, with tests that mock the subprocess call to simulate outputs and errors.
import subprocess
from unittest.mock import patch, Mock
def run_vagrant(action: str) -> str:
result = subprocess.run(
["vagrant", action],
capture_output=True,
text=True,
check=False,
)
return result.stdout.strip()
def vagrant_wrapper(action: str) -> str:
if action n…
How to Parse Terraform Plan Output in Python
Parse mock Terraform plan output text into structured add, change, and destroy lists using Python.
import json
from typing import Dict, List
def parse_terraform_plan_output(plan_output_text: str) -> Dict[str, List[str]]:
"""
Parses a mock Terraform plan output text into a structured dictionary.
"""
parsed: Dict[str, List[str]] = {"add": [], "change": [], "destroy": []}
for line in plan_output_…
How to Watch a Folder and Convert New Images in Python
Watch a folder for new files and mock-convert images by copying and renaming them in an output directory.
import time
import hashlib
from pathlib import Path
from datetime import datetime
def mock_convert_image(source: Path, dest_dir: Path) -> Path:
"""Mock image conversion: copy bytes and add .converted suffix."""
dest = dest_dir / f"{source.stem}.converted{source.suffix}"
dest.write_bytes(source.read_bytes(…
Mock Certbot Renewal in Python for Testing
Simulates a Let's Encrypt certificate renewal by writing a mock certificate file and printing realistic certbot CLI output, without calling the actual certbot.
import subprocess
import sys
from datetime import datetime, timedelta
from pathlib import Path
def renew_cert(domain: str, output_dir: str = "certs") -> str:
"""Simulate a Let's Encrypt renewal with mock certbot output."""
out = Path(output_dir)
out.mkdir(parents=True, exist_ok=True)
cert_path = out…
Parse WHOIS Data with Python Regex
Extract domain registration fields from a mock WHOIS record using regex and compute days until expiration.
import re
from datetime import datetime
def parse_whois(whois_text: str) -> dict:
"""Extract key registration fields from a mock WHOIS record."""
patterns = {
"domain": r"Domain Name:\s*(.+)",
"registrar": r"Registrar:\s*(.+)",
"creation_date": r"Creation Date:\s*(.+)",
"expir…
Parse cron expression and compute next run datetime in Python
Parse a 5-field cron expression and compute the next matching datetime starting from a given base time.
from datetime import datetime, timedelta
import re
def parse_cron_and_next_run(cron_expr, base_time=None):
"""Parse a cron expression and compute the next run time."""
if base_time is None:
base_time = datetime.now().replace(second=0, microsecond=0)
fields = cron_expr.split()
if len(fields) !…
Resize Disk Partitions in Python (Mock Script)
A mock disk partition resize script that uses dataclasses to model partitions, validate new sizes, and output the updated layout as JSON.
#!/usr/bin/env python3
"""Mock script to demonstrate disk partition resize logic."""
import json
from dataclasses import dataclass
from typing import Dict
@dataclass
class Partition:
name: str
size_gb: int
mount_point: str
def to_dict(self) -> Dict[str, object]:
return {
"name": …
Stress CPU Threads with a Mock Compute in Python
Simulates CPU-intensive work across multiple threads to test how Python schedules parallel compute.
import threading
import time
def stress_cpu(iterations: int):
result = 0
for i in range(iterations):
result += i * i % 1000
return result
def run_mock_stress(thread_count: int, iterations: int):
threads = []
for tid in range(thread_count):
t = threading.Thread(target=lambda: str…
Browse by section
Each section groups closely related Python snippets.
Automation & scripting — Python code examples
What you will find here
This page collects automation & scripting snippets — short, copy-ready Python you can paste into our free online IDE and run without installing anything. Each sample includes a plain-English explanation and the full source code.
Samples vs tutorials and challenges
Samples are quick reference — one concept per page. For step-by-step teaching, use our Python tutorials. To test yourself, try quizzes or coding challenges. Clean up style with the Python formatter.