我正在尝试使用 python 和 python ptrace 来读取外部进程的内存。我需要完全在 python 中工作,并且我一直在尝试读取并打印出 linux 中进程的内存。
例如,我尝试了以下代码,它一直给我 IO 错误:
proc_mem = open("/proc/%i/mem" % process.pid, "r")
print proc_mem.read()
proc_mem.close()
大多数情况下,我只是想重复转储进程的内存并查找随时间的变化。如果这是执行此操作的正确方法,那么我的问题是什么?或者有更合适的方法吗?
最佳答案
从 python 调用 shell 命令 - 子进程模块
import subprocess
# ps -ux | grep 1842 (Assuming 1842 is the process id. replace with process id you get)
p1 = subprocess.Popen(["ps", "-ux"], stdout=subprocess.PIPE)
p2 = subprocess.Popen(["grep", "1842"], stdin=p1.stdout, stdout=subprocess.PIPE)
p1.stdout.close() # Allow p1 to receive a SIGPIPE if p2 exits.
output = p2.communicate()[0]
print output
并解析输出以查看其内存利用率
关于python - 如何在 linux 中读取 python 进程的内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13807498/