【发布时间】:2016-06-07 17:52:16
【问题描述】:
我已经有一个 shell 脚本可以确定哪个进程正在使用交换以及使用多少,但我宁愿在 python 中执行此操作。
Shell one-liner(我在网上找到了这个脚本,但不记得它的出处):
for file in /proc/*/status ; do awk '/VmSwap|Name/{printf $2 " " $3}END{ print ""}' $file; done| sort -k 2 -n
上面的脚本基本上是通过 /proc 来查看进程名称、PID 以及它正在使用的交换空间量。
就 python 而言,psutil 中的 memory_maps() 看起来很有希望,但我找不到输出指定进程名称或 PID 的位置。
我想做什么?我正在尝试重写一堆旧的 shell 脚本,这些脚本将 CPU、内存、交换、使用等内容收集到一个大型 python 程序中。我知道我可以使用 subprocess 或 shellexec 调用这些脚本,但我想尽可能避免这种情况。
我在问什么?有一个更好的方法吗?我的方法全错了吗?
编辑:
我在 python3 方面取得了一些进展。这是我的代码。
#!/usr/bin/python3
import re
import glob
class searchfile:
def __init__(self, file, searchstring1, searchstring2, searchstring3, searchstring4 ):
self.file = file
self.searchstring1 = searchstring1
self.searchstring2 = searchstring2
self.searchstring3 = searchstring3
self.searchstring4 = searchstring4
class searchparm(searchfile):
def printsearch(self):
hand = open(self.file)
for line in hand:
line = line.rstrip()
if re.search(self.searchstring1, line):
print (line)
if re.search(self.searchstring2, line):
print (line)
if re.search(self.searchstring3, line):
print (line)
if re.search(self.searchstring4, line):
print (line)
for file in glob.glob('/proc/*/status'):
search_proc = searchparm(file, 'Name', 'VmSwap', 'Pid:', 'VmSize:' )
print("#########################################")
print("#########################################")
print(search_proc.printsearch())
【问题讨论】:
-
你可以从 Python 中读取
/proc/<pid>/status。