Reference library

Automation & scripting

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

81 matches
Automation & scripting easy

Aggregate Log Errors Count by Hour in Python

Counts ERROR log lines per hour using regex and Counter, returning a sorted dictionary of hourly totals.

logs regex counter
Python
import re
from collections import Counter
from datetime import datetime

def aggregate_errors_by_hour(log_lines):
    pattern = re.compile(r'^(\d{4}-\d{2}-\d{2} \d{2}):\d{2}:\d{2}.*ERROR')
    hourly_counts = Counter()
    
    for line in log_lines:
        match = pattern.match(line)
        if match:
            ho…
21 0 Open
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

Automatically Generate Hardware Inventory Reports in Python

Generate a system hardware report including OS version, CPU cores, RAM, and disk usage using platform and psutil.

hardware inventory psutil
Python
import platform
import psutil  # requires: pip install psutil
from datetime import datetime

def generate_hardware_report():
    report_lines = []
    report_lines.append(f"Report Generated: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
    report_lines.append(f"System: {platform.system()} {platform.release()} ({pl…
55 0 Open
Automation & scripting easy

Batch Rename Hundreds of Files in Python

Rename all files with a given extension inside a folder using a sequential counter and a custom prefix.

automation files pathlib
Python
import os
from pathlib import Path

def batch_rename_files(directory: str, prefix: str, extension: str = ".txt") -> None:
    """Rename all files with given extension in directory to prefix_{counter}.ext."""
    path = Path(directory)
    if not path.is_dir():
        print(f"Directory '{directory}' does not exist.")
…
57 0 Open
Automation & scripting easy

Build a Command-Line Password Generator in Python

Generate cryptographically strong random passwords using Python's secrets module and print them for command-line use.

secrets password-generator automation
Python
import secrets
import string

def generate_password(length=16):
    """Generate a cryptographically strong random password."""
    alphabet = string.ascii_letters + string.digits + string.punctuation
    password = ''.join(secrets.choice(alphabet) for _ in range(length))
    return password

if __name__ == "__main__":…
48 0 Open
Automation & scripting easy

Build a Live Countdown Timer for Events in Python

A Python script that displays a real-time countdown to a target date and time, updating every second in the console.

datetime countdown timers
Python
import datetime
import time

def countdown(event_name, target_datetime):
    """Displays a live countdown to a target datetime."""
    while True:
        now = datetime.datetime.now()
        remaining = target_datetime - now
        if remaining.total_seconds() <= 0:
            print(f"\n🚀 {event_name} is happening…
46 0 Open
Automation & scripting easy

Bulk Rename Files in Python with Regex Replacement

Renames every file in a directory by applying a regex substitution to its filename using Python's stdlib re and pathlib.

automation regex pathlib
Python
import re
from pathlib import Path

def bulk_rename_regex(directory, pattern, replacement):
    path = Path(directory)
    renamed = []
    for file in path.iterdir():
        if file.is_file():
            new_name = re.sub(pattern, replacement, file.name)
            if new_name != file.name:
                new_pat…
17 0 Open
Automation & scripting easy

Check Service Ping Status and Exit Code in Python

Ping a list of hosts, print OK/FAIL per host, and exit with a non-zero code when any host is unreachable.

subprocess ping exit-code
Python
import subprocess
import sys

SERVICES = [
    "8.8.8.8",
    "1.1.1.1",
    "invalid-host",
]

def main():
    failed = []
    for host in SERVICES:
        result = subprocess.run(
            ["ping", "-c", "1", "-W", "2", host],
            stdout=subprocess.DEVNULL,
            stderr=subprocess.DEVNULL,
        …
16 0 Open
Automation & scripting easy

Convert Markdown to HTML in Python (Batch)

Convert every Markdown file in a directory to HTML with the Python markdown library, saving each result with an .html extension.

markdown html batch
Python
import markdown
from pathlib import Path


def convert_md_to_html(source_dir: str, dest_dir: str) -> list[str]:
    src = Path(source_dir)
    dst = Path(dest_dir)
    dst.mkdir(parents=True, exist_ok=True)

    converted_files = []
    for md_file in src.glob("*.md"):
        html_content = markdown.markdown(md_file.…
14 0 Open
Automation & scripting easy

Create ICS Calendar Invites in Python

This script generates a batch of calendar invites in the ICS format using the ics library.

ics calendar automation
Python
import ics
from datetime import datetime, timedelta

def create_invites(batch):
    calendar = ics.Calendar()
    for event_data in batch:
        event = ics.Event()
        event.name = event_data["name"]
        event.begin = event_data["start"]
        event.end = event_data["end"]
        event.description = even…
11 0 Open
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

Create a Simple HTTP File Server in Python

This code creates a simple HTTP file server that serves files from the current working directory on port 8000 using Python's built-in http.server module.

http server file-server
Python
import http.server
import socketserver
import os

PORT = 8000
DIRECTORY = os.getcwd()

class CustomHandler(http.server.SimpleHTTPRequestHandler):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, directory=DIRECTORY, **kwargs)

    def log_message(self, format, *args):
        print(f"[{self.log…
56 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 Strong Random Passwords with Custom Rules in Python

Build a configurable password generator using Python's secrets module that lets you toggle lowercase, uppercase, digits, and punctuation.

password secrets security
Python
import secrets
import string

def generate_password(length=16, use_lower=True, use_upper=True, use_digits=True, use_punct=True):
    pool = ''
    if use_lower:
        pool += string.ascii_lowercase
    if use_upper:
        pool += string.ascii_uppercase
    if use_digits:
        pool += string.digits
    if use_pu…
37 0 Open
Automation & scripting easy

Generate a Monthly Report CSV from Log Files in Python

Reads a CSV log file, filters events by a given month, aggregates daily event counts and revenue, and writes a summarized monthly report to a new CSV.

csv logs report
Python
import csv
from collections import defaultdict
from datetime import datetime

def generate_monthly_report(log_file: str, month: str, output_file: str) -> None:
    events_by_date = defaultdict(int)
    revenue_by_date = defaultdict(float)
    
    with open(log_file, 'r') as f:
        for line in f:
            date_…
14 0 Open
Automation & scripting easy

How to Auto Organize Downloads by File Extension in Python

A Python script that sorts files in a directory into subfolders based on their file extensions, creating folders automatically.

file-organization automation pathlib
Python
import os
import shutil
from pathlib import Path

def organize_downloads(download_dir="~/Downloads"):
    """Move files in a directory into subfolders based on file extension."""
    download_path = Path(download_dir).expanduser()
    
    if not download_path.exists():
        print(f"Directory not found: {download_p…
13 0 Open
Automation & scripting easy

How to Automatically Download Every Favicon from a List of Websites in Python

Download each website's favicon.ico file by constructing its URL, making a GET request, and saving the binary content locally.

web-scraping automation download
Python
import requests
from urllib.parse import urlparse
import os

websites = [
    "https://www.google.com",
    "https://www.github.com",
    "https://www.stackoverflow.com"
]

def download_favicon(url):
    parsed = urlparse(url)
    favicon_url = f"{parsed.scheme}://{parsed.netloc}/favicon.ico"
    response = requests.g…
38 0 Open
Automation & scripting easy

How to Batch Resize Images in Python with pathlib and Pillow

Batch resize all JPG images from a source folder and save to a destination folder using pathlib and Pillow.

pathlib pillow image-processing
Python
from pathlib import Path
from PIL import Image

def batch_resize_images(src_dir: str, dest_dir: str, size: tuple[int, int] = (800, 600)) -> None:
    src_path = Path(src_dir)
    dest_path = Path(dest_dir)
    dest_path.mkdir(parents=True, exist_ok=True)
    
    for img_path in src_path.glob("*.jpg"):
        if not …
12 0 Open
Automation & scripting easy

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.

argparse cli scripting
Python
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")
 …
11 0 Open
Automation & scripting easy

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.

argparse cli command-line
Python
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.…
11 0 Open
Automation & scripting easy

How to Build a Simple argparse CLI in Python

Create a beginner-friendly command-line tool with argparse that reads a file, optionally uppercases its lines, and prints a configurable number of lines.

argparse cli automation
Python
import argparse

def main():
    parser = argparse.ArgumentParser(
        description="Automate file processing with a simple CLI tool."
    )
    parser.add_argument("filename", help="Path to the input file")
    parser.add_argument("--uppercase", action="store_true", help="Convert text to uppercase")
    parser.add…
14 0 Open
Automation & scripting easy

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.

argparse cli command-line
Python
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=…
13 0 Open
Automation & scripting easy

How to Build an argparse CLI That Filters File Lines by Keyword in Python

This Python script is a command-line tool built with argparse that reads a text file and prints only the lines that contain (or don't contain) a given keyword.

argparse cli filter
Python
import argparse
import sys

def main():
    parser = argparse.ArgumentParser(description="Filter lines from a file by keyword.")
    parser.add_argument("input", type=str, help="File to read")
    parser.add_argument("keyword", type=str, help="Keyword to filter lines")
    parser.add_argument("--contains", action="sto…
14 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.