圆月山庄资源网 Design By www.vgjia.com

本文实例讲述了python在linux系统下获取系统内存使用情况的方法。分享给大家供大家参考。具体如下:

"""
Simple module for getting amount of memory used 
by a specified user's processes on a UNIX system.
It uses UNIX ps utility to get the memory usage for 
a specified username and pipe it to awk for summing up
per application memory usage and return the total.
Python's Popen() from subprocess module is used 
for spawning ps and awk.
"""
import subprocess
class MemoryMonitor(object):
  def __init__(self, username):
    """Create new MemoryMonitor instance."""
    self.username = username
  def usage(self):
    """Return int containing memory used by user's processes."""
    self.process = subprocess.Popen("ps -u %s -o rss | awk '{sum+=$1} END {print sum}'" % self.username,
                    shell=True,
                    stdout=subprocess.PIPE,
                    )
    self.stdout_list = self.process.communicate()[0].split('\n')
    return int(self.stdout_list[0])

将上面的代码保存为:memorymonitor.py

调用方法如下:

from memorymonitor import MemoryMonitor
memory_mon = MemoryMonitor('username')
used_memory = memory_mon.usage()

希望本文所述对大家的Python程序设计有所帮助。

标签:
python,linux系统,系统内存,使用情况

圆月山庄资源网 Design By www.vgjia.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
圆月山庄资源网 Design By www.vgjia.com