Add a non-interactive batch mode to python -m pstats

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:

  1. import pstats,

  2. execute one command (e.g., sort cumulative; stats 10),

  3. print the result to stdout,

  4. 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/--commands to 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 --execute is provided, read commands from stdin and run them (pipe-friendly).

  • (Optional) --format=json for machine-readable output of stats 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.

These organically work already?

True but relies on command line / shell experience to realize that. A note in the pstats documentation would seem appropriate.

Yes, I agree. In that case it is not obvious from the documentation that you can execute the commands without using the interactive shell.