On this page
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`)
- > Running External Commands (`subprocess` & `argparse`)
- > Configuration & Diagnostics (`tomllib`, `configparser`, `socket`)
- > Web Scraping & HTML Parsing (`urllib.request` & `html.parser`)
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
- tuts/python3/tutorials/popular_application_domains/desktop_gui_development Linked here; links to this page; shared tags: #domains, #stdlib, #tutorials
- tuts/python3/tutorials/popular_application_domains Linked here; links to this page; shared tags: #domains, #tutorials
- tuts/python3/tutorials Linked here; links to this page; shared tags: #tutorials
- tuts/python3/stdlib_module/argparse Linked here; shared tags: #stdlib
- tuts/python3/stdlib_module/html Linked here; shared tags: #stdlib
- tuts/python3/stdlib_module/pathlib Linked here; shared tags: #stdlib
- tuts/python3/stdlib_module/shutil Linked here; shared tags: #stdlib
- tuts/python3/stdlib_module/subprocess Linked here; shared tags: #stdlib
- tuts/python3/stdlib_module/tarfile Linked here; shared tags: #stdlib
- tuts/python3/stdlib_module/tomllib Linked here; shared tags: #stdlib