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",
…
Create Mock Watermarked Image Bytes in Python Without PIL
Builds a mock image-like byte stream with an embedded watermark using only stdlib modules, for testing pipelines without PIL.
from io import BytesIO
import zlib
import struct
def create_watermarked_bytes(width: int, height: int, watermark: bytes) -> bytes:
"""Create a mock image-like byte stream with a watermark (no PIL)."""
header = struct.pack("<2I", width, height)
payload = watermark * max(1, (width * height // max(1, len(wa…
Fetch weather API mock and write dashboard HTML in Python
This script fetches a mock weather API response as a Python dict, builds a simple HTML dashboard, writes it to a file, and prints both the file path and JSON payload.
from datetime import datetime
import json
import os
def fetch_weather_mock(city: str) -> dict:
"""Return a mock weather payload for a given city."""
return {
"city": city,
"temperature_c": 21.5,
"condition": "Partly Cloudy",
"humidity": 58,
"wind_kph": 12.3,
"u…
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 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 Cross Post Markdown to dev.to API in Python
A Python function that POSTs markdown content to the dev.to API and handles HTTP or URLError exceptions with mock API testing.
import json
from urllib import request, error
def cross_post_to_devto(markdown_content, api_key, devto_api_url="https://dev.to/api/articles"):
"""
Mock cross-posting of markdown content to the dev.to API.
Returns the API response or an error message.
"""
payload = json.dumps({
"article": …
How to Generate a cloud-init User Data Mock in Python
Generate a cloud-init user data mock for a VM using a dataclass and JSON in Python.
import json
from dataclasses import dataclass, asdict
@dataclass
class VMConfig:
hostname: str
cpus: int
memory_mb: int
ssh_key: str
def generate_cloud_init_mock(config: VMConfig) -> str:
"""Build a cloud-init user-data mock for a VM."""
user_data = {
"hostname": config.hostname,
…
How to Map Network Drive Paths to Local Paths in Python
Convert mock SMB network drive paths (like 'S:\reports\q1.xlsx') to local placeholder paths and back using a simple mapping dictionary in Python.
"""Map mock SMB network drive paths to local placeholder paths."""
from dataclasses import dataclass
@dataclass(frozen=True)
class NetworkDrive:
letter: str
remote_path: str
DRIVES = {
"S:": NetworkDrive("S", r"\\server01\shares\sales"),
"M:": NetworkDrive("M", r"\\server02\media\movies"),
"X:": …
How to Merge PDFs in Python (Mock pypdf Stub)
Merge PDF files by concatenating their raw byte content using a simple stubbed class that mimics the pypdf interface.
import io
from hashlib import sha256
class PdfStub:
def __init__(self, data: bytes, name: str):
self.data = data
self.name = name
def get_content_bytes(self) -> bytes:
return self.data
def merge_pdfs_mock(pdf_stubs) -> bytes:
merged = io.BytesIO()
for stub in pdf_stubs:
…
How to Mock FFmpeg subprocess Calls in Python
Compress a video with ffmpeg while mocking subprocess.run to test the command construction without executing the actual encoder.
import subprocess
from unittest.mock import Mock, patch
def compress_video(input_path: str, output_path: str, crf: int = 23) -> None:
"""Compress a video using ffmpeg with a given CRF (quality) value."""
command = [
"ffmpeg",
"-i", input_path,
"-c:v", "libx264",
"-crf", str(cr…
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 an Ansible Inventory in Python
Load an Ansible-style inventory JSON file into Python and simulate a playbook run across hosts and groups.
import json
from pathlib import Path
class InventoryMock:
def __init__(self, inventory_file: str):
self.inventory_file = Path(inventory_file)
self.hosts = {}
def load(self):
if not self.inventory_file.exists():
raise FileNotFoundError(f"Inventory file {self.inventory_file…
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 Simulate a Traceroute in Python
This Python script simulates a network traceroute by generating mock hop IPs, random delays, and a destination reach condition, useful for testing network scripts.
import random
import time
def simulate_traceroute(destination, max_hops=30):
"""Simulate a traceroute to a destination with mock hop delays."""
print(f"Traceroute to {destination} ({max_hops} hops max):")
for hop in range(1, max_hops + 1):
# Mock IP address for the hop
mock_ip = f"10.0.{ra…
How to Strip EXIF Metadata from Images in Python
Remove EXIF metadata from image bytes using Pillow, with a mock JPEG generator for testing.
from PIL import Image
from PIL.ExifTags import TAGS
from io import BytesIO
import struct
def strip_exif(image_bytes, remove_metadata=True):
"""Remove EXIF metadata from image bytes."""
img = Image.open(BytesIO(image_bytes))
if remove_metadata:
# Clear all metadata
img.info.clear()
# Sa…
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(…
How to generate an htpasswd bcrypt entry in Python
Create a mock htpasswd file entry with a bcrypt-hashed password for a given username using a simple Python script.
import bcrypt
def mock_htpasswd_entry(username, password):
salt = bcrypt.gensalt(rounds=12)
hashed = bcrypt.hashpw(password.encode(), salt).decode()
return f"{username}:{hashed}"
if __name__ == "__main__":
entry = mock_htpasswd_entry("demo_user", "s3cretP@ss")
print(entry)
How to rename music files by ID3 tags in Python
Renames MP3 files in a folder using artist and title extracted from ID3 tags, with a mock fallback that parses filenames.
import os
import re
from pathlib import Path
def sanitize_filename(name: str) -> str:
return re.sub(r'[<>:"/\\|?*]', '_', name).strip()
def rename_mp3_from_id3(path: Path) -> None:
for f in path.glob("*.mp3"):
# Mock ID3 extraction: derive artist/title from filename
stem = f.stem
if "…
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…
Mock a Helm Upgrade Install Command in Python
Use unittest mock to simulate a Helm upgrade --install call for testing automation scripts without a real cluster.
from unittest.mock import MagicMock, patch
class HelmClient:
def upgrade_install(self, release, chart, namespace="default"):
# Simulates the helm upgrade --install command
return f"Release {release} upgraded/installed in {namespace} using chart {chart}"
@patch("helm_client.HelmClient.upgrade_in…
Mock systemctl Wrapper in Python for Service Testing
A Python class-based mock of systemctl that simulates start, stop, restart, and status operations for a service, useful for testing automation scripts.
import subprocess
import sys
class ServiceManager:
def __init__(self, service_name):
self.service_name = service_name
self.status = "inactive"
def start(self):
self.status = "active"
print(f"Starting {self.service_name}... OK")
def stop(self):
self.status …
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…
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": …
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.