Python的基礎是非常重要的,。基礎是處理一切問題的基石,。如果查看Linux操作系統(tǒng)的負載情況,,我們用Python實現(xiàn)的原理是通過查看文件`/proc/loadavg` 的內(nèi)容去實現(xiàn)。 $cat /proc/loadavg 0.00 0.01 0.05 1/187 11193
#!/usr/bin/env python3loadavg = {}def load_stat(): f = open('/proc/loadavg') con = f.read().split() f.close() loadavg['lavg_1']=con[0] # 1分鐘負載 loadavg['lavg_5']=con[1] # 5分鐘負載 loadavg['lavg_15']=con[2] #15分鐘負載 return loadavgload_stat()print(loadavg)#輸出load1的值print('load1:'+loadavg['lavg_1']) 為了能夠讀取 `/proc/loadavg` 里的文件,,我們可以定義一個函數(shù) load_stat()函數(shù) 用來打開文件和關閉,。然后讀取里面的文件存到一個數(shù)據(jù)結構里,當然數(shù)據(jù)結構你可以采用List,,也可以采用Dict,,筆者用Dict去存放這些內(nèi)容。#!/usr/bin/env python3 f = open('/proc/loadavg') con = f.read() #con = f.read().split() # 調試代碼 print(con) f.close() 我們使用split函數(shù)用于對字符串數(shù)據(jù)進行切片然后放到一個列表里面去,。最后我們把列表對應的索引的值又存放到一個新的字典里去,。如果要存放在字典。所以我們必須在開頭定義好一個空的字典結構,。$ python3 load.py {'lavg_1': '0.00', 'lavg_5': '0.01', 'lavg_15': '0.05'}load1:0.00 最后我們輸出的是一個字典,,那么我們要取負載情況就方便多了計算內(nèi)存的利用率原理是需要讀取的是/proc/meminfo文件,該文件的結構比較清晰,,不需要額外的介紹,,需要知道的是內(nèi)存的使用總量為used = total - free - buffers - cached。with open('/proc/meminfo') as meminfo: for i in meminfo: if i.startswith('MemTotal'): total_mem = i.split() # print(total_mem) total_mem = total_mem[1] continue elif i.startswith('MemAvailable'): free_mem = i.split() free_mem = free_mem[1] continue elif i.startswith('Buffers'): buff_mem = i.split() buff_mem= buff_mem[1] elif i.startswith('Cached'): cache_mem = i.split() cache_mem = cache_mem[1] break else: pass print('total_mem:'+total_mem),、 # 輸出可用內(nèi)存 # print('free_mem:'+free_mem) # 輸出buffer內(nèi)存 # print('buff_mem:'+buff_mem) # print('cache_mem'+cache_mem) # print(type(free_mem)) # used_mem = total_mem-free_mem-buff_mem-cache_mem used_mem = float(total_mem)-float(free_mem)-float(buff_mem)-float(cache_mem) print(used_mem) # 使用內(nèi)存 print(used_mem) #計算內(nèi)存使用率 res = used_mem/float(total_mem) # 輸出內(nèi)存使用率值 print(res) 上面的代碼首先是去打開 文件`/proc/meminfo`,然后使用for循環(huán)遍歷文件里的內(nèi)容,。使用的是字符串的`startswith` 方法。得到的內(nèi)容使用字符串的`split` 方法切割形成一個列表,。Python startswith() 方法用于檢查字符串是否是以指定子字符串開頭,如果是則返回 True,,否則返回 False,。如果參數(shù) beg 和 end 指定值,,則在指定范圍內(nèi)檢查。['MemTotal:', '1863224', 'kB'] 從列表內(nèi)容來看,,索引為1的值1863224,,就是MemTotal(總內(nèi)存的數(shù)值)。然后一系列的多條件的if else 語句來分別得到,,total_mem,,buff_mem,free_mem,,cache_mem的值并賦值給變量,。當把所有的值取到之后使用break 語句退出循環(huán)。代碼`used_mem = float(total_mem)-float(free_mem)-float(buff_mem)-float(cache_mem)`,因為我們得到的total_mem 等內(nèi)存是字符串沒辦法進行數(shù)學運算,,所以需要轉成浮點數(shù)進行數(shù)學運算,。最后使用除法`res = used_mem/float(total_mem)` 來計算內(nèi)存使用率。為了能獲取網(wǎng)卡的流量我們使用 `psutil` 會更加方便,,官方文檔:https://psutil./en/latestpsutil是個跨平臺庫,,能夠輕松實現(xiàn)獲取系統(tǒng)運行的進程和系統(tǒng)利用率,包括CPU,、內(nèi)存,、磁盤、網(wǎng)絡等信息,。之前的查看Linux系統(tǒng)的負載和內(nèi)存使用情況實現(xiàn)都可以用`psutil` 庫去實現(xiàn),。#獲取網(wǎng)卡eth0的IP地址 >>> psutil.net_if_addrs()['eth0'][0].address '192.168.137.16' #子網(wǎng)掩碼 >>> psutil.net_if_addrs()['eth0'][0].netmask '255.255.255.0' #查看網(wǎng)卡是否開啟 >>> psutil.net_if_stats()['eth0'].isup True #查看網(wǎng)卡的速率,命令有ifconfig,,ethtool >>> psutil.net_if_stats()['eth0'].speed #單位 Mb/s 查看cpu的使用情況我們使用`psutil` 更加方便,。#!/usr/bin/env python3# @Author : knightimport psutil#檢測cpu的使用率#psutil獲取系統(tǒng)cpu使用率的方法是cpu_percent(),其有兩個參數(shù),分別是interval和percpu,interval指定的是計算cpu使用率的時間間隔,,percpu則指定是選擇總的使用率還是每個cpu的使用率print(psutil.cpu_percent(interval=20,percpu=False))#查看物理cpu的個數(shù)print(psutil.cpu_count(logical=False))#查看cpu的總使用情況print(psutil.cpu_times_percent())# #每個cpu的使用情況print(psutil.cpu_times_percent(percpu=True))#cpu的使用率psutil.cpu_percent() ```我們執(zhí)行上面的腳本,,執(zhí)行結果如下:```$python3 test.py 2.84scputimes(user=1.0, nice=0.0, system=1.8, idle=97.2, iowait=0.0, irq=0.0, softirq=0.0, steal=0.0, guest=0.0, guest_nice=0.0)[scputimes(user=0.0, nice=0.0, system=1.0, idle=98.0, iowait=1.0, irq=0.0, softirq=0.0, steal=0.0, guest=0.0, guest_nice=0.0), scputimes(user=1.0, nice=0.0, system=2.0, idle=97.0, iowait=0.0, irq=0.0, softirq=0.0, steal=0.0, guest=0.0, guest_nice=0.0), scputimes(user=0.0, nice=0.0, system=2.0, idle=97.0, iowait=0.0, irq=0.0, softirq=0.0, steal=0.0, guest=0.0, guest_nice=0.0), scputimes(user=0.0, nice=0.0, system=2.0, idle=97.0, iowait=0.0, irq=0.0, softirq=0.0, steal=0.0, guest=0.0, guest_nice=0.0), scputimes(user=2.0, nice=0.0, system=1.0, idle=97.0, iowait=0.0, irq=0.0, softirq=0.0, steal=0.0, guest=0.0, guest_nice=0.0), scputimes(user=0.0, nice=0.0, system=2.0, idle=98.0, iowait=0.0, irq=0.0, softirq=0.0, steal=0.0, guest=0.0, guest_nice=0.0), scputimes(user=1.0, nice=0.0, system=1.0, idle=98.0, iowait=0.0, irq=0.0, softirq=0.0, steal=0.0, guest=0.0, guest_nice=0.0), scputimes(user=3.0, nice=0.0, system=3.0, idle=93.0, iowait=0.0, irq=0.0, softirq=0.0, steal=0.0, guest=0.0, guest_nice=0.0)] 以上的代碼能正常的去獲取cpu的負載情況,cpu狀態(tài)和信息,,內(nèi)存信息,,網(wǎng)絡信息和流量等。(1)我們再拓展一下使用`psutil` 庫去實現(xiàn) 之前的cpu是使用情況,。具體的實現(xiàn)如下:使用psutil獲取物理內(nèi)存和交換內(nèi)存信息,,分別使用:>>> psutil.virtual_memory() svmem(total=8589934592, available=2866520064, percent=66.6, used=7201386496, free=216178688, active=3342192640, inactive=2650341376, wired=1208852480) >>> psutil.swap_memory() sswap(total=1073741824, used=150732800, free=923009024, percent=14.0, sin=10705981440, sout=40353792) 返回的是字節(jié)為單位的整數(shù),可以看到,,總內(nèi)存大小是8589934592 = 8 GB,,已用7201386496 = 6.7 GB,使用了66.6%,。而交換區(qū)大小是1073741824 = 1 GB(2)我們要獲取系統(tǒng)的負載情況,,我們還可以使用os模塊去實現(xiàn)具體代碼如下, 下面的代碼我們是通過ipython進行交互的,,在linux命令行交互式調試過程中。具體的Ipython的安裝方法為`pip3 install ipython`,。In [12]: import os In [13]: os.getloadavg() Out[13]: (0.09, 0.27, 0.29) 多維度詳解 手把手入門
|