Use python to obtain cpu information for script sharing in linux

Source: Internet
Author: User
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 ()
If len (line. split (':') = 2:
Procinfo [line. split (':') [0]. strip ()] = line. split (':') [1]. strip ()
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 The result is shown in the figure below.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.