从正在运行的程序中获取变量 [英] Get a variable from a running program
问题描述
我有一个运行了几天的脚本,并且在其中有一个计数器.计数器会定期写入文件,是否可以从其他python脚本,linux命令甚至Java中找出计数器设置的值?
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 from either another python script, linux command, or even java?
简单的python计数器示例:
Example of simple python counter:
import time
import random
a = 0
while True:
a +=1
time.sleep(random.random())
我对给定时间的 a
的值感兴趣.
I'm interested in the value of a
at a given time.
推荐答案
是的,您可以使用任何IPC方法,例如,您可以将计数器发送到套接字:
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'))
如果要从无法修改的已经运行的进程中获取值,则可以尝试附加调试器:
$ sudo gdb python <pid of running process>
要启用特定于python的帮助程序命令,请添加到您的〜/.gdbinit
:
To enable python-specific helper commands, add to your ~/.gdbinit
:
add-auto-load-safe-path /path/to/python-gdb.py
示例gdb会话可能类似于:
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
通过另一个Python脚本,您可以以批处理模式运行gdb:
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])
这篇关于从正在运行的程序中获取变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!