Reference library

Automation & scripting

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

176 matches
Automation & scripting medium

Find Zombie Processes on Linux with Python

Parse the output of `ps -eo pid,stat,comm` to detect processes in zombie state (Z) on a Linux system and report their PIDs and commands.

linux process monitoring
Python
#!/usr/bin/env python3
import os
import subprocess

def find_zombie_processes():
    """Find zombie processes (state 'Z') running on Linux."""
    try:
        result = subprocess.run(['ps', '-eo', 'pid,stat,comm'], capture_output=True, text=True, check=True)
        zombies = []
        for line in result.stdout.stri…
37 0 Open
Automation & scripting medium

Find and Delete Duplicate Files Using Hashing in Python

Walk a directory tree, compute SHA256 hashes for every file, and delete duplicates that share the same hash.

deduplication files hashing
Python
import hashlib
import os
from pathlib import Path

def file_hash(path, block_size=65536):
    """Return SHA256 hash of file content."""
    hasher = hashlib.sha256()
    with open(path, 'rb') as f:
        while chunk := f.read(block_size):
            hasher.update(chunk)
    return hasher.hexdigest()

def find_and_d…
51 0 Open
Automation & scripting medium

Find the Largest Files Consuming Disk Space with a Beautiful Terminal Report in Python

Scan a directory recursively and print a formatted terminal report of the largest files, with human-readable sizes.

file-system disk-space pathlib
Python
import os
import sys
from pathlib import Path

def get_largest_files(directory: str, count: int = 10) -> list:
    """
    Scan the given directory and return the largest files.
    
    Args:
        directory: Path to the directory to scan
        count: Number of largest files to return
        
    Returns:
      …
44 0 Open
Automation & scripting medium

Generate Beautiful Project Documentation from Python Source Code Automatically

Automatically generate a markdown summary of function docstrings from any Python source file using the AST module.

ast automation documentation
Python
import ast
import inspect
from pathlib import Path

def extract_docstrings_from_file(filepath):
    """Parse a Python file and collect function docstrings."""
    source = Path(filepath).read_text()
    tree = ast.parse(source)

    docs = []
    for node in ast.walk(tree):
        if isinstance(node, (ast.FunctionDef…
34 0 Open
Automation & scripting medium

Generate Holiday Calendars for Different Countries in Python

Generate a sorted list of public holidays for a given country and year using Python's calendar and datetime modules.

calendar datetime holidays
Python
import calendar
from datetime import date, timedelta

def generate_holiday_calendar(country_code, year=2025):
    holidays = []
    
    if country_code == "US":
        # New Year's Day
        holidays.append(date(year, 1, 1))
        # Independence Day
        holidays.append(date(year, 7, 4))
        # Thanksgivin…
39 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

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 medium

Generate Strong SSH Keys and Save Them Securely with Python

Generate a 4096-bit RSA SSH key pair using Python's cryptography library and save both private and public keys with restricted file permissions.

ssh key-generation cryptography
Python
import os
import stat
from pathlib import Path
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.backends import default_backend

def generate_ssh_keypair(key_path: str = "id_rsa", passphrase: str = None):
    """Generate a 4096-…
36 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…
37 0 Open
Automation & scripting easy

How to Backup an SQLite Database with a Timestamp in Python

Backs up an SQLite database file to a timestamped copy using the sqlite3 backup API.

sqlite backup automation
Python
import sqlite3
import shutil
from datetime import datetime
from pathlib import Path

def backup_database(db_path: str, backup_dir: str = "backups") -> Path:
    db = Path(db_path)
    backup_folder = Path(backup_dir)
    backup_folder.mkdir(exist_ok=True)
    
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
 …
13 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 medium

How to Build a Cryptocurrency Price Tracker in Python

A continuous Python script that fetches real-time cryptocurrency prices from the CoinGecko API and displays them on a loop.

crypto api automation
Python
import requests
import time

def get_crypto_prices(coin_ids=["bitcoin", "ethereum", "solana"]):
    url = "https://api.coingecko.com/api/v3/simple/price"
    params = {
        "ids": ",".join(coin_ids),
        "vs_currencies": "usd"
    }
    try:
        response = requests.get(url, params=params, timeout=10)
     …
45 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 medium

How to Build a Mock Route53 DNS API in Python

Create a mock DNS API server in Python that simulates Route53 record lookups and updates using the standard library.

mock-server dns http-server
Python
import json
from http.server import BaseHTTPRequestHandler, HTTPServer
from urllib.parse import urlparse, parse_qs


class DNSUpdateHandler(BaseHTTPRequestHandler):
    records = {"example.com": "1.2.3.4"}

    def do_GET(self):
        domain = parse_qs(urlparse(self.path).query).get("domain", [""])[0]
        if dom…
13 0 Open
Automation & scripting medium

How to Build a Python Tool That Finds Trending Open Source Projects Daily

A Python script that queries the GitHub Search API to fetch the top 5 trending repositories created in the last day, sorted by stars, with optional language filtering.

github api trending
Python
import requests
import json
import datetime

def fetch_trending_projects(language: str = "", since: str = "daily"):
    url = "https://api.github.com/search/repositories"
    date_limit = (datetime.date.today() - datetime.timedelta(days=1)).isoformat()
    query = f"created:>{date_limit} language:{language}" if langua…
46 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

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.