Advertisement
Advanced Python, Debugging & Profiling

How would you use py-spy (a sampling profiler) to profile a running Python process in PRODUCTION without restarting it or adding any code changes?

Short answer

py-spy attaches to an ALREADY-RUNNING Python process from OUTSIDE it (using OS-level process introspection, no code changes or restarts needed) and samples the call stack periodically, producing either a live top-style view (`py-spy top --pid `) or a flame graph (`py-spy…

Save Python mock interview
Advertisement
AModel answer
py-spy attaches to an ALREADY-RUNNING Python process from OUTSIDE it (using OS-level process introspection, no code changes or restarts needed) and samples the call stack periodically, producing either a live top-style view (`py-spy top --pid <pid>`) or a flame graph (`py-spy record`) — ideal for diagnosing performance issues in a live production service.
Example

# Attach to a running process by PID, no code modification needed py-spy top --pid 12345 # Record a flame graph over 30 seconds py-spy record -o profile.svg --pid 12345 --duration 30

Real-world example
Diagnosing why a production web server is suddenly consuming excessive CPU, without restarting the service or deploying profiling code.
Likely follow-ups
  • Why is a SAMPLING profiler like py-spy generally considered safer for production use than a deterministic profiler like cProfile?
Related topics