python获取CPU和内存信息脚本

  • A+
所属分类:Linux  Python  编程&脚本
摘要

基于/proc 文件系统使用python来获取当前系统上的cpu和内存的信息

#!/usr/bin/env python
#-*- encoding: utf-8 -*-
#########################################################################
# File Name: cpu.py
# Author: LookBack
# Email: admin#dwhd.org
# Version:
# Created Time: 2015年08月17日 星期一 11时34分20秒
#########################################################################

from __future__ import print_function
from collections import OrderedDict
import pprint

def CPUinfo():
    ''' Return the information in /proc/CPUinfo
    as a dictionary in the following format:
    CPU_info['proc0']={...}
    CPU_info['proc1']={...}
    '''
    CPUinfo=OrderedDict()
    procinfo=OrderedDict()

    nprocs = 0
    with open('/proc/cpuinfo') as f:
        for line in f:
            if not line.strip():
                # end of one processor
                CPUinfo['proc%s' % nprocs] = procinfo
                nprocs=nprocs+1
                # Reset
                procinfo=OrderedDict()
            else:
                if len(line.split(':')) == 2:
                    procinfo[line.split(':')[0].strip()] = line.split(':')[1].strip()
                else:
                    procinfo[line.split(':')[0].strip()] = ''
            
    return CPUinfo

if __name__=='__main__':
    CPUinfo = CPUinfo()
    for processor in CPUinfo.keys():
        print(CPUinfo[processor]['model name'])

python获取CPU和内存信息脚本

#!/usr/bin/env python
#-*- encoding: utf-8 -*-
#########################################################################
# File Name: meminfo.py
# Author: LookBack
# Email: admin#dwhd.org
# Version:
# Created Time: 2015年08月17日 星期一 11时39分31秒
#########################################################################

from __future__ import print_function
from collections import OrderedDict

def meminfo():
    ''' Return the information in /proc/meminfo
    as a dictionary '''
    meminfo=OrderedDict()

    with open('/proc/meminfo') as f:
        for line in f:
            meminfo[line.split(':')[0]] = line.split(':')[1].strip()
    return meminfo

if __name__=='__main__':
    #print(meminfo())
    
    meminfo = meminfo()
    print('Total memory: {0}'.format(meminfo['MemTotal']))
    print('Free memory: {0}'.format(meminfo['MemFree']))

python获取CPU和内存信息脚本

lookback

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: