Practical scripting, CLI & automation
argparse, subprocess, filesystem automation, configuration, SQLite, HTTP clients and test doubles.
Command-line interfaces with argparse
Turn a script into a usable CLI with positional arguments, options, flags, type conversion, validation and generated help.
argparse is Python's standard-library default for basic command-line applications. An ArgumentParser describes what the program accepts; add_argument() declares positional arguments, named options and boolean flags, and parse_args() converts the actual command line into a Namespace. Declaring type=int, choices=..., defaults and required values moves routine validation into the parser and produces consistent usage/error messages automatically. -h/--help is generated for you. For larger CLIs, add_subparsers() can model commands such as tool test ... and tool report .... Keep parsing near the application entry point rather than at import time so the module remains easy to import and test.
Key points
- ArgumentParser + add_argument() declares the CLI contract; parse_args() returns a Namespace
- Use type, choices, defaults and actions such as store_true instead of hand-parsing sys.argv
- argparse generates help and input-error messages automatically, and subparsers support multi-command CLIs
Code
import argparse
def build_parser():
parser = argparse.ArgumentParser(description="Run a test suite")
parser.add_argument("suite", help="suite name")
parser.add_argument("--retries", type=int, default=1, choices=range(1, 6))
parser.add_argument("-v", "--verbose", action="store_true")
return parser
def main():
args = build_parser().parse_args()
print(f"suite={args.suite} retries={args.retries} verbose={args.verbose}")
if __name__ == "__main__":
main()A complete small CLI with one positional argument, a validated integer option, a boolean flag and generated help.
Common pitfalls
- Using type=bool does not create a normal flag; use action="store_true" or action="store_false"
- Calling parse_args() at module import time makes the module hard to import from tests or other code
- Manually indexing sys.argv duplicates validation and help behavior that argparse already provides
Practice exercise
Build a CLI that accepts a required environment name, an optional --workers integer from 1 to 8, and a --dry-run flag; verify the automatically generated --help and an invalid workers value.
Running external commands with subprocess
Use subprocess.run() to execute external programs, inspect exit codes, capture output and enforce timeouts safely.
subprocess.run() is the recommended high-level interface for executing an external command when you can wait for it to finish. Pass the command as a list of arguments so quoting is explicit, use check=True when a non-zero exit status should be an exception, capture_output=True plus text=True when you need stdout/stderr as strings, and timeout= so a hung child process cannot block forever. The returned CompletedProcess exposes returncode, stdout and stderr; failures with check=True raise CalledProcessError, and timeouts raise TimeoutExpired. Avoid shell=True for untrusted or interpolated input because passing text through a shell introduces command-injection and quoting risks.
Key points
- Prefer subprocess.run() for ordinary synchronous command execution
- Use check=True, capture_output=True, text=True and timeout= deliberately according to the contract you need
- Pass an argument list and avoid shell=True for untrusted input
Code
import subprocess
import sys
result = subprocess.run(
[sys.executable, "-c", "print('child ok')"],
check=True,
capture_output=True,
text=True,
timeout=5,
)
print(result.returncode)
print(result.stdout.strip())A portable child Python process whose exit status and captured stdout are checked explicitly.
Common pitfalls
- Ignoring the return code can make a failed external tool look like success
- shell=True with interpolated user input can create command-injection vulnerabilities
- Without a timeout, a stuck child process can block the caller indefinitely
Practice exercise
Run a child Python process that writes one line to stdout and one to stderr, capture both streams as text, then intentionally exit with code 2 and observe CalledProcessError when check=True is enabled.
Filesystem automation with shutil and tempfile
Combine pathlib with shutil for high-level file operations and tempfile for isolated temporary workspaces.
pathlib is excellent for expressing paths, while shutil provides high-level operations such as copying files (copy2), moving paths, copying directory trees, deleting directory trees and creating archives. tempfile creates temporary files and directories without hardcoding collision-prone names; context managers such as TemporaryDirectory() remove their workspace automatically when the block exits. This combination is particularly useful for test setup, build scripts and data-conversion jobs: create an isolated workspace, do the work, copy or archive the result, then let cleanup happen reliably. Treat destructive calls such as shutil.rmtree() as production operations — validate the target before deleting anything.
Key points
- Use pathlib for paths and shutil for high-level copy/move/tree/archive operations
- TemporaryDirectory() gives an isolated directory and removes it automatically on context exit
- Validate targets before destructive operations such as rmtree()
Code
from pathlib import Path
import shutil
import tempfile
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
source = root / "result.txt"
backup = root / "backup"
backup.mkdir()
source.write_text("passed\n", encoding="utf-8")
copied = shutil.copy2(source, backup / source.name)
print(Path(copied).read_text(encoding="utf-8").strip())
print("temporary workspace cleaned")A temporary workspace is created, a file is copied with shutil.copy2(), read back, and then cleaned automatically.
Common pitfalls
- shutil.rmtree() is recursive and destructive; a wrong path can remove far more than intended
- copy2() preserves more metadata than copy(), but it still cannot preserve every filesystem metadata feature on every OS
- Do not rely on a TemporaryDirectory path after its context has exited
Practice exercise
Create a TemporaryDirectory, generate three text files inside it, copy only the .txt files into a backup subdirectory, print the copied filenames, and confirm the temporary tree disappears after the context exits.
Configuration: environment variables, TOML and INI
Separate runtime configuration from code using environment variables and structured configuration files.
Configuration should describe how a program runs without requiring source-code edits. Environment variables (os.environ / os.getenv) are a common way to inject deployment-specific values and secrets. tomllib reads TOML into ordinary Python dictionaries and is a good fit for structured application or tool configuration; it is read-only in the standard library. configparser handles traditional INI files with named sections and string values. Decide precedence explicitly — for example defaults < config file < environment variables < CLI arguments — so operators can predict which value wins. Parse configuration once near startup, validate required values and types, and pass a typed configuration object deeper into the program instead of reading global environment state everywhere.
Key points
- Use environment variables for deployment-specific values and secrets, not hardcoded source constants
- tomllib reads structured TOML; configparser reads/writes INI-style sections
- Define configuration precedence and validate configuration once near application startup
Code
import configparser
import os
import tomllib
toml_config = tomllib.loads("""
timeout = 5
[api]
base_url = "https://example.test"
""")
ini = configparser.ConfigParser()
ini.read_string("""
[pytest]
addopts = -q
""")
environment = os.getenv("APP_ENV", "local")
print(environment)
print(toml_config["api"]["base_url"], toml_config["timeout"])
print(ini["pytest"]["addopts"])Reading three common configuration sources without hardcoding environment-specific behavior into program logic.
Common pitfalls
- Environment variables are strings; convert and validate numbers, booleans and structured values explicitly
- tomllib reads TOML but does not write it
- Letting different modules independently read globals makes precedence and testing difficult to reason about
Practice exercise
Define defaults for base_url and timeout, load overrides from a TOML string, then let API_TIMEOUT from the environment override only timeout; print the final resolved configuration.
SQLite from Python with sqlite3
Use the built-in DB-API interface for local relational data, parameterized SQL, transactions and row retrieval.
The standard-library sqlite3 module connects Python to SQLite without a separate database server. connect() returns a connection, execute() runs SQL, and placeholders (?) bind values separately from SQL text so data is not concatenated into a query. A connection used as a context manager commits the transaction when the block succeeds and rolls it back when an exception escapes, but that context manager does not close the connection by itself, so close it explicitly. sqlite3.Row makes result rows accessible by column name. SQLite is useful for local tools, fixtures, caches and prototypes; production systems with concurrent remote clients usually need a server database, but the DB-API habits — parameters, transactions and explicit resource ownership — transfer directly.
Key points
- Use ? placeholders and parameter tuples instead of interpolating values into SQL
- Use transactions deliberately; the connection context manager commits or rolls back but does not close the connection
- sqlite3.Row provides readable name-based column access
Code
import sqlite3
con = sqlite3.connect(":memory:")
con.row_factory = sqlite3.Row
try:
with con:
con.execute("CREATE TABLE tests (name TEXT, duration_ms INTEGER)")
con.executemany(
"INSERT INTO tests VALUES (?, ?)",
[("login", 120), ("search", 75), ("checkout", 210)],
)
rows = con.execute(
"SELECT name, duration_ms FROM tests WHERE duration_ms > ? ORDER BY duration_ms",
(100,),
).fetchall()
print([dict(row) for row in rows])
finally:
con.close()An in-memory database demonstrates schema creation, parameterized inserts, a transaction and a parameterized SELECT.
Common pitfalls
- Never build SQL with f-strings or string concatenation for data values; bind parameters instead
- A connection context manager manages transactions but does not automatically close the connection
- Forgetting transaction boundaries can leave writes uncommitted or make failure behavior unclear
Practice exercise
Create an in-memory table of test runs, insert several rows with executemany(), update one status inside a transaction, and select only failed rows using a bound parameter rather than string formatting.
Test doubles with unittest.mock and pytest monkeypatch
Replace slow or external boundaries in tests, control behavior, and verify interactions without replacing the code under test.
A test double replaces a dependency at a boundary so the test can control inputs or observe interactions. unittest.mock.Mock can return configured values and record calls; patch() temporarily replaces an attribute for the duration of a context manager or decorated test. The central rule is to patch the name where the code under test looks it up, not automatically where the original object was defined. pytest's monkeypatch fixture is a lightweight way to replace attributes, dictionary entries or environment variables and automatically restores them after the test. Mock external HTTP clients, clocks or OS boundaries when isolation is valuable, but avoid mocking the unit's own internal logic so heavily that the test merely verifies its implementation rather than behavior.
Key points
- Mock or patch external boundaries, not the behavior you are actually trying to test
- Patch where the dependency is looked up by the code under test
- pytest monkeypatch automatically restores attributes, mappings and environment changes after the test
Code
from unittest.mock import Mock
class HealthService:
def __init__(self, client):
self.client = client
def is_ready(self):
return self.client.get("/health")["status"] == "ok"
client = Mock()
client.get.return_value = {"status": "ok"}
service = HealthService(client)
print(service.is_ready())
client.get.assert_called_once_with("/health")
# In pytest, monkeypatch can temporarily change an env var:
# monkeypatch.setenv("APP_ENV", "test")A mock replaces only the HTTP-client boundary while the service's real decision logic still executes and the interaction is asserted.
Common pitfalls
- Patching the object at its definition instead of the name imported by the module under test often has no effect
- Over-mocking implementation details makes refactoring break tests even when behavior is unchanged
- A Mock accepts many misspelled attributes unless you use a spec/autospec or another stricter interface
Practice exercise
Write a function that asks a client for /version and returns the version string. Test it with Mock, assert the call arguments, then write a pytest test that uses monkeypatch.setenv() to control a separate environment-dependent branch.
HTTP clients with Requests
Make maintainable HTTP calls with explicit timeouts, status checks, query parameters, JSON payloads and sessions.
Requests is a third-party HTTP client, so install it in the project's environment and declare it as a dependency rather than assuming it is part of Python. requests.get()/post() return a Response; call raise_for_status() when non-success HTTP statuses should become exceptions, use response.json() only when the response is expected to contain JSON, and always set a timeout so a network call cannot wait forever. Pass query parameters through params= and JSON request bodies through json= instead of manually building URLs or serializing payloads. A requests.Session() can reuse connection state and shared headers across several calls. In production code, keep HTTP access behind a small client function/class so tests can replace that boundary cleanly.
Key points
- Requests is third-party: install and declare it as a project dependency
- Set timeouts, check status deliberately with raise_for_status(), and decode JSON only when the contract says JSON
- Use params= and json= instead of hand-building query strings or JSON text; use Session for repeated calls
Code
import requests
def fetch_user(base_url: str, user_id: int) -> dict:
response = requests.get(
f"{base_url}/users/{user_id}",
params={"include": "roles"},
timeout=5,
)
response.raise_for_status()
return response.json()A small HTTP boundary with a query parameter, explicit timeout, status validation and JSON decoding.
Common pitfalls
- Requests has no default timeout, so omitting timeout= can leave a call waiting indefinitely
- A 404 or 500 response is still a Response object; call raise_for_status() or handle status_code explicitly
- Calling response.json() does not prove Content-Type or schema correctness and can itself fail on invalid JSON
Practice exercise
Write create_job(base_url, payload) that POSTs JSON with a 5-second timeout, requires a successful status, and returns the decoded JSON. Keep the HTTP call in this single function so a unit test can replace it.
Secrets, hashes and UUIDs
Know when to use secrets for secure randomness, hashlib for digests, and uuid for identifiers.
Different utilities solve different problems. secrets generates cryptographically strong random values suitable for tokens and reset links; the random module is for simulation and sampling, not security. hashlib computes deterministic message digests such as SHA-256, useful for integrity checks, cache keys and content fingerprints — but a fast general-purpose hash is not a password-storage scheme, which requires a dedicated password-hashing algorithm with salting and work factors. uuid.uuid4() generates a random UUID for identifiers that need extremely low collision probability without coordination; a UUID is an identifier, not a secret. Keep these distinctions explicit so code does not accidentally use a convenient primitive for the wrong security property.
Key points
- Use secrets, not random, for security-sensitive tokens
- hashlib digests are useful for integrity/fingerprints but raw SHA-256 is not a password-storage solution
- UUIDs are identifiers with low collision probability; they are not secrets or authorization tokens
Code
import hashlib
import secrets
import uuid
token = secrets.token_urlsafe(16)
digest = hashlib.sha256(b"build-artifact").hexdigest()
run_id = uuid.uuid4()
print("token length:", len(token))
print("sha256:", digest)
print("run id:", run_id)Three distinct primitives demonstrate secure random tokens, deterministic hashing and unique identifiers.
Common pitfalls
- random.random() and random.choice() are not appropriate for secrets or security tokens
- A UUID is usually guessable enough that it must not be treated as authentication
- Fast hashes such as plain SHA-256 are not suitable for storing passwords directly
Practice exercise
Generate a secure token, hash a byte string twice to prove the digest is deterministic, and generate two UUID4 values to show they are distinct identifiers.