Debug and Profile Python Apps from the CLI
Use Python's built-in debugger (pdb), profiling tools (cProfile), and memory analysis to find bugs and performance bottlenecks from the command line.
Prerequisites
- -Python 3.8+ installed
Steps
Run a script with the debugger
Start the script under the Python debugger. Execution pauses at the first line, letting you step through code, set breakpoints, and inspect variables.
Use breakpoint() in your code to set inline breakpoints instead of running the entire script under pdb.
Run with post-mortem debugging on crash
If a script crashes, use pdb.pm() to open the debugger at the point of the exception. You can inspect the traceback, local variables, and call stack.
The simpler approach is to add 'breakpoint()' on the line before the crash and run normally, which drops you into pdb at that exact location.
Profile a script with cProfile
Run the script with the built-in profiler and sort results by cumulative time. This shows which functions consume the most total time including their callees.
Save profiling data and analyze it
Save profiling data to a binary file and open the interactive pstats browser. You can sort, filter, and drill into call trees.
Use 'snakeviz profile.prof' for a visual flame graph in your browser. Install with pip install snakeviz.
Measure memory usage with tracemalloc
Trace memory allocations and display the top 10 lines by memory consumption. This helps identify memory leaks and excessive allocations.
Time a specific code snippet
Benchmark a code snippet by running it 1000 times and reporting the average execution time. The -s flag runs setup code once before timing begins.
Full Script
FAQ
Discussion
Loading comments...