Automation & scripting
CLI tools, scheduled jobs, filesystem tasks, and glue scripts that save time.
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…
Generate Random Fake User Data for Testing in Python
This code generates a list of fake user dictionaries with random names, emails, ages, and timestamps using the Python standard library for testing purposes.
import json
import random
import string
from datetime import datetime, timedelta
def generate_user_data(num_users=1):
first_names = ["Alice", "Bob", "Charlie", "Diana", "Eve"]
last_names = ["Smith", "Johnson", "Brown", "Taylor", "Wilson"]
domains = ["example.com", "test.org", "demo.net"]
users = …
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 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 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 Send an Email with smtplib and a Mock Server in Python
Send an email using smtplib and verify it with a local aiosmtpd mock SMTP server — perfect for testing without a real mail server.
import smtplib
from email.message import EmailMessage
import aiosmtpd.controller as controller
import threading
def handle_message(server, session, envelope):
print(f"Mock server received message:")
print(f"From: {envelope.mail_from}")
print(f"To: {envelope.rcpt_tos}")
print(f"Subject: {envelope.cont…
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…
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 …
Mount ISO Loop Device Mock Script in Python
Simulate ISO mounting with a loop device using a mock class — useful for testing scripts that depend on mount/unmount without actual system privileges.
import os
import tempfile
from dataclasses import dataclass
from pathlib import Path
@dataclass
class LoopDevice:
path: str
iso_path: str
mounted: bool = False
def mount(self, mount_point: str):
if self.mounted:
raise RuntimeError(f"Loop device {self.path} already mounted")
…
Run pytest and email summary in Python
Runs pytest via subprocess, extracts the test summary line, and sends it in an email (mocked for demonstration).
import smtplib
import subprocess
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
def run_tests():
"""Run pytest and capture the summary output."""
result = subprocess.run(
["pytest", "-q"],
capture_output=True,
text=True
)
return result.stdo…
Toggle VPN Mock Network Manager Script in Python
Simulate a VPN manager with connect, disconnect, toggle, and status methods for testing or demo workflows.
import time
class MockVPNManager:
def __init__(self):
self.is_connected = False
self.servers = ["us-west", "eu-central", "asia-east"]
self.active_server = None
def toggle(self):
if self.is_connected:
self.disconnect()
else:
self.connect()
d…
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.