linux系統使用python擷取cpu資訊指令碼分享

來源:互聯網
上載者:User
linux系統使用python擷取cpu資訊指令碼分享

代碼如下:


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

簡單說明一下清單 1,讀取/proc/CPUinfo 中的資訊,返回 list,每核心一個 dict。其中 list 是一個使用方括弧括起來的有序元素集合。List 可以作為以 0 下標開始的數組。Dict 是 Python 的內建資料類型之一, 它定義了鍵和值之間一對一的關係。OrderedDict 是一個字典子類,可以記住其內容增加的順序。常規 dict 並不跟蹤插入順序,迭代處理時會根據鍵在散列表中儲存的順序來產生值。在 OrderedDict 中則相反,它會記住元素插入的順序,並在建立迭代器時使用這個順序。
可以使用 Python 命令運行指令碼 CPU1.py 結果見圖

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    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.