python在linux系统下获取系统内存使用情况的方法

yipeiwu_com6年前Python基础

本文实例讲述了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学习小技巧之利用字典的默认行为

本文介绍的是关于Python利用字典的默认行为的相关内容,分享出来供大家参考学习,下面来看看详细的介绍: 典型代码1: from collections import defaul...

Python3之读取连接过的网络并定位的方法

如下所示: #!/usr/bin/python # coding=utf-8 import json from urllib.request import urlopen from...

Python中使用Boolean操作符做真值测试实例

在Python中,任何类型的对象都可以做真值测试,并且保证返回True或者False。 以下几种值(不论类型)在真值测试中返回False: 1.None 2.False 3.任何类型的数...

Python多线程编程(七):使用Condition实现复杂同步

目前我们已经会使用Lock去对公共资源进行互斥访问了,也探讨了同一线程可以使用RLock去重入锁,但是尽管如此我们只不过才处理了一些程序中简单的同步现象,我们甚至还不能很合理的去解决使用...

对于Python异常处理慎用“except:pass”建议

翻译自StackOverflow中一个关于Python异常处理的问答。 问题:为什么“except:pass”是一个不好的编程习惯? 我时常在StackOverflow上看到有人评论关于...