Automation & scripting
CLI tools, scheduled jobs, filesystem tasks, and glue scripts that save time.
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.
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…
Automatically Log CPU, RAM, and Disk Usage Every Minute in Python
This script logs CPU, RAM, and disk usage to a CSV file every 60 seconds using psutil and Python's standard library.
import psutil
import time
import csv
from pathlib import Path
LOG_FILE = Path("system_usage_log.csv")
INTERVAL_SECONDS = 60
def log_system_usage():
"""Write CPU, RAM, and disk usage to CSV every minute."""
file_exists = LOG_FILE.exists()
with open(LOG_FILE, mode="a", newline="") as f:
writer = cs…
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.
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.")
…
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.
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__":…
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.
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…
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.
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…
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 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 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 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 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)
…
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.