Python 指令碼之獲取CPU資訊

Dus發表於2015-06-21
 1 #!/usr/bin/env Python
 2 from __future__ import print_function
 3 from collections import OrderedDict
 4 import pprint
 5  
 6 def CPUinfo():
 7     
 8 ''' Return the information in /proc/CPUinfo
 9     
10 as a dictionary in the following format:
11     
12 CPU_info['proc0']={...}
13     
14 CPU_info['proc1']={...}
15     
16 '''
17     CPUinfo=OrderedDict()
18     procinfo=OrderedDict()
19  
20     nprocs = 0
21     with open('/proc/CPUinfo') as f:
22         for line in f:
23             if not line.strip():
24                 
25 # end of one processor
26                 CPUinfo['proc%s' % nprocs] = procinfo
27                 nprocs=nprocs+1
28                 
29 # Reset
30                 procinfo=OrderedDict()
31             else:
32                 if len(line.split(':')) == 2:
33                     procinfo[line.split(':')[0].strip()] = line.split(':')[1].strip()
34                 else:
35                     procinfo[line.split(':')[0].strip()] = ''
36  
37     return CPUinfo
38  
39 if __name__=='__main__':
40     CPUinfo = CPUinfo()
41     for processor in CPUinfo.keys():
42         print(CPUinfo[processor]['model name'])

 

相關文章