首页 > 解决方案 > 根据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 吗?

标签: pythonlinuxloops

解决方案


推荐阅读