python在linux系統(tǒng)下獲取系統(tǒng)內存使用情況的方法
更新時間:2015年05月11日 09:54:44 作者:work24
這篇文章主要介紹了python在linux系統(tǒng)下獲取系統(tǒng)內存使用情況的方法,涉及Python在Linux平臺下獲取系統(tǒng)硬件信息的相關技巧,需要的朋友可以參考下
本文實例講述了python在linux系統(tǒng)下獲取系統(tǒng)內存使用情況的方法。分享給大家供大家參考。具體如下:
""" 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程序設計有所幫助。
相關文章
解決pytorch DataLoader num_workers出現的問題
今天小編就為大家分享一篇解決pytorch DataLoader num_workers出現的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-01-01詳解Python常用標準庫之時間模塊time和datetime
time和datetime是Python中常用的兩個時間模塊,本文將通過示例詳細為大家講講二者的使用方法,感興趣的小伙伴可以跟隨小編一起學習學習2022-05-05