Automation & scripting
CLI tools, scheduled jobs, filesystem tasks, and glue scripts that save time.
Automate Tweeting New Blog Posts in Python
A mock script that fetches new blog posts from a CMS and tweets them via a simulated Twitter API, outputting JSON results.
import json
import time
from datetime import datetime
def fetch_new_blog_posts():
"""Mock function to simulate fetching latest blog posts from a CMS."""
return [
{
"id": 1,
"title": "Getting Started with Python",
"url": "https://blog.example.com/python-start",
…
Build a Python Utility That Verifies Backup Integrity Automatically
Automatically compute and verify SHA-256 checksums of backup files using a JSON manifest to detect missing or corrupted data.
import hashlib
import os
import json
def compute_checksum(filepath, algorithm='sha256'):
"""Compute checksum for the given file."""
hash_func = hashlib.new(algorithm)
with open(filepath, 'rb') as f:
for chunk in iter(lambda: f.read(4096), b''):
hash_func.update(chunk)
return hash_f…
Fetch weather API mock and write dashboard HTML in Python
This script fetches a mock weather API response as a Python dict, builds a simple HTML dashboard, writes it to a file, and prints both the file path and JSON payload.
from datetime import datetime
import json
import os
def fetch_weather_mock(city: str) -> dict:
"""Return a mock weather payload for a given city."""
return {
"city": city,
"temperature_c": 21.5,
"condition": "Partly Cloudy",
"humidity": 58,
"wind_kph": 12.3,
"u…
Fill PDF Form Fields from a Mock Template in Python
Fills a PDF-style form template dictionary with user data, preserving template fields and formatting output as JSON.
import json
template = {
"first_name": "",
"last_name": "",
"email": "",
"phone": "",
"date_of_birth": "",
"address": "",
"city": "",
"state": "",
"zip_code": "",
"agree_to_terms": False
}
def fill_pdf_form(template: dict, data: dict) -> dict:
for key, value in data.items…
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.
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 = …
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.
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(…
How to Filter Docker Containers for Pruning in Python
Simulate Docker's container prune by filtering a JSON list for exited containers older than a cutoff, returning pruned IDs and space freed.
import json
from datetime import datetime, timedelta
def parse_docker_ps(json_output: str, older_than_hours: int = 24) -> list:
containers = json.loads(json_output)
cutoff = datetime.now() - timedelta(hours=older_than_hours)
return [
c for c in containers
if datetime.fromisoformat(c["crea…
How to Generate a cloud-init User Data Mock in Python
Generate a cloud-init user data mock for a VM using a dataclass and JSON in Python.
import json
from dataclasses import dataclass, asdict
@dataclass
class VMConfig:
hostname: str
cpus: int
memory_mb: int
ssh_key: str
def generate_cloud_init_mock(config: VMConfig) -> str:
"""Build a cloud-init user-data mock for a VM."""
user_data = {
"hostname": config.hostname,
…
How to Mock an Ansible Inventory in Python
Load an Ansible-style inventory JSON file into Python and simulate a playbook run across hosts and groups.
import json
from pathlib import Path
class InventoryMock:
def __init__(self, inventory_file: str):
self.inventory_file = Path(inventory_file)
self.hosts = {}
def load(self):
if not self.inventory_file.exists():
raise FileNotFoundError(f"Inventory file {self.inventory_file…
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.
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…
How to Save a VM Snapshot State to a JSON File in Python
Define a dataclass for a VM snapshot and serialize it to a JSON file, then reload it to verify the state.
import json
from dataclasses import dataclass, asdict
from pathlib import Path
@dataclass
class VMSnapshot:
name: str
memory_mb: int
disk_gb: int
state: str = "saved"
def snapshot_to_file(self, path: Path) -> str:
"""Write snapshot state to a JSON file and return the filename."""
…
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…
Resize Disk Partitions in Python (Mock Script)
A mock disk partition resize script that uses dataclasses to model partitions, validate new sizes, and output the updated layout as JSON.
#!/usr/bin/env python3
"""Mock script to demonstrate disk partition resize logic."""
import json
from dataclasses import dataclass
from typing import Dict
@dataclass
class Partition:
name: str
size_gb: int
mount_point: str
def to_dict(self) -> Dict[str, object]:
return {
"name": …
Track File Changes with Version History in Python
A Python utility that monitors a file for changes, creating versioned backups with SHA-256 hashing to detect modifications and store a local JSON history.
import hashlib, json, os, shutil, time
from pathlib import Path
class FileTracker:
def __init__(self, history_file="file_history.json"):
self.history_file = Path(history_file)
self.history = self._load_history()
def _load_history(self):
if self.history_file.exists():
retur…
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.