psutil获取CPU MEMORY DISK方法

本文介绍了一种使用Python和psutil库监控系统资源的方法,包括CPU状态、内存使用情况及磁盘信息。通过简单的函数调用,可以获取到CPU核心数、使用率,内存的总容量、已使用和剩余空间,以及磁盘的总大小、已用空间和使用率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import psutil
def get_CPU_state(time_count=1):
    return {'cpu_count': str(psutil.cpu_count(logical=False)),
            'cpu_percent': str(psutil.cpu_percent(time_count, 0)) + "%"}

 

def get_memory_state():
    phymem = psutil.virtual_memory()
    memory = dict()
    memory['total'] = str(int(phymem.total / 1024 / 1024)) + "M"
    memory['used'] = str(int(phymem.used / 1024 / 1024)) + "M"
    memory['free'] = str(int(phymem.free / 1024 / 1024)) + "M"
    memory['sum_mem'] = str(float(phymem.used / 1024 / 1024) / float(phymem.total / 1024 / 1024) * 100)[0:5] + "%"
    return memory

 

def get_disk_satate():
    diskinfo = psutil.disk_usage('/')
    disk = {
        'total': str(int(diskinfo.total / 1024 / 1024 / 1024)) + "G",
        'used': str(int(diskinfo.used / 1024 / 1024 / 1024)) + "G",
        'free': str(int(diskinfo.free / 1024 / 1024 / 1024)) + "G",
        'sum_disk': str(float(diskinfo.used / 1024 / 1024 / 1024) / float(diskinfo.total / 1024 / 1024 / 1024) * 100)[0:5] + "%"
    }
    return disk
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值