Linux system uses Python to get CPU information script sharing
Copy Code code as follows:
#!/usr/bin/env Python
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 '))
Simply explain listing 1, read the information in/proc/cpuinfo, and return to list, a dict per core. Where list is a collection of ordered elements enclosed in square brackets. The List can be used as an array starting with a 0 subscript. Dict is one of the built-in data types of Python, which defines a one-to-one relationship between keys and values. Ordereddict is a dictionary subclass that remembers the order in which content is added. Regular dict do not track the insertion order, and iterations generate values based on the order in which the keys are stored in the hash table. In Ordereddict, in contrast, it remembers the order in which elements are inserted and uses this order when creating iterators.
You can run the script using the Python command cpu1.py results are shown in the figure