Get A Variable From A Running Program
I have a script that runs for days, and inside it there's a counter. The counter gets written to a file periodically, is it possible to find out the value that the counter is set f
Solution 1:
Yes, you could use any IPC method e.g., you could send the counter over a socket:
self.request.sendall(json.dumps(dict(counter=a)).encode('ascii'))
If you want to get the value from an already running process that you can't modify then you could try to attach a debugger:
$ sudo gdb python <pid of running process>
To enable python-specific helper commands, add to your ~/.gdbinit
:
add-auto-load-safe-path /path/to/python-gdb.py
The example gdb session could look like:
>>> thread apply all py-list
Thread 1 (Thread 0x7f68ff397700 (LWP 9807)):
2 import random
3
4 a = 0
5 while True:
6 a +=1
>7 time.sleep(random.random())
>>> py-print a
global 'a' = 83
From another Python script, you could run gdb in the batch mode:
#!/usr/bin/env python
import shlex
import subprocess
cmd = shlex.split("sudo gdb --batch -ex 'py-print a' python") + [str(pid)]
output = subprocess.check_output(cmd, stderr=subprocess.DEVNULL,
cwd=path_to_python_gdb)
a = int(output.rsplit(b'\n', 2)[-2].rpartition(b' ')[2])
Post a Comment for "Get A Variable From A Running Program"