python - 根据python中的过滤列表检查列表
问题描述
该项目的初始范围是从 linux 服务器获取 nics 列表并检查启动状态,这部分按预期工作。现在我正在为其添加网络统计信息,并且现在当我尝试将它们组合起来时,它能够在单个界面上工作,我遇到了一些我正在尝试进行排序的问题。
当我运行以下代码时,出现此错误:文件“test.py”,第 58 行,在 RX = float(STATS[0]) IndexError: list index out of range
SIOCGIFFLAGS = 0x8913
null256 = '\0'*256
filtered_interfaces = list(filter(lambda i: re.findall(r'enp[0-3]n',i), interfaces()))
STATS = []
# Create a socket so we have a handle to query
s = socket(AF_INET, SOCK_DGRAM)
def getNicStatus():
# Call ioctl( ) to get the flags for the given interface
for interface in filtered_interfaces:
result = fcntl.ioctl(s.fileno( ), SIOCGIFFLAGS, interface + null256)
# Extract the interface's flags from the return value
flags, = struct.unpack('H', result[16:18])
# Check "UP" bit and print a message
up = flags & 1
print(('DOWN', 'UP')[up], interface)
# Return a value suitable for shell's "if"
sys.exit(not up)
#getNicStatus()
def rx():
ifstat = open('/proc/net/dev').readlines()
for interface in ifstat:
if interface in filtered_interfaces:
stat = float(interface.split()[1])
STATS[0:] = [stat]
def tx():
ifstat = open('/proc/net/dev').readlines()
for interface in ifstat:
if filtered_interfaces == interface:
stat = float(interface.split()[9])
STATS[1:] = [stat]
print 'In Out'
rx()
tx()
while True:
time.sleep(1)
rxstat_o = list(STATS)
rx()
tx()
RX = float(STATS[0])
RX_O = rxstat_o[0]
TX = float(STATS[1])
TX_O = rxstat_o[1]
RX_RATE = round((RX - RX_O)/1024/1024,3)
TX_RATE = round((TX - TX_O)/1024/1024,3)
print RX_RATE ,'MB ',TX_RATE ,'MB'
如果我对接口值进行硬编码,它会按预期工作,请在此处编写代码:
INTERFACE = 'enp3n9'
STATS = []
print 'Interface:',INTERFACE
def rx():
ifstat = open('/proc/net/dev').readlines()
for interface in ifstat:
if INTERFACE in interface:
stat = float(interface.split()[1])
STATS[0:] = [stat]
def tx():
ifstat = open('/proc/net/dev').readlines()
for interface in ifstat:
if INTERFACE in interface:
stat = float(interface.split()[9])
STATS[1:] = [stat]
print 'In Out'
rx()
tx()
while True:
time.sleep(1)
rxstat_o = list(STATS)
rx()
tx()
RX = float(STATS[0])
RX_O = rxstat_o[0]
TX = float(STATS[1])
TX_O = rxstat_o[1]
RX_RATE = round((RX - RX_O)/1024/1024,3)
TX_RATE = round((TX - TX_O)/1024/1024,3)
print RX_RATE ,'MB ',TX_RATE ,'MB'
有人可以为我指出正确的方向,让它遍历所有的 nics 吗?
解决方案
推荐阅读
- python-3.x - 如何修改python中的文本?
- python - 更快的实现 python3 -leetcode 问题集-
- reactjs - index.html 中的脚本文件在主页上工作,但在其他子屏幕上不工作
- javascript - 如何将 webpack 样式加载器随机数属性添加到 craco 配置
- python - 将文件分配给列表
- python - 如何将此 URL 参数字典编码为有效字符串?
- javascript - 比较JavaScript中的两个字符串而不考虑顺序?
- .net - .NET 5 (NET Core 5) 使用针对 .NET Framework 4 构建的库 - 兼容性垫片?
- java - 如何验证 selenium + java 中的排序?
- python - 如何按流派或标题按字母顺序对文本文件中的列表进行排序?