python实现监测CPU、内存、硬盘状况,psutil

作者环境为python3

GetHardwareInfo.py

#!/usr/bin/python
# -*- coding: UTF-8 -*-
import psutil
import os


#infomation of Hardware, include disk, CPU, RAM
class HardwareInfo(object):
    def __init__(self):
        self.disk_total = 0
        self.disk_used = 0
        self.disk_free = 0
        self.disk_percent = 0
        self.ram_total = 0
        self.ram_used = 0
        self.ram_available = 0
        self.ram_percent = 0
        self.cpu_percent = 0
        self.temperatures = 0
        self.file_size = 0

def getHardwareInfo(disk, file_path):
    d = psutil.disk_usage(disk)
    h = HardwareInfo()
    h.disk_total = int(d.total/1024/1024)
    h.disk_used = int(d.used/1024/1024)
    h.disk_free = int(d.free/1024/1024)
    h.disk_percent = d.percent

    r = psutil.virtual_memory()
    h.ram_total = int(r.total/1024/1024)
    h.ram_used = int(r.used/1024/1024)
    h.ram_available = int(r.available/1024/1024)
    h.ram_percent = r.percent

    h.cpu_percent = psutil.cpu_percent()

    h.temperatures = psutil.sensors_temperatures()

    h.file_size = os.path.getsize(file_path)/1024/1024
    return h

test.py

#!/usr/bin/python
# -*- coding: UTF-8 -*-
''' 配置psutil $sudo pip install psutil print(ghi.getHardwareInfo('/', '/home/room304/lichengyuan/make_voc2007.py').disk_used) 第一个参数为硬盘编号,可以通过psutil.disk_partitions()获得 第二个参数为需要监测大小的文件路径 s = ghi.getHardwareInfo('/', '/home/room304/lichengyuan/make_voc2007.py') 所有参数单位为M s.disk_total 硬盘大小 s.disk_used 已使用硬盘大小 s.disk_free 未使用硬盘大小 s.disk_percent 硬盘使用率 s.ram_total 内存大小 s.ram_used 已使用内存大小 s.ram_available 可以使用的内存大小 s.ram_percent 内存使用率 s.cpu_percent cpu使用率 s.temperatures 硬件温度,结构体 s.file_size 监测的文件大小 '''
import GetHardwareInfo as ghi
print(ghi.getHardwareInfo('/', '/home/xx/xx/xx.py').disk_used)

你可能感兴趣的:(python3)