benfred / py-spy

Sampling profiler for Python programs
MIT License
12.53k stars 414 forks source link

How to list local variables in a running program #505

Closed sorasful closed 2 years ago

sorasful commented 2 years ago

Hello there,

I have a fairly simple code, I want to be able to access the pwd variable. I've tried using dump with --locals options, but it did not show me the variables.

import getpass
import time

pwd = getpass.getpass()

while True:
    time.sleep(1)

The result : I can see where I am in the code, but not the values of the variable.

sudo env "PATH=$PATH" py-spy dump --pid 338370 -l -l -j
[
  {
    "pid": 338370,
    "thread_id": 140654867665536,
    "thread_name": null,
    "os_thread_id": 338370,
    "active": false,
    "owns_gil": false,
    "frames": [
      {
        "name": "<module>",
        "filename": "/home/xxx/code/alma/main/yolo.py",
        "module": null,
        "short_filename": "yolo.py",
        "line": 8,
        "locals": []
      }
    ],
    "process_info": null
  }
]

Thanks for your help !

Jongy commented 2 years ago

py-spy dump --locals displays the local variables of each frame. The thing is, a variable defined in the module level is not a variable of any frame - it's a global variable. (which py-spy can theoretically print but it's just to implemented to do so at the moment).

If the code was written this way:

import getpass
import time

def main():
    pwd = getpass.getpass()
    while True:
        time.sleep(1)

main()

you'd achieve your goal :)

sorasful commented 2 years ago

Oh okay, I get it ! Thank you for your answer, I close this :)