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利用ORM控制MongoDB(MongoEngine)的步骤全纪录

简介: MongoEngine 是一个Document-Object Mapper (想一下ORM, 但它是针对文档型数据库),Python通过它与MongoDB交互。你可能会说那PyM...

将python图片转为二进制文本的实例

将python图片转为二进制文本的实例

写在最前面: 我在研究机器学习的过程中,给的数据集是手写数字图片被处理后的由0,1表达的txt文件,今天写一写关于图片转化为二进制txt文件的python实践 在这里,我们使用pytho...

Python图像处理之图片文字识别功能(OCR)

Python图像处理之图片文字识别功能(OCR)

OCR与Tesseract介绍 将图片翻译成文字一般被称为光学文字识别(Optical Character Recognition,OCR)。可以实现OCR 的底层库并不多,目前很多库都...

Python计时相关操作详解【time,datetime】

本文实例讲述了Python计时相关操作。分享给大家供大家参考,具体如下: 内容目录: 1. 时间戳 2. 当前时间 3. 时间差 4. python中时间日期格式化符号 5. 例子 一、...

Python中print函数简单使用总结

Python中print函数简单使用总结

print函数是Python的入门,每一个学习python的人都绕不开这个函数,下面介绍一下这个函数的用法。 打开电脑,选择python软件,下面选择python 3.7为例进行介绍,点...