Automation & scripting
CLI tools, scheduled jobs, filesystem tasks, and glue scripts that save time.
Aggregate Log Errors Count by Hour in Python
Counts ERROR log lines per hour using regex and Counter, returning a sorted dictionary of hourly totals.
import re
from collections import Counter
from datetime import datetime
def aggregate_errors_by_hour(log_lines):
pattern = re.compile(r'^(\d{4}-\d{2}-\d{2} \d{2}):\d{2}:\d{2}.*ERROR')
hourly_counts = Counter()
for line in log_lines:
match = pattern.match(line)
if match:
ho…
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…
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.
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_…
Python: Archive Old Logs by Compressing Gzip by Age
A Python script that finds .log files older than a specified age and compresses them into .gz archives while removing the originals.
import gzip
import os
import shutil
from pathlib import Path
def archive_logs(log_dir: str, max_age_days: int) -> list[str]:
"""Compress log files older than max_age_days into .gz archives.
Returns a list of compressed file paths.
"""
cutoff = time.time() - max_age_days * 86400
compressed = …
Track Internet Connectivity and Downtime Automatically in Python
Monitors internet connectivity by pinging a remote host and logs any downtime events with timestamps and duration.
import time
import subprocess
from datetime import datetime
def check_internet(host="8.8.8.8", timeout=3):
"""Returns True if internet is reachable via ping."""
try:
subprocess.run(
["ping", "-c", "1", "-W", str(timeout), host],
capture_output=True,
timeout=timeout …
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.