This article describes how to use python to obtain cpu information scripts in linux. For more information, see how to use python to obtain cpu information in linux.
The code is 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'])
A brief description of listing 1 reads the information in/proc/CPUinfo and returns a list with a dict for each core. List is a set of ordered elements enclosed by square brackets. List can be used as an array starting with 0 subscript. Dict is one of Python's built-in data types. it defines the one-to-one relationship between keys and values. OrderedDict is a dictionary subclass that remembers the order in which the content is added. Conventional dict does not track the insertion sequence. during iteration, values are generated based on the order in which keys are stored in the hash table. In OrderedDict, it remembers the order of element insertion and uses this order when creating the iterator.
You can use the Python command to run the script CPU1.py. The result is shown in the figure below.