How to obtain the system memory usage in a linux system-python tutorial

Source: Internet
Author: User
This article describes how to obtain the system memory usage of python in a linux system, and describes how to obtain the system hardware information of Python on the Linux platform, for more information about how to obtain the system memory usage of python in linux, see the following example. Share it with you for your reference. The details are as follows:

"""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 upper application memory usage and return the total.Python's Popen() from subprocess module is used for spawning ps and awk."""import subprocessclass 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])

Save the above code as: memorymonitor. py

The call method is as follows:

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

I hope this article will help you with Python programming.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.