本文介绍了如何使用Python将/proc/net/dev的输出解析为每个接口的key:value对?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
/proc/net/dev 在Linux上看起来像这样:
The output of /proc/net/dev on Linux looks like this:
Inter-| Receive | Transmit
face |bytes packets errs drop fifo frame compressed multicast|bytes packets errs drop fifo colls carrier compressed
lo:18748525 129811 0 0 0 0 0 0 18748525 129811 0 0 0 0 0 0
eth0:1699369069 226296437 0 0 0 0 0 3555 4118745424 194001149 0 0 0 0 0 0
eth1: 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
sit0: 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
如何使用Python将每个接口的输出解析为key:value对?我发现此论坛主题以使用Shell脚本实现该主题,并且有 Perl扩展,但我需要使用Python.
How can I use Python to parse this output into key:value pairs for each interface? I have found this forum topic for achieving it using shell scripting and there is a Perl extension but I need to use Python.
推荐答案
这是格式很漂亮的输入,您可以通过拆分每一行,然后为其创建一个字典,轻松获得列和数据列表.
this is pretty formatted input and you can easily get columns and data list by splitting each line, and then create a dict of of it.
这是一个不带正则表达式的简单脚本
here is a simple script without regex
lines = open("/proc/net/dev", "r").readlines()
columnLine = lines[1]
_, receiveCols , transmitCols = columnLine.split("|")
receiveCols = map(lambda a:"recv_"+a, receiveCols.split())
transmitCols = map(lambda a:"trans_"+a, transmitCols.split())
cols = receiveCols+transmitCols
faces = {}
for line in lines[2:]:
if line.find(":") < 0: continue
face, data = line.split(":")
faceData = dict(zip(cols, data.split()))
faces[face] = faceData
import pprint
pprint.pprint(faces)
它输出
{' lo': {'recv_bytes': '7056295',
'recv_compressed': '0',
'recv_drop': '0',
'recv_errs': '0',
'recv_fifo': '0',
'recv_frame': '0',
'recv_multicast': '0',
'recv_packets': '12148',
'trans_bytes': '7056295',
'trans_carrier': '0',
'trans_colls': '0',
'trans_compressed': '0',
'trans_drop': '0',
'trans_errs': '0',
'trans_fifo': '0',
'trans_packets': '12148'},
' eth0': {'recv_bytes': '34084530',
'recv_compressed': '0',
'recv_drop': '0',
'recv_errs': '0',
'recv_fifo': '0',
'recv_frame': '0',
'recv_multicast': '0',
'recv_packets': '30599',
'trans_bytes': '6170441',
'trans_carrier': '0',
'trans_colls': '0',
'trans_compressed': '0',
'trans_drop': '0',
'trans_errs': '0',
'trans_fifo': '0',
'trans_packets': '32377'}}
这篇关于如何使用Python将/proc/net/dev的输出解析为每个接口的key:value对?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!