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",
…
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…
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 Build a CLI with argparse in Python
Create a beginner-friendly command-line tool in Python that processes multiple filenames with optional flags for verbose output and uppercase conversion.
import argparse
def main():
parser = argparse.ArgumentParser(
description="A simple CLI to process files with optional verbose mode."
)
parser.add_argument("filenames", nargs="+", help="Files to process")
parser.add_argument("-v", "--verbose", action="store_true", help="Print extra details")
…
How to Build a Simple Python CLI with argparse
Create a friendly command-line greeting tool with argparse that accepts a positional name and optional flags for custom greetings and uppercase output.
import argparse
def greet(name, greeting="Hello", uppercase=False):
message = f"{greeting}, {name}!"
return message.upper() if uppercase else message
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="A simple greeting tool to demonstrate argparse basics."
)
parser.…
How to Build a Simple argparse CLI in Python
Build a beginner-friendly command-line tool with argparse that greets a user, with optional greeting text and uppercase output.
import argparse
def greet(name, greeting="Hello", uppercase=False):
message = f"{greeting}, {name}!"
if uppercase:
message = message.upper()
return message
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Simple CLI greeting tool")
parser.add_argument("name", help=…
How to Build an argparse Command-Line Tool in Python
Create a simple file-info CLI with argparse that counts lines and prints file size, with optional verbose and output flags.
import argparse
import os
from pathlib import Path
def process_file(filepath, verbose=False):
"""Read a file and report its size and line count."""
path = Path(filepath)
if not path.exists():
raise FileNotFoundError(f"File not found: {filepath}")
content = path.read_text()
lines = conten…
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 Mock a Whisper API Transcription Stub in Python
Simulate an OpenAI Whisper-style transcription response with a dataclass request model and a mock function that returns structured audio transcription output.
import json
from dataclasses import dataclass
from typing import Optional
@dataclass
class AudioRequest:
file_path: str
language: Optional[str] = None
def to_api_payload(self) -> dict:
return {"file": self.file_path, "language": self.language}
def mock_whisper_transcribe(payload: dict) -> dict:
…
How to Mock subprocess Calls in Python with unittest.mock
A Python script that wraps Vagrant up/destroy commands using subprocess, with tests that mock the subprocess call to simulate outputs and errors.
import subprocess
from unittest.mock import patch, Mock
def run_vagrant(action: str) -> str:
result = subprocess.run(
["vagrant", action],
capture_output=True,
text=True,
check=False,
)
return result.stdout.strip()
def vagrant_wrapper(action: str) -> str:
if action n…
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…
How to Parse Terraform Plan Output in Python
Parse mock Terraform plan output text into structured add, change, and destroy lists using Python.
import json
from typing import Dict, List
def parse_terraform_plan_output(plan_output_text: str) -> Dict[str, List[str]]:
"""
Parses a mock Terraform plan output text into a structured dictionary.
"""
parsed: Dict[str, List[str]] = {"add": [], "change": [], "destroy": []}
for line in plan_output_…
How to Watch a Folder and Convert New Images in Python
Watch a folder for new files and mock-convert images by copying and renaming them in an output directory.
import time
import hashlib
from pathlib import Path
from datetime import datetime
def mock_convert_image(source: Path, dest_dir: Path) -> Path:
"""Mock image conversion: copy bytes and add .converted suffix."""
dest = dest_dir / f"{source.stem}.converted{source.suffix}"
dest.write_bytes(source.read_bytes(…
Mock Certbot Renewal in Python for Testing
Simulates a Let's Encrypt certificate renewal by writing a mock certificate file and printing realistic certbot CLI output, without calling the actual certbot.
import subprocess
import sys
from datetime import datetime, timedelta
from pathlib import Path
def renew_cert(domain: str, output_dir: str = "certs") -> str:
"""Simulate a Let's Encrypt renewal with mock certbot output."""
out = Path(output_dir)
out.mkdir(parents=True, exist_ok=True)
cert_path = out…
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": …
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.