Automation & scripting
CLI tools, scheduled jobs, filesystem tasks, and glue scripts that save time.
Automatically Generate Charts from CSV Files with One Command
Read a CSV file with headers, extract the first two numeric columns, and save a matplotlib line chart as a PNG image.
import csv
import sys
from pathlib import Path
import matplotlib.pyplot as plt
def generate_chart(csv_path: str) -> None:
"""Read a CSV file with headers and plot the first two numeric columns."""
data = []
with open(csv_path, 'r', newline='') as f:
reader = csv.reader(f)
headers = next(re…
Build a Network Ping Monitor in Python
A Python script that continuously pings a remote host using subprocess and reports connectivity status with timestamps and latency.
import subprocess
import time
def ping_host(host, count=4):
"""Ping a host and return the results."""
try:
# Platform-independent ping command
cmd = ["ping", "-c", str(count), host]
result = subprocess.run(cmd, capture_output=True, text=True, timeout=10)
return result.stdout, r…
Detect and Remove Blurry Images in Python with OpenCV
Automatically scan a directory of images, detect blur using Laplacian variance, and remove blurry images with a dry-run option for safety.
from pathlib import Path
import cv2
import numpy as np
def is_blurry(image_path, threshold=100.0):
"""
Detect if an image is blurry using Laplacian variance.
Returns True if blurry, False otherwise.
"""
img = cv2.imread(str(image_path), cv2.IMREAD_GRAYSCALE)
if img is None:
return True…
Find Zombie Processes on Linux with Python
Parse the output of `ps -eo pid,stat,comm` to detect processes in zombie state (Z) on a Linux system and report their PIDs and commands.
#!/usr/bin/env python3
import os
import subprocess
def find_zombie_processes():
"""Find zombie processes (state 'Z') running on Linux."""
try:
result = subprocess.run(['ps', '-eo', 'pid,stat,comm'], capture_output=True, text=True, check=True)
zombies = []
for line in result.stdout.stri…
How to Detect Applications Consuming Excessive Memory in Python
Use psutil to list the top memory-using processes by RSS and print their names, PIDs, and memory usage in MB.
import psutil
def find_top_memory_processes(limit=5):
"""Return top `limit` processes by memory usage (RSS)."""
processes = []
for proc in psutil.process_iter(['pid', 'name', 'memory_info']):
try:
info = proc.info
mem = info['memory_info'].rss if info['memory_info'] else 0…
How to Detect Recently Installed Software in Python
Uses subprocess to call pip and parse package metadata to list recently installed Python packages.
import subprocess
import sys
from datetime import datetime, timedelta
def detect_recently_installed(days=7):
"""Detect recently installed software packages."""
recent_packages = []
cutoff_date = datetime.now() - timedelta(days=days)
try:
# For pip-installed packages (Python packages)
…
How to Monitor USB Device Connections in Python
A Python utility that monitors USB device connections and disconnections by comparing output of the lsusb command at regular intervals.
import time
import subprocess
import os
def get_usb_devices():
"""Return list of currently connected USB devices (Linux)."""
try:
result = subprocess.run(['lsusb'], capture_output=True, text=True, check=True)
return result.stdout.strip().split('\n')
except (subprocess.CalledProcessError, F…
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.