Automation & scripting
CLI tools, scheduled jobs, filesystem tasks, and glue scripts that save time.
Create a Simple HTTP File Server in Python
This code creates a simple HTTP file server that serves files from the current working directory on port 8000 using Python's built-in http.server module.
import http.server
import socketserver
import os
PORT = 8000
DIRECTORY = os.getcwd()
class CustomHandler(http.server.SimpleHTTPRequestHandler):
def __init__(self, *args, **kwargs):
super().__init__(*args, directory=DIRECTORY, **kwargs)
def log_message(self, format, *args):
print(f"[{self.log…
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 Cross Post Markdown to dev.to API in Python
A Python function that POSTs markdown content to the dev.to API and handles HTTP or URLError exceptions with mock API testing.
import json
from urllib import request, error
def cross_post_to_devto(markdown_content, api_key, devto_api_url="https://dev.to/api/articles"):
"""
Mock cross-posting of markdown content to the dev.to API.
Returns the API response or an error message.
"""
payload = json.dumps({
"article": …
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…
Port Scan Localhost Common Ports in Python
Scan common localhost ports (HTTP, HTTPS, SSH, FTP, and more) with a fast socket-based Python script that prints an open/closed status table.
import socket
from datetime import datetime
COMMON_PORTS = {
80: "HTTP",
443: "HTTPS",
22: "SSH",
21: "FTP",
25: "SMTP",
3306: "MySQL",
5432: "PostgreSQL"
}
def scan_port(port):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(0.1)
try:
resu…
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.