大家都知道,linux里一切皆为文件,在linux/unix的根目录下,有个/proc目录,这个/proc 是一种内核和内核模块用来向进程(process)发送信息的机制(所以叫做“/proc”),这个伪文件系统允许与内核内部数据结构交互,获取有关进程的有用信息,在运行中(on the fly)改变设置(通过改变内核参数)。与其他文件系统不同,/proc 存在于内存而不是硬盘中。proc 文件系统提供的信息如下:
"codetitle">复制代码 代码如下:
liujl@liujl-ThinkPad-Edge-E431:~/mybash$ cat /proc/cpuinfo
processor : 0
vendor_id : GenuineIntel
cpu family : 6
model : 58
model name : Intel(R) Core(TM) i5-3230M CPU @ 2.60GHz
stepping : 9
microcode : 0x15
cpu MHz : 1200.000
cache size : 3072 KB
physical id : 0
siblings : 4
core id : 0
cpu cores : 2
apicid : 0
。。。 。。。
复制代码 代码如下:
liujl@liujl-ThinkPad-Edge-E431:~/mybash$ cat /proc/meminfo
MemTotal: 3593316 kB
MemFree: 2145916 kB
Buffers: 93372 kB
Cached: 684864 kB
SwapCached: 0 kB
Active: 706564 kB
Inactive: 554052 kB
Active(anon): 483996 kB
Inactive(anon): 178388 kB
Active(file): 222568 kB
Inactive(file): 375664 kB
。。 。 。。。
那下面介绍如何通过python编程的方式获取需求的信息。
1、获取cpu的信息
复制代码 代码如下:
#! /usr/bin/env python
#Filename:CPU1.py
from __future__ import print_function
from collections import OrderedDict
import pprint
def CPUinfo():
'''Return the info in /proc/cpuinfo
as a dirctionary in the follow 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[{0}]={1}'.format(processor,CPUinfo[processor]['model name']))
运行如下:
复制代码 代码如下:
liujl@liujl-ThinkPad-Edge-E431:~/mypython$ python CPU1.py
CPUinfo[proc0]=Intel(R) Core(TM) i5-3230M CPU @ 2.60GHz
CPUinfo[proc1]=Intel(R) Core(TM) i5-3230M CPU @ 2.60GHz
CPUinfo[proc2]=Intel(R) Core(TM) i5-3230M CPU @ 2.60GHz
CPUinfo[proc3]=Intel(R) Core(TM) i5-3230M CPU @ 2.60GHz
2、获取内存信息
复制代码 代码如下:
#! /usr/bin/env python
#Filename:meminfo.py
from __future__ import print_function
from collections import OrderedDict
def meminfo():
'''return the info of /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__':
meminfo = meminfo()
print("Total memory:{0}".format(meminfo['MemTotal']))
print("Free memory:{0}".format(meminfo['MemFree']))
结果如下:
复制代码 代码如下:
liujl@liujl-ThinkPad-Edge-E431:~/mypython$ python meminfo.py
Total memory:3593316 kB
Free memory:2113712 kB