Python psutil模組簡單使用執行個體

來源:互聯網
上載者:User
安裝很簡單

代碼如下:


pip install psutil

官網地址為:
https://pythonhosted.org/psutil/ (文檔上有詳細的api)
github地址為:
https://github.com/giampaolo/psutil/

psutil比較好的地方,一個是跨平台,不需要切換平台的時候在重新開放了,另外一個好處的工具集中CPU, memory, disks, network,這些資訊都可以獲得到。
可以用來做系統監控,效能分析,進程管理。 可以支援的系統有Linux, Windows, OSX, FreeBSD and Sun Solaris,32和64位系統都支援,同時支援pyhton2.4到3.4。

為了看看跨平台的好不好用,在windows實驗下

代碼如下:


#-*- coding: utf-8 -*-
#python2.7x
#author: orangleliu@gmail.com 2014-12-12
#psutiltest.py
'''''
照著教程簡單學習下psutil的使用,windows下試試
'''
import psutil
import datetime

#查看cpu的資訊
print u"CPU 個數 %s"%psutil.cpu_count()
print u"物理CPU個數 %s"%psutil.cpu_count(logical=False)
print u"CPU uptimes"
print psutil.cpu_times()
print ""

#查看記憶體資訊
print u"系統總記憶體 %s M"%(psutil.TOTAL_PHYMEM/1024/1024)
print u"系統可用記憶體 %s M"%(psutil.avail_phymem()/1024/1024)
mem_rate = int(psutil.avail_phymem())/float(psutil.TOTAL_PHYMEM)
print u"系統記憶體使用量率 %s %%"%int(mem_rate*100)

#系統啟動時間
print u"系統啟動時間 %s"%datetime.datetime.fromtimestamp(psutil.boot_time()).strftime("%Y-%m-%d %H:%M:%S")

#系統使用者
users_count = len(psutil.users())
users_list = ",".join([ u.name for u in psutil.users()])
print u"當前有%s個使用者,分別是%s"%(users_count, users_list)

#網卡,可以得到網卡屬性,串連數,當前流量等資訊
net = psutil.net_io_counters()
bytes_sent = '{0:.2f} kb'.format(net.bytes_recv / 1024)
bytes_rcvd = '{0:.2f} kb'.format(net.bytes_sent / 1024)
print u"網卡接收流量 %s 網卡發送流量 %s"%(bytes_rcvd, bytes_sent)

#進程 進程的各種詳細參數
#磁碟 磁碟的使用量等等


從這個簡單的案例中可見psuti的強大,在window上也如此好用,做系統資料擷取非常合適。
如果需要使用請詳細參考官方文檔。
gist上也有些程式碼片段可以參考https://gist.github.com/search?q=psutil
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.