Linux system uses Python to get CPU information script sharing _python

Source: Internet
Author: User

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

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.