Automation & scripting
CLI tools, scheduled jobs, filesystem tasks, and glue scripts that save time.
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 Check Website Status Codes in Python
This script checks the HTTP status codes of multiple URLs concurrently using a thread pool and prints the results.
import requests
from concurrent.futures import ThreadPoolExecutor
URLS = [
"https://www.google.com",
"https://www.python.org",
"https://www.nonexistent-site-12345.com",
"https://www.github.com",
]
def check_status(url):
try:
response = requests.get(url, timeout=5)
return url, resp…
How to Create a Mock Headless Browser Screenshot Stub in Python
This code provides a deterministic stub that simulates capturing webpage screenshots with a headless browser, returning formatted output without real browser dependencies.
import subprocess
import sys
def mock_screenshot_webpage(url: str, width: int = 1280, height: int = 800) -> str:
"""Stub that simulates taking a screenshot of a webpage using headless browser."""
# In real implementation, you would use playwright/selenium/headless chrome
result = {
"url": url,
…
How to Deploy a Static Site Build to an Nginx Directory in Python
Copy a static site build directory into an Nginx web root using Python's shutil and pathlib modules.
import shutil
import os
from pathlib import Path
SRC_DIR = Path("build")
DEST_DIR = Path("/var/www/html")
def deploy_site(src: Path, dest: Path) -> None:
if not src.exists():
raise FileNotFoundError(f"Build directory not found: {src}")
dest.mkdir(parents=True, exist_ok=True)
for item in src.ite…
How to Update a Hosts File to Block Distractions in Python
This script updates a local hosts file (or a demo file) by adding or updating entries to block distracting websites like Facebook and Twitter.
from pathlib import Path
def update_hosts(entries):
"""
Add or update blocking entries in the hosts file.
Uses a local demo file by default to avoid system changes.
"""
hosts_path = Path("demo_hosts.txt")
# Create demo file if it doesn't exist
if not hosts_path.exists():
hosts…
How to generate website performance reports from HTTP requests in Python
Measure and report website load time, status code, and content size using Python's standard library.
import urllib.request
import time
def measure_website_load_time(url):
"""Measures total loading time of a website."""
start_time = time.time()
try:
with urllib.request.urlopen(url, timeout=10) as response:
content = response.read()
status_code = response.status
…
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…
Post a message to a Slack webhook in Python
Send a message to a Slack webhook endpoint using the standard library's urllib.request, handling the POST request and response cleanly.
import json
from urllib import request
def post_to_slack(webhook_url: str, message: str) -> dict:
payload = json.dumps({"text": message}).encode("utf-8")
req = request.Request(
webhook_url,
data=payload,
headers={"Content-Type": "application/json"},
method="POST",
)
wit…
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.