方案:
經思考得出兩種處理方案:
- 通過讀取linux中的/proc目錄的相關文件獲取網絡數據的差值進而計算出當前網速
- 通過調用命令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