Reference library

Automation & scripting

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

20 matches
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

Build an M3U Playlist from Folder MP3s in Python

Scans a folder for MP3 files and writes a valid M3U playlist with absolute file URIs.

m3u playlist pathlib
Python
from pathlib import Path
import sys


def build_playlist(folder: str, output: str = "playlist.m3u") -> str:
    folder_path = Path(folder)
    if not folder_path.is_dir():
        raise FileNotFoundError(f"Folder not found: {folder}")

    mp3_files = sorted(folder_path.glob("*.mp3"))
    if not mp3_files:
        pri…
17 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

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

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

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 Docker Image Tag Script in Python

Generate consistent Docker image tags from service names and versions with automatic normalization.

docker scripting cli
Python
#!/usr/bin/env python3
"""Mock script for building docker image tags."""


def build_tag(service_name: str, version: str, registry: str = "docker.io") -> str:
    """Construct a docker image tag."""
    safe_name = service_name.lower().replace("_", "-")
    return f"{registry}/{safe_name}:{version}"


if __name__ == "…
12 0 Open
Automation & scripting easy

How to Build a Python argparse CLI for Beginners

Build a beginner-friendly command-line interface using Python's argparse module with positional and optional arguments.

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

def main():
    parser = argparse.ArgumentParser(description="A simple CLI greet tool for beginners.")
    parser.add_argument("name", help="…
15 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
Automation & scripting easy

How to Build an argparse Command-Line Tool in Python

Create a simple file-info CLI with argparse that counts lines and prints file size, with optional verbose and output flags.

argparse cli command-line
Python
import argparse
import os
from pathlib import Path


def process_file(filepath, verbose=False):
    """Read a file and report its size and line count."""
    path = Path(filepath)
    if not path.exists():
        raise FileNotFoundError(f"File not found: {filepath}")

    content = path.read_text()
    lines = conten…
14 0 Open
Automation & scripting easy

How to Create a Simple Python CLI with argparse

Build a beginner-friendly command-line tool with argparse that accepts positional and optional arguments to greet users flexibly.

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

def main():
    parser = argparse.ArgumentParser(
        description="A simple CLI tool that greets users."
    )
    parser.add_argument(
        "name",
   …
15 0 Open
Automation & scripting easy

How to Deploy a Static Site Build to an Nginx Directory in Python

Copy a static site build directory into an Nginx web root using Python's shutil and pathlib modules.

automation deployment shutil
Python
import shutil
import os
from pathlib import Path

SRC_DIR = Path("build")
DEST_DIR = Path("/var/www/html")

def deploy_site(src: Path, dest: Path) -> None:
    if not src.exists():
        raise FileNotFoundError(f"Build directory not found: {src}")

    dest.mkdir(parents=True, exist_ok=True)

    for item in src.ite…
16 0 Open
Automation & scripting easy

How to Implement argparse CLI Command in Python

Build a beginner-friendly command-line tool with argparse that accepts positional and optional arguments, flags, and prints a customizable greeting.

argparse cli command-line
Python
import argparse


def main():
    parser = argparse.ArgumentParser(description="A simple CLI tool to greet users.")
    parser.add_argument("name", help="Your name")
    parser.add_argument("-g", "--greeting", default="Hello", help="Greeting word (default: Hello)")
    parser.add_argument("--uppercase", action="store_…
15 0 Open
Automation & scripting easy

How to Parse CLI Arguments in Python with argparse

Build a beginner-friendly CLI with argparse that accepts optional --name, --greeting, and --uppercase flags, then prints a customizable greeting.

argparse cli command-line
Python
import argparse

def main():
    parser = argparse.ArgumentParser(description="Greet a user with optional customization.")
    parser.add_argument("--name", default="world", help="Name to greet")
    parser.add_argument("--greeting", default="Hello", help="Greeting word")
    parser.add_argument("--uppercase", action=…
14 0 Open
Automation & scripting easy

How to Sort Command-Line Arguments in Python

Build a beginner-friendly argparse CLI that sorts numbers or words passed as arguments, with an optional reverse flag.

argparse cli sorting
Python
import argparse


def main():
    parser = argparse.ArgumentParser(description="Sort numbers or words from the command line.")
    parser.add_argument("items", nargs="+", help="Items to sort (numbers or words)")
    parser.add_argument("--reverse", "-r", action="store_true", help="Sort in descending order")
    args =…
13 0 Open
Automation & scripting easy

How to validate argparse CLI commands in Python

Build a beginner-friendly command-line argument parser with argparse, including required and optional arguments, plus simple validation for age.

argparse cli validation
Python
import argparse


def main():
    parser = argparse.ArgumentParser(description="Validate CLI arguments for beginners.")
    parser.add_argument("name", type=str, help="Your name.")
    parser.add_argument("--age", type=int, default=None, help="Your age (optional).")
    parser.add_argument("--verbose", action="store_t…
13 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.