Automation & scripting
CLI tools, scheduled jobs, filesystem tasks, and glue scripts that save time.
Automatically Generate Hardware Inventory Reports in Python
Generate a system hardware report including OS version, CPU cores, RAM, and disk usage using platform and psutil.
import platform
import psutil # requires: pip install psutil
from datetime import datetime
def generate_hardware_report():
report_lines = []
report_lines.append(f"Report Generated: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
report_lines.append(f"System: {platform.system()} {platform.release()} ({pl…
Convert Markdown to HTML in Python (Batch)
Convert every Markdown file in a directory to HTML with the Python markdown library, saving each result with an .html extension.
import markdown
from pathlib import Path
def convert_md_to_html(source_dir: str, dest_dir: str) -> list[str]:
src = Path(source_dir)
dst = Path(dest_dir)
dst.mkdir(parents=True, exist_ok=True)
converted_files = []
for md_file in src.glob("*.md"):
html_content = markdown.markdown(md_file.…
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 Docker Image Tag Script in Python
Generate consistent Docker image tags from service names and versions with automatic normalization.
#!/usr/bin/env python3
"""Mock script for building docker image tags."""
def build_tag(service_name: str, version: str, registry: str = "docker.io") -> str:
"""Construct a docker image tag."""
safe_name = service_name.lower().replace("_", "-")
return f"{registry}/{safe_name}:{version}"
if __name__ == "…
How to Bump Version in pyproject.toml Using Regex in Python
Updates the version field in a pyproject.toml file using a regex substitution with the Python standard library.
import re
from pathlib import Path
def bump_version(pyproject_path: str, new_version: str) -> None:
"""Update version in pyproject.toml using regex."""
path = Path(pyproject_path)
content = path.read_text()
# Match version = "x.y.z" (simple or PEP 440 with pre-release)
pattern = r'^version\s*=\s*…
How to Generate an Inventory CSV of Installed pip Packages in Python
This script uses subprocess and csv to list all installed pip packages and write their names and versions into a CSV inventory file.
import subprocess
import csv
def get_installed_packages():
"""Return a list of (name, version) tuples for installed pip packages."""
result = subprocess.run(
["pip", "list", "--format=freeze"],
capture_output=True,
text=True,
check=True
)
packages = []
for line in r…
Pin Python package versions in requirements.txt
Pin package versions in requirements.txt-style text by adding ==version when no specifier is present, while preserving existing version constraints and comments.
import re
from pathlib import Path
def pin_versions(requirements_text: str) -> str:
"""
Pin package versions in requirements.txt-style text.
Adds ==version if no version specifier is present.
Keeps existing specifiers (>=, <=, ~=, etc.) unchanged.
"""
lines = requirements_text.strip().splitli…
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.