Reference library

Automation & scripting

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

9 matches
Automation & scripting easy

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.

automation tweeting blog
Python
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",
    …
16 0 Open
Automation & scripting easy

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.

weather-api dashboard html
Python
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…
14 0 Open
Automation & scripting easy

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.

pdf forms json
Python
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…
10 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 = …
38 0 Open
Automation & scripting easy

How to Filter Docker Containers for Pruning in Python

Simulate Docker's container prune by filtering a JSON list for exited containers older than a cutoff, returning pruned IDs and space freed.

docker json datetime
Python
import json
from datetime import datetime, timedelta


def parse_docker_ps(json_output: str, older_than_hours: int = 24) -> list:
    containers = json.loads(json_output)
    cutoff = datetime.now() - timedelta(hours=older_than_hours)
    return [
        c for c in containers
        if datetime.fromisoformat(c["crea…
13 0 Open
Automation & scripting easy

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.

cloud-init automation dataclasses
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,
    …
14 0 Open
Automation & scripting easy

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.

ansible inventory automation
Python
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…
12 0 Open
Automation & scripting easy

How to Save a VM Snapshot State to a JSON File in Python

Define a dataclass for a VM snapshot and serialize it to a JSON file, then reload it to verify the state.

json dataclass files
Python
import json
from dataclasses import dataclass, asdict
from pathlib import Path


@dataclass
class VMSnapshot:
    name: str
    memory_mb: int
    disk_gb: int
    state: str = "saved"

    def snapshot_to_file(self, path: Path) -> str:
        """Write snapshot state to a JSON file and return the filename."""
       …
13 0 Open
Automation & scripting easy

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.

disk partition dataclass
Python
#!/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": …
16 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.