python psutil模塊,監控系統的信息,監控cpu、內存、網絡、磁盤使用情況;安裝psutil報錯

python psutil模塊,主要用來監控主機的性能指標,包括但不限於cpu使用率、內存使用率、網絡狀況、磁盤使用情況。
win10下通過pip安裝psutil模塊,我遇到了問題,主要是因爲我是python2.7與python3.5共存所引起的,所以,我建議大家,在多版本python共存的機器下,通過pip安裝python第三方庫,如果報錯,需要先考慮下手動安裝第三方庫。(具體怎麼手動安裝請百度,很簡單)

下面將部分代碼貼出,後期我會一直跟進,將psutil和motplotlib一起形成我自己的監控腳本。

請記住我,我是胖超人。

代碼奉上

#_*_coding=utf-8 _*
#__author__ = 'chubby_superman'


import psutil
import datetime
import time
print('-----------------------------系統基本信息---------------------------------------')
# 當前時間
now_time = time.strftime('%Y-%m-%d-%H:%M:%S', time.localtime(time.time()))
print(now_time)
# 系統啓動時間
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))
print('-----------------------------cpu信息---------------------------------------')
# 查看cpu物理個數的信息
print(u"物理CPU個數: %s" % psutil.cpu_count(logical=False))
print(u"CPU核心總數: %s" % psutil.cpu_count())
#CPU的使用率
cpu = (str(psutil.cpu_percent(1))) + '%'
print(u"cup使用率: %s" % cpu)
print('-----------------------------mem信息---------------------------------------')
#查看內存信息,剩餘內存.free  總共.total
#round()函數方法爲返回浮點數x的四捨五入值。
free = str(round(psutil.virtual_memory().free / (1024.0 * 1024.0 * 1024.0), 2))
total = str(round(psutil.virtual_memory().total / (1024.0 * 1024.0 * 1024.0), 2))
memory = int(psutil.virtual_memory().total - psutil.virtual_memory().free) / float(psutil.virtual_memory().total)
print(u"物理內存: %s G" % total)
print(u"剩餘物理內存: %s G" % free)
print(u"物理內存使用率: %s %%" % int(memory * 100))
print('-----------------------------網絡信息---------------------------------------')
#網卡,可以得到網卡屬性,連接數,當前流量等信息
net = psutil.net_io_counters()
bytes_sent = '{0:.2f} Mb'.format(net.bytes_recv / 1024 / 1024)
bytes_rcvd = '{0:.2f} Mb'.format(net.bytes_sent / 1024 / 1024)
print(u"網卡接收流量 %s 網卡發送流量 %s" % (bytes_rcvd, bytes_sent))

print('-----------------------------磁盤信息---------------------------------------')
io = psutil.disk_partitions()
#print("系統磁盤信息:" + str(io))

for i in io:
    try:
        o = psutil.disk_usage(i.device)
        ioo=psutil.disk_io_counters()
        print(ioo)
    except Exception as e:
        pass
    print("%s盤總容量:"%i.device + str(int(o.total / (1024.0 * 1024.0 * 1024.0))) + "G")
    print("已用容量:" + str(int(o.used / (1024.0 * 1024.0 * 1024.0))) + "G")
    print("可用容量:" + str(int(o.free / (1024.0 * 1024.0 * 1024.0))) + "G")

print('-----------------------------進程信息-------------------------------------')
# 查看系統全部進程
for pnum in psutil.pids():
    p = psutil.Process(pnum)
    print(u"進程名 %-20s  內存利用率 %-18s 進程狀態 %-10s 創建時間 %-10s " \
    % (p.name(), p.memory_percent(), p.status(), p.create_time()))




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章