Maintenance

Site is under maintenance — quizzes are still available.

Go to quizzes
Reference library

Automation & scripting

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

55 matches
Automation & scripting medium

Find Orphan Files Not Referenced Anywhere in Python

Scan a project directory for files whose names never appear in the content of other files, identifying potentially unused resources.

orphan files file cleanup automation
Python
import os
from pathlib import Path
import re

def find_orphan_files(root_dir: str, extensions: set = None, ignore_patterns: list = None):
    """Find files not referenced by any other file in the project."""
    if extensions is None:
        extensions = {'.txt', '.md', '.py', '.html', '.css', '.js', '.json', '.yaml'…
22 0 Open
Automation & scripting medium

Find Sensitive Information in Log Files with Python

Scan log files for emails, IP addresses, API keys, and passwords using regular expressions in Python.

regex security log-analysis
Python
import re
import os
from pathlib import Path

def find_sensitive_info(log_path):
    """Scans log files for patterns like emails, IPs, API keys, and passwords."""
    patterns = {
        'Email': r'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}',
        'IP Address': r'\b(?:\d{1,3}\.){3}\d{1,3}\b',
        'API Key'…
18 0 Open
Automation & scripting medium

Find Unused Python Packages Automatically

Scan a Python project's source files for imports and list installed packages not imported anywhere.

unused-packages static-analysis ast
Python
import pkg_resources
import ast
import os
import sys
from pathlib import Path

def find_imports_in_project(project_dir="."):
    imports = set()
    for py_file in Path(project_dir).rglob("*.py"):
        try:
            with open(py_file, "r") as f:
                tree = ast.parse(f.read())
            for node in …
21 0 Open
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…
21 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…
31 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:
      …
22 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…
16 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…
18 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-…
19 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)
     …
24 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…
25 0 Open
Automation & scripting medium

How to Compare Two GitHub Repositories and Highlight Differences in Python

Fetch metadata from two GitHub repositories using the GitHub API and compare key attributes like stars, forks, license, and language, printing any differences.

github-api api comparison
Python
import requests
import json
from pathlib import Path

def fetch_repo_data(owner, repo_name):
    """Fetch repository metadata from GitHub API."""
    url = f"https://api.github.com/repos/{owner}/{repo_name}"
    response = requests.get(url)
    response.raise_for_status()
    return response.json()

def compare_repos(…
19 0 Open
Automation & scripting medium

How to Create a Link Graph Visualization for Any Website in Python

A Python script that crawls a website's internal links, builds a directed graph of parent-child URL relationships, and prints the graph to the console.

crawler graph visualization
Python
import requests
from bs4 import BeautifulSoup
from collections import defaultdict
from urllib.parse import urljoin, urlparse
import sys

def get_links(url, max_links=20):
    try:
        response = requests.get(url, timeout=5)
        soup = BeautifulSoup(response.text, 'html.parser')
        base_url = f"{urlparse(u…
22 0 Open
Automation & scripting medium

How to Detect Applications Consuming Excessive Memory in Python

Use psutil to list the top memory-using processes by RSS and print their names, PIDs, and memory usage in MB.

psutil memory monitoring
Python
import psutil

def find_top_memory_processes(limit=5):
    """Return top `limit` processes by memory usage (RSS)."""
    processes = []

    for proc in psutil.process_iter(['pid', 'name', 'memory_info']):
        try:
            info = proc.info
            mem = info['memory_info'].rss if info['memory_info'] else 0…
17 0 Open
Automation & scripting medium

How to Detect Network Interface Changes in Python

Monitor active network interfaces and print a message when an interface is added or removed using psutil and socket.

network monitoring psutil
Python
import socket
import psutil
import time

def get_network_interfaces():
    """Return a set of currently active interface names."""
    active_ifaces = set()
    for iface, addrs in psutil.net_if_addrs().items():
        for addr in addrs:
            if addr.family == socket.AF_INET:  # IPv4 address present
          …
24 0 Open
Automation & scripting medium

How to Detect Recently Installed Software in Python

Uses subprocess to call pip and parse package metadata to list recently installed Python packages.

pip subprocess automation
Python
import subprocess
import sys
from datetime import datetime, timedelta

def detect_recently_installed(days=7):
    """Detect recently installed software packages."""
    recent_packages = []
    cutoff_date = datetime.now() - timedelta(days=days)
    
    try:
        # For pip-installed packages (Python packages)
    …
17 0 Open
Automation & scripting medium

How to Detect Unused Images in a Project with Python

A Python script that scans a website project folder, identifies all image files, and checks HTML/CSS/JS files to find which images are never referenced.

automation files regex
Python
import os
import re
from pathlib import Path

def find_unused_images(project_path):
    image_exts = {'.png', '.jpg', '.jpeg', '.gif', '.svg', '.webp'}
    used_images = set()
    all_images = set()
    
    # Find all image files
    for root, _, files in os.walk(project_path):
        for file in files:
            …
20 0 Open
Automation & scripting medium

How to Download All Assets from GitHub Releases in Python

Downloads every asset attached to the latest GitHub release of a repository, saving them locally using the GitHub API and Python's requests and pathlib libraries.

github api downloading
Python
import requests
import os
import zipfile
from pathlib import Path

def download_github_release_assets(owner: str, repo: str, output_dir: str = "release_assets") -> None:
    """Downloads all assets from the latest release of a GitHub repository."""
    releases_url = f"https://api.github.com/repos/{owner}/{repo}/relea…
19 0 Open
Automation & scripting medium

How to Download a GitHub Repository as a ZIP File in Python

Download any public GitHub repository as a ZIP file using the GitHub API and Python's requests and zipfile modules.

github download zip
Python
import requests
import zipfile
import io
import os

def download_github_repo_as_zip(repo_url, output_path='.'):
    """
    Download a GitHub repository as a ZIP file.
    
    Args:
        repo_url (str): Full GitHub repository URL (e.g., 'https://github.com/username/repo')
        output_path (str): Directory to sa…
17 0 Open
Automation & scripting medium

How to Generate Project Statistics Including Lines of Code and Complexity in Python

Walk through a Python script that scans a project directory for Python files, counts lines of code excluding blanks and comments, and estimates cyclomatic complexity by counting decision keywords.

code metrics lines of code cyclomatic complexity
Python
import os
from pathlib import Path

def count_lines_of_code(filepath):
    """Counts lines of code in a Python file, excluding blank lines and comments."""
    try:
        with open(filepath, 'r') as f:
            lines = f.readlines()
        code_lines = [line for line in lines if line.strip() and not line.strip()…
22 0 Open
Automation & scripting medium

How to Generate a Dependency Graph for Python Projects

This script walks through a Python project directory, parses each .py file's imports, and prints a dependency graph showing which modules depend on which other modules.

ast dependency graph import parsing
Python
import os
import ast
from pathlib import Path
from collections import defaultdict

def get_imports(filepath):
    with open(filepath) as f:
        try:
            tree = ast.parse(f.read())
        except SyntaxError:
            return []
    imports = []
    for node in ast.walk(tree):
        if isinstance(node, …
19 0 Open
Automation & scripting medium

How to Monitor Laptop Battery Health Over Time in Python

Log battery percentage, power status, and remaining time every N seconds to a JSON file using psutil for ongoing health monitoring.

psutil battery monitoring
Python
import time
import json
from pathlib import Path
from datetime import datetime

try:
    import psutil
except ImportError:
    print("psutil required: pip install psutil")
    exit(1)

LOG_FILE = Path("battery_health_log.json")

def monitor_battery(log_interval=60, duration=300):
    """Log battery percentage and rema…
17 0 Open
Automation & scripting medium

How to Monitor USB Device Connections in Python

A Python utility that monitors USB device connections and disconnections by comparing output of the lsusb command at regular intervals.

usb monitoring subprocess
Python
import time
import subprocess
import os

def get_usb_devices():
    """Return list of currently connected USB devices (Linux)."""
    try:
        result = subprocess.run(['lsusb'], capture_output=True, text=True, check=True)
        return result.stdout.strip().split('\n')
    except (subprocess.CalledProcessError, F…
23 0 Open
Automation & scripting medium

How to Monitor Website Content Changes in Python

This script fetches a webpage's content, computes its SHA-256 hash, and compares it with the last stored hash to detect and alert on changes.

web scraping monitoring requests
Python
import time
import hashlib
import requests
from pathlib import Path

def fetch_content_hash(url: str) -> str:
    response = requests.get(url, timeout=10)
    response.raise_for_status()
    return hashlib.sha256(response.text.encode()).hexdigest()

def monitor_website(url: str, check_interval: int = 60):
    hash_fil…
28 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.