In [15]: from subprocess import Popen,PIPE
In [16]: p=Popen(['pidof','httpd'],stdout=PIPE,stderr=PIPE)
In [22]: p.stdout.read().split()
Out[22]:
['13712',
'13711',
'13710',
'13709',
'13708',
'13707',
'13706',
'13705',
'13698']
测试
[root@133 systeminformation]# vim 10_httpd.py
#!/usr/bin/env python
import os
import subprocess
from subprocess import Popen,PIPE
def getPid():
p = Popen(['pidof', 'httpd'], stdout=PIPE,stderr=PIPE)
pids = p.stdout.read().split()
print pids #打印httpd进称号
return pids
def parsePidFile(pids):
sum = 0
for i in pids:
fn = os.path.join('/proc/',i,'status')
print fn #打印文件路径
with open(fn) as fd:
for line in fd:
if line.startswith('VmRSS'):
http_mem = int(line.split()[1])
print http_mem #打印每个进称占用的内存,单位k
sum += http_mem #计算httpd占用的总内存
break
return sum
计算所有的httpd进称占用的物理内存,(VmRSS)的大小,占所有物理内存的比例。
/proc/meminfo
[root@133 systeminformation]# vim /proc/meminfo
MemTotal: 20455792 kB
[root@133 systeminformation]# vim 10_httpd.py
#!/usr/bin/env python
import os
import subprocess
from subprocess import Popen,PIPE
def getPid():
p = Popen(['pidof', 'httpd'], stdout=PIPE,stderr=PIPE)
pids = p.stdout.read().split()
return pids
def parsePidFile(pids):
sum = 0
for i in pids:
fn = os.path.join('/proc/',i,'status')
with open(fn) as fd:
for line in fd:
if line.startswith('VmRSS'):
http_mem = int(line.split()[1])
sum += http_mem
break
return sum
def total_mem(f):
with open(f) as fd:
for line in fd:
if line.startswith('MemTotal'):
total_mem = int(line.split()[1])
return total_mem
if __name__ == '__main__':
pids = getPid()
http_mem = parsePidFile(pids)
total_mem = total_mem('/proc/meminfo')
print "Apache memory is: %s KB" % http_mem
print "Total memory is: %s KB" % total_mem
print "Percent: %.2f%%" % (http_mem/float(total_mem)*100)
[root@133 systeminformation]# python 10_httpd.py
Apache memory is: 435760 KB
Total memory is: 20455792 KB
Percent: 2.13%