Reference library

Automation & scripting

CLI tools, scheduled jobs, filesystem tasks, and glue scripts that save time.

14 matches
Automation & scripting easy

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.

watermark bytes zlib
Python
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…
13 0 Open
Automation & scripting easy

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.

testing random data-generation
Python
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 = …
39 0 Open
Automation & scripting easy

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.

api dev.to markdown
Python
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": …
10 0 Open
Automation & scripting easy

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.

subprocess mocking ffmpeg
Python
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…
13 0 Open
Automation & scripting easy

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.

subprocess unittest.mock vagrant
Python
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…
14 0 Open
Automation & scripting medium

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.

smtplib email aiosmtpd
Python
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…
12 0 Open
Automation & scripting easy

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.

traceroute simulation network
Python
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…
15 0 Open
Automation & scripting easy

How to Strip EXIF Metadata from Images in Python

Remove EXIF metadata from image bytes using Pillow, with a mock JPEG generator for testing.

exif images metadata
Python
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…
13 0 Open
Automation & scripting easy

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.

certbot letsencrypt automation
Python
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…
16 0 Open
Automation & scripting easy

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.

mock helm testing
Python
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…
13 0 Open
Automation & scripting easy

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.

systemctl mock automation
Python
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 …
14 0 Open
Automation & scripting medium

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.

iso loop-device mock
Python
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")
      …
14 0 Open
Automation & scripting easy

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).

pytest subprocess email
Python
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…
12 0 Open
Automation & scripting easy

Toggle VPN Mock Network Manager Script in Python

Simulate a VPN manager with connect, disconnect, toggle, and status methods for testing or demo workflows.

vpn simulation automation
Python
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…
11 0 Open

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.