Automation & scripting
CLI tools, scheduled jobs, filesystem tasks, and glue scripts that save time.
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…
Find Dead Code in a Python Project Using AST
Walk a project tree, parse every Python file with ast, and list defined functions that are never called anywhere.
import ast
import os
import sys
def find_dead_code(project_path):
defined_functions = {}
called_functions = set()
for root, dirs, files in os.walk(project_path):
for file in files:
if file.endswith('.py'):
filepath = os.path.join(root, file)
with open(f…
Find Unused Python Packages Automatically
Scan a Python project's source files for imports and list installed packages not imported anywhere.
import pkg_resources
import ast
import os
import sys
from pathlib import Path
def find_imports_in_project(project_dir="."):
imports = set()
for py_file in Path(project_dir).rglob("*.py"):
try:
with open(py_file, "r") as f:
tree = ast.parse(f.read())
for node in …
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 Generate Project Statistics Including Lines of Code and Complexity in Python
Walk through a Python script that scans a project directory for Python files, counts lines of code excluding blanks and comments, and estimates cyclomatic complexity by counting decision keywords.
import os
from pathlib import Path
def count_lines_of_code(filepath):
"""Counts lines of code in a Python file, excluding blank lines and comments."""
try:
with open(filepath, 'r') as f:
lines = f.readlines()
code_lines = [line for line in lines if line.strip() and not line.strip()…
How to Generate a Dependency Graph for Python Projects
This script walks through a Python project directory, parses each .py file's imports, and prints a dependency graph showing which modules depend on which other modules.
import os
import ast
from pathlib import Path
from collections import defaultdict
def get_imports(filepath):
with open(filepath) as f:
try:
tree = ast.parse(f.read())
except SyntaxError:
return []
imports = []
for node in ast.walk(tree):
if isinstance(node, …
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 check Python files for common coding mistakes
Walks a directory tree parsing each .py file with ast, reporting empty functions, bare try blocks, too many parameters, and empty classes.
import ast
import os
import sys
def check_file(filepath):
try:
with open(filepath) as f:
code = f.read()
tree = ast.parse(code, filename=filepath)
except SyntaxError as e:
print(f"{filepath}: SyntaxError: {e.msg}")
return
issues = []
for node in ast.wal…
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…
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.