Linux system uses Python to get CPU information script sharing

Source: Internet
Author: User
Linux system uses Python to get CPU information script sharing

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 ')

Simply explain listing 1, read the information in the/proc/cpuinfo, and return to the list, one dict per core. Where list is a set of ordered elements enclosed in square brackets. The List can be used as an array starting with the 0 subscript. Dict is one of the built-in data types for Python, which defines the relationship between the key and the value. Ordereddict is a dictionary subclass that remembers the order in which its contents are incremented. Regular dict do not track the insertion order, and the iteration process generates values based on the order in which the keys are stored in the hash table. In Ordereddict, instead, it remembers the order in which elements are inserted and uses that order when creating iterators.
You can run the script using the Python command cpu1.py results See figure

  • 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: info-contact@alibabacloud.com 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.