Skip to content

gh-159560: Add a command-line interface to tracemalloc - #159563

Open
vadim-smal wants to merge 2 commits into
python:mainfrom
vadim-smal:CognitiveDisson/tracemalloc-cli
Open

vadim-smal wants to merge 2 commits into
python:mainfrom
vadim-smal:CognitiveDisson/tracemalloc-cli

Conversation

@vadim-smal

@vadim-smal vadim-smal commented Oct 16, 2026 •

Copy link
Copy Markdown

Why make this change

Today, to check memory allocations of a script with tracemalloc you have to modify the script itself. This adds python -m tracemalloc, so it can be used the same way as cProfile, without touching the code. Discussed in https://discuss.python.org/t/run-tracemalloc-module-as-a-script/50821.

$ python -m tracemalloc -l 5 script.py
Top 5 lineno allocations still alive at exit:
script.py:2: size=981 KiB, count=101, average=9942 B
<frozen runpy>:266: size=434 B, count=4, average=108 B
<frozen runpy>:102: size=400 B, count=1, average=400 B
<frozen runpy>:81: size=400 B, count=1, average=400 B
script.py:1: size=168 B, count=1, average=168 B
2 other: size=90 B, count=2
Total size: 982 KiB
Peak size: 983 KiB

What will change

  • Add _main() to Lib/tracemalloc.py with options -o, -t, --cumulative, -n, -l and -m
  • Run the target with runpy, so sys.argv, __name__ and sys.path[0] are the same as when it runs directly. Directories and zip files work too
  • Keep the globals of the traced program alive until the snapshot is taken, otherwise module level data is freed before the report
  • Strip the oldest runpy / tracemalloc frames from the tracebacks, so --cumulative and -t traceback show only the frames of the traced program
  • Restart tracing if it was already enabled by -X tracemalloc or PYTHONTRACEMALLOC, otherwise -n is silently ignored
  • With -o, dumped snapshots use tracemalloc.Snapshot ( not __main__.Snapshot ), so they can be loaded with Snapshot.load()
  • Add docs, a What's New entry and tests

Known limitations, same as cProfile:

  • a missing -m module raises ImportError with a traceback. Checking it before tracing would import its parent packages untraced
  • a -- right after the target is removed by argparse ( same in profiling.sampling )

@vadim-smal
vadim-smal requested a review from AA-Turner as a code owner October 16, 2026 17:43
@python-cla-bot

python-cla-bot Bot commented Oct 16, 2026 •

Copy link
Copy Markdown

All commit authors signed the Contributor License Agreement.

CLA signed

@read-the-docs-community

Copy link
Copy Markdown

Documentation build overview

📚 cpython-previews | 🛠️ Build #35197853 | 📁 Comparing dd69fd2 against main (d3ada45)

  🔍 Preview build  

4 files changed
± library/cmdline.html
± library/tracemalloc.html
± whatsnew/3.16.html
± whatsnew/changelog.html

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant