Automation & scripting
CLI tools, scheduled jobs, filesystem tasks, and glue scripts that save time.
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.
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 …
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.
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…
How to Create a File Organizer That Sorts Files Automatically in Python
A Python script that scans a given folder, categorizes files by extension (Images, Documents, Audio, Video, Archives, Misc), and moves them into subfolders automatically.
import os
import shutil
from pathlib import Path
FILE_CATEGORIES = {
"Images": [".jpg", ".jpeg", ".png", ".gif", ".bmp"],
"Documents": [".pdf", ".docx", ".txt", ".csv", ".xlsx"],
"Audio": [".mp3", ".wav", ".flac", ".aac"],
"Video": [".mp4", ".mkv", ".avi", ".mov"],
"Archives": [".zip", ".tar", ".g…
How to Detect Recently Installed Software in Python
Uses subprocess to call pip and parse package metadata to list recently installed Python packages.
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)
…
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.
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:
…
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.
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…
How to Generate an Inventory CSV of Installed pip Packages in Python
This script uses subprocess and csv to list all installed pip packages and write their names and versions into a CSV inventory file.
import subprocess
import csv
def get_installed_packages():
"""Return a list of (name, version) tuples for installed pip packages."""
result = subprocess.run(
["pip", "list", "--format=freeze"],
capture_output=True,
text=True,
check=True
)
packages = []
for line in r…
How to Implement a Weighted DNS Resolver with Failover in Python
Simulates a weighted DNS load balancer that distributes traffic across IPs by weight and automatically fails over when a server is marked unhealthy.
import random
import time
class WeightedDNSResolver:
def __init__(self, records):
self.records = records # list of (ip, weight)
self.total_weight = sum(weight for _, weight in records)
self.failed_ips = set()
def resolve(self):
available = [(ip, weight) for ip, weight in self…
How to Mock FFmpeg subprocess Calls in Python
Compress a video with ffmpeg while mocking subprocess.run to test the command construction without executing the actual encoder.
import subprocess
from unittest.mock import Mock, patch
def compress_video(input_path: str, output_path: str, crf: int = 23) -> None:
"""Compress a video using ffmpeg with a given CRF (quality) value."""
command = [
"ffmpeg",
"-i", input_path,
"-c:v", "libx264",
"-crf", str(cr…
How to Mock subprocess Calls in Python with unittest.mock
A Python script that wraps Vagrant up/destroy commands using subprocess, with tests that mock the subprocess call to simulate outputs and errors.
import subprocess
from unittest.mock import patch, Mock
def run_vagrant(action: str) -> str:
result = subprocess.run(
["vagrant", action],
capture_output=True,
text=True,
check=False,
)
return result.stdout.strip()
def vagrant_wrapper(action: str) -> str:
if action n…
How to Ping Multiple Hosts in Parallel with Python ThreadPoolExecutor
A parallel host-pinging script using ThreadPoolExecutor and subprocess to check connectivity across multiple addresses concurrently.
import subprocess
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
HOSTS = [
"google.com",
"github.com",
"stackoverflow.com",
"nonexistent.invalid",
"localhost",
]
def ping_host(host: str) -> str:
"""Ping a single host and return a status string."""
result = subp…
How to Recover Deleted .txt Files from a Backup in Python
A Python function that searches a backup directory recursively and copies all .txt files to a destination folder, printing each recovered file name and a total count.
import os
import shutil
from pathlib import Path
def recover_deleted_txt_files(source_backup_dir: str, destination_dir: str) -> None:
"""Recover .txt files from backup directory."""
backup_path = Path(source_backup_dir)
dest_path = Path(destination_dir)
dest_path.mkdir(parents=True, exist_ok=True)
…
How to Scan Configuration Files for Security Issues in Python
Automatically scan configuration files for common security mistakes using regex rules in Python.
import re
import os
from pathlib import Path
SECURITY_RULES = [
(r'^#\s*INSECURE_', 'Insecure comment starts with # INSECURE_'),
(r'password\s*=\s*("|\\\')?[^"\\\'"\s]+("|\\\')?$', 'Hardcoded password'),
(r'debug\s*=\s*True', 'Debug mode enabled'),
(r'[Pp]ermit[Rr]ootLogin\s+yes', 'PermitRootLogin ena…
How to Track GitHub Stars, Forks, and Watchers in Python
Automatically fetch and track stars, forks, and watchers for multiple GitHub repositories, saving snapshots locally as JSON files for historical analysis.
import os
import time
import json
import requests
from pathlib import Path
from datetime import datetime
REPOS = [
"psf/requests",
"python/cpython",
"pallets/flask",
]
DATA_DIR = Path("github_metrics")
def fetch_repo_stats(repo):
url = f"https://api.github.com/repos/{repo}"
resp = requests.get(ur…
How to apply Kubernetes YAML files from a folder in Python
Uses the Kubernetes Python client to apply all YAML manifests in a directory, with sorted processing and per-file error handling.
import os
import yaml
from kubernetes import client, config
from kubernetes.utils import create_from_yaml
def apply_yaml_folder(folder_path):
"""Apply all YAML files in a folder using the Kubernetes mock client."""
# Load mock configuration
config.load_kube_config()
k8s_client = client.ApiClient()
…
How to automatically organize your Downloads folder by file type in Python
This script scans the Downloads folder and moves files into sub-folders based on their extensions (e.g., Images, Documents, Videos).
import os
import shutil
from pathlib import Path
def organize_downloads_folder(downloads_path=None):
if downloads_path is None:
downloads_path = str(Path.home() / "Downloads")
if not os.path.exists(downloads_path):
print(f"Path {downloads_path} does not exist.")
return
fi…
How to rename music files by ID3 tags in Python
Renames MP3 files in a folder using artist and title extracted from ID3 tags, with a mock fallback that parses filenames.
import os
import re
from pathlib import Path
def sanitize_filename(name: str) -> str:
return re.sub(r'[<>:"/\\|?*]', '_', name).strip()
def rename_mp3_from_id3(path: Path) -> None:
for f in path.glob("*.mp3"):
# Mock ID3 extraction: derive artist/title from filename
stem = f.stem
if "…
How to stage and commit all changes with Git in Python
Run git add -A and git commit from Python using subprocess to automate staging and committing all file changes in one step.
import subprocess
from pathlib import Path
def stage_and_commit_all(commit_message: str) -> None:
"""Stage all changes and create a commit with the given message."""
repo_root = Path.cwd()
if not (repo_root / ".git").exists():
raise RuntimeError("Not inside a Git repository")
subprocess.run([…
Mock Certbot Renewal in Python for Testing
Simulates a Let's Encrypt certificate renewal by writing a mock certificate file and printing realistic certbot CLI output, without calling the actual certbot.
import subprocess
import sys
from datetime import datetime, timedelta
from pathlib import Path
def renew_cert(domain: str, output_dir: str = "certs") -> str:
"""Simulate a Let's Encrypt renewal with mock certbot output."""
out = Path(output_dir)
out.mkdir(parents=True, exist_ok=True)
cert_path = out…
Mock a Helm Upgrade Install Command in Python
Use unittest mock to simulate a Helm upgrade --install call for testing automation scripts without a real cluster.
from unittest.mock import MagicMock, patch
class HelmClient:
def upgrade_install(self, release, chart, namespace="default"):
# Simulates the helm upgrade --install command
return f"Release {release} upgraded/installed in {namespace} using chart {chart}"
@patch("helm_client.HelmClient.upgrade_in…
Monitor Website Uptime with Python
Periodically check if a website is reachable and its HTTP status is 200, logging the status with timestamps.
import requests
import time
def check_website(url):
try:
response = requests.get(url, timeout=5)
if response.status_code == 200:
return True
else:
return False
except requests.ConnectionError:
return False
except requests.Timeout:
return Fals…
Rename Files in Folder with Numeric Prefix in Python
Renames all files in a folder by adding a sequential numeric prefix (e.g., 01_, 02_) to each filename using pathlib.
from pathlib import Path
def rename_with_numeric_prefix(folder_path):
folder = Path(folder_path)
for index, file_path in enumerate(folder.iterdir(), start=1):
if file_path.is_file():
new_name = f"{index:02d}_{file_path.name}"
new_path = file_path.with_name(new_name)
…
Scrape HTML Tables in Python with html.parser
Extract data from HTML tables using Python's built-in html.parser module, without third-party dependencies, by overriding callback methods to track table, row, and cell states.
import html.parser
from urllib.request import urlopen
class TableParser(html.parser.HTMLParser):
def __init__(self):
super().__init__()
self.in_table = False
self.in_row = False
self.in_cell = False
self.current_cell = []
self.rows = []
self.row = []
d…
Stress CPU Threads with a Mock Compute in Python
Simulates CPU-intensive work across multiple threads to test how Python schedules parallel compute.
import threading
import time
def stress_cpu(iterations: int):
result = 0
for i in range(iterations):
result += i * i % 1000
return result
def run_mock_stress(thread_count: int, iterations: int):
threads = []
for tid in range(thread_count):
t = threading.Thread(target=lambda: str…
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.