giampaolo / psutil

Cross-platform lib for process and system monitoring in Python
BSD 3-Clause "New" or "Revised" License
10.11k stars 1.37k forks source link

Frame or Line Execution of the current psutil.Process? #2279

Closed davidbernat closed 11 months ago

davidbernat commented 1 year ago

Summary

Numerous inspection mechanisms enable the use of profilers to detail what line of Python code is being executed at any current time through the Frames and Stack. When within the current process, the use of sys._getframe() provides this information. However, psutil is a monitoring system in which the working process is monitored from the outside; therefore, the working process pid is known, but calling sys._getframe() from the monitoring system will provide frames of the monitoring system, not the internal state of the working system. It seems clear to me that inspection of this sort ought to be available with the existing off-the-shelf Python capabilities. What are the solutions here, and are the appropriate for inclusion into psutil directly?

giampaolo commented 11 months ago

I am not sure if something like that exists. There are tools like strace on Linux or Truss on FreeBSD which allows you to "attach" to a process PID and see the system calls (read(), write(), close(), etc) in real time, as they are executed. In order to do the same for a Python process, and see exactly "where you are" in terms of code execution, you need the collaboration of the Python interpreter (sys._getframe() or whatever). In order to do what sys._getframe() does for an external python process I am afraid you have to build something from scratch, or search if there is something ready on PyPi. E.g. your Python process may listen on a TCP port on localhost, and once you connect to it it can send you the result of sys._getframe(). The client can be made interactive and accept further user input to interact with the remote process similarly to a pdb (python debugger) session. I remember I did something like this many years ago by using standard stdlib modules.