Today, python -m pstats starts an interactive shell that’s great for humans but awkward for automation and coding agents, which need stable stdout and exit codes.
In my experience, coding agents that try to analyse profiles often end up generating short scripts that:
-
import
pstats, -
execute one command (e.g.,
sort cumulative; stats 10), -
print the result to stdout,
-
exit, and then repeat the process for drilling down.
This approach is extremely inefficient as it wastes tokens and context for generating scripts.
A simple non-interactive CLI mode built into pstats would avoid all of that overhead, making automated performance analysis faster, cheaper, and more reproducible.
I propose:
-
--execute/--commandsto run semicolon/newline-separated pstats commands non-interactively and print results to stdout only, then exit with a meaningful status code. -
If stdin is not a TTY and no
--executeis provided, read commands from stdin and run them (pipe-friendly). -
(Optional)
--format=jsonfor machine-readable output ofstats N,callers,callees, etc.
This is fully backward-compatible, requires minimal code (argparse + feeding commands to the existing Stats/cmd loop), and makes pstats easy to use in CI, shell pipelines, and agent workflows.
Examples:
python -m cProfile -o out.prof myscript.py
python -m pstats out.prof --execute "sort cumulative; stats 10"
printf "sort time\nstats 20\n" | python -m pstats out.prof
# Optional JSON
python -m pstats out.prof --execute "stats 10" --format json
Happy to draft a PR with argparse wiring, tests, and docs if there’s interest.