
How to Use Regex in Python re Module for Scripts Easily
Use the Python re module in scripts: search, match and fullmatch, named groups, finditer, sub with a function, flags, raw strings and backtracking.
Tag
30 posts

Use the Python re module in scripts: search, match and fullmatch, named groups, finditer, sub with a function, flags, raw strings and backtracking.

Run shell commands concurrently with asyncio.create_subprocess_exec: capture output, cap concurrency with a semaphore, add timeouts and kill stuck children.

Run jobs in parallel with Python's concurrent.futures: threads for waiting work and commands, processes for CPU work, as_completed, errors and limits.

Run commands from Python with a timeout, catch TimeoutExpired and CalledProcessError, retry with backoff and kill whole process trees when a command hangs.

Package a Python command line tool with pyproject.toml and a console script entry point, install it with pipx or uv tool, upgrade it and build for others.

Make a Python script executable: write the env python3 shebang, set the mode bit, avoid CRLF line endings, handle virtual environments and put it on PATH.

Write single file Python scripts that declare their own dependencies using PEP 723 inline metadata, run them with uv or pipx, lock versions and share them.

Run Python scripts in isolated environments with uv: create a venv, run with uv run, add one-off packages, pin a Python version and use it in a shebang.

Test a Python command line tool with pytest: subprocess and in-process runs, exit codes and output, tmp_path, monkeypatch and parametrized cases.

Handle SIGINT and SIGTERM in Python scripts: stop a loop cleanly, run cleanup with try and finally, use atexit, and know which signals cannot be caught.

Use the Python REPL and IPython for terminal work: history, tab completion, magics like %timeit, shell commands, editing and a useful startup file.

Send email from a Python script with smtplib and EmailMessage: STARTTLS, passwords from the environment, attachments, HTML bodies and error handling.