python在linux下讀取網速

方案:

經思考得出兩種處理方案:

  1. 通過讀取linux中的/proc目錄的相關文件獲取網絡數據的差值進而計算出當前網速
  2. 通過調用命令ifconfig來獲取RX部分的數據值通過計算相應時間間隔的差值計算結果

思考

  • 在方案一中使用的是linux下的proc文件系統net目錄中的相關信息

在該方案中需要

  • 讀取對應的proc中的相關文件(/proc/net/dev)
  • 通過對字符串的操作獲取相關結果值
  • 通過延時函數得到時間差
  • 計算相關結果值
  • 在方案二中使用的是linux下的ifconfig命令中的網卡信息

在該方案中需要

  • 使用python對linux命令的簡單調用處理,這里使用os.popen函數處理
  • 正則re的簡單使用,這里需要正則匹配到對應的相關值,即可
  • 通過調用延時函數得到時間差
  • 計算相關結果值

結果

方案一示例代碼:

# 該部分代碼不夠健全
import sys, time

def net_speed(interface, is_download):
    # 獲取對應值
    which_num = 0 if is_download else 8
    # 讀取文件
    with open('/proc/net/dev') as f:
        lines = f.readlines()
    # 獲取結果值       
    for line in lines:
        if line.rstrip().split(':')[0].strip() == interface:
            return line.rstrip().split(':')[1].split()[which_num]     

if __name__ == '__main__':
    # 獲取參數
    interface = sys.argv[1] 
    is_upload = False if sys.argv[2]=='tx' else True
    get_time = int(sys.argv[3])
    # 計算部分
    begin = int(net_speed(interface, is_upload))
    time.sleep(get_time)
    end = int(net_speed(interface, is_upload))
    print begin, ":", end
    print (end-begin) /get_time/1024
    

方案二示例代碼:

# 該部分代碼不夠健全
import os, sys, time, re

# 獲取對應值
def get_total_bytes(interface, is_download):
    grep = 'RX bytes:' if is_download else 'TX bytes:'
    r = os.popen('ifconfig ' + interface + ' | grep "' + grep + '"').read()  
    total_bytes = re.findall(grep+'(.*?) \(',  r)
    return int(total_bytes[0])

if __name__ == '__main__':
    # 獲取參數
    interface = sys.argv[1] 
    is_upload = False if sys.argv[2]=='tx' else True
    get_time = int(sys.argv[3])
    # 計算部分
    begin = get_total_bytes(interface, is_upload)
    time.sleep(get_time)
    end = get_total_bytes(interface, is_upload)
    print (end-begin) /get_time/1024
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • linux資料總章2.1 1.0寫的不好抱歉 但是2.0已經改了很多 但是錯誤還是無法避免 以后資料會慢慢更新 大...
    數據革命閱讀 12,228評論 2 33
  • 1.命令格式:ifconfig [網絡設備] [參數] 2.命令功能: ifconfig 命令用來查看和配置網絡設...
    Nuuuu閱讀 3,802評論 0 12
  • Ubuntu的發音 Ubuntu,源于非洲祖魯人和科薩人的語言,發作 oo-boon-too 的音。了解發音是有意...
    螢火蟲de夢閱讀 99,571評論 9 467
  • Spring Cloud為開發人員提供了快速構建分布式系統中一些常見模式的工具(例如配置管理,服務發現,斷路器,智...
    卡卡羅2017閱讀 134,948評論 18 139
  • 同一個頁面效果,所有前端的開發人員都能實現。但是如何判定誰做的好,往往只能查看源碼進行進一步的確定。其實,還可以采...
    rocneal閱讀 1,236評論 0 0