On this page
  1. Automation, DevOps & Web Scraping
  2. Contents
  3. Filesystem & Archive Automation (pathlib, shutil, tarfile)
  4. Running External Commands (subprocess & argparse)
  5. Configuration & Diagnostics (tomllib, configparser, socket)
  6. Web Scraping & HTML Parsing (urllib.request & html.parser)

Automation, DevOps & Web Scraping

Prev: Desktop GUI Development | Up: Popular Application Domains | Next: tutorials
Rel: pathlib, shutil, subprocess, argparse, html, urllib, tomllib, tarfile
Ref: docs.python.org โ€” pathlib | docs.python.org โ€” subprocess | docs.python.org โ€” html.parser
Tags: #public #python3 #tutorials #domains #automation #devops #scraping #stdlib


Contents


Filesystem & Archive Automation (pathlib, shutil, tarfile)

Prefer [[stdlib_module/pathlib|pathlib.Path]] for cross-platform path manipulation and [[stdlib_module/tarfile|tarfile]] / [[stdlib_module/zipfile|zipfile]] for backup archives.

from pathlib import Path
import tarfile
import tempfile

with tempfile.TemporaryDirectory() as tmp:
    root = Path(tmp)
    (root / "notes.txt").write_text("backup me\n", encoding="utf-8")

    archive_path = root / "backup.tar.gz"
    with tarfile.open(archive_path, "w:gz") as tar:
        for file in root.glob("*.txt"):
            tar.add(file, arcname=file.name)

    with tarfile.open(archive_path, "r:gz") as tar:
        print("Archived members:", tar.getnames())  # ['notes.txt']

Running External Commands (subprocess & argparse)

Use [[stdlib_module/subprocess|subprocess.run()]] with a list of arguments (avoiding shell=True to prevent shell injection) and [[stdlib_module/argparse|argparse]] for structured CLI scripts.

import argparse
import subprocess
import sys

def run_command(args: list[str]) -> str:
    completed = subprocess.run(
        args,
        capture_output=True,
        text=True,
        check=True,
        timeout=10,
    )
    return completed.stdout.strip()

print("Python version:", run_command([sys.executable, "--version"]))

parser = argparse.ArgumentParser(description="Inspect directory entries.")
parser.add_argument("--limit", type=int, default=5, help="Max items to display")
parsed = parser.parse_args(["--limit", "3"])
print("Parsed CLI limit:", parsed.limit)

Configuration & Diagnostics (tomllib, configparser, socket)

Python 3.11+ includes [[stdlib_module/tomllib|tomllib]] for parsing pyproject.toml and TOML config files natively, alongside [[stdlib_module/configparser|configparser]] for INI files and [[stdlib_module/socket|socket]] for TCP health checks.

import socket
import tomllib

raw_toml = """
[service]
name = "api-gateway"
port = 8080
retries = 3
"""

cfg = tomllib.loads(raw_toml)
print(cfg["service"]["name"], cfg["service"]["port"])

def check_tcp_port(host: str, port: int, timeout: float = 1.0) -> bool:
    try:
        with socket.create_connection((host, port), timeout=timeout):
            return True
    except OSError:
        return False

Web Scraping & HTML Parsing (urllib.request & html.parser)

[[stdlib_module/html|html.parser.HTMLParser]] parses HTML documents in a streaming event-driven manner using only the standard library (paired with [[stdlib_module/urllib|urllib.request.urlopen()]] for fetching pages).

from html.parser import HTMLParser

class LinkExtractor(HTMLParser):
    def __init__(self) -> None:
        super().__init__()
        self.links: list[str] = []

    def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
        if tag == "a":
            attr_map = dict(attrs)
            if href := attr_map.get("href"):
                self.links.append(href)

sample_html = """
<html><body>
  <a href="https://docs.python.org/3/">Python Docs</a>
  <a href="https://peps.python.org/">PEP Index</a>
</body></html>
"""

extractor = LinkExtractor()
extractor.feed(sample_html)
print("Extracted links:", extractor.links)

Linked from

Related notes