Linux systems use python to get CPU information for script sharing

  • 2020-04-02 13:19:18
  • OfStack

Linux systems use python to get CPU information for script sharing


#!/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'])

To illustrate briefly, listing 1 reads the information in /proc/cpuinfo and returns the list, one dict per core. List is an ordered collection of elements enclosed in square brackets. A List can be an array that starts with a 0 index. Dict is one of Python's built-in data types that defines one-to-one relationships between keys and values. OrderedDict is a dictionary subclass that remembers the order in which its contents are added. Regular dict does not track the insertion order, but iterates to generate values based on the order in which the keys are stored in the hash table. In OrderedDict, by contrast, it remembers the order in which the elements were inserted and USES that order when creating the iterator.
You can use the Python command to run the script cpu1.py, as shown in the figure
< img border = 0 id = theimg onclick = window. The open this. (SRC) SRC = "/ / files.jb51.net/file_images/article/201401/20140115113630.jpg? 2014015113649 ">


Related articles: