简体   繁体   English

分割字符串时索引超出范围

[英]Index Out of Range When Splitting String

I am attempting what seems like a simple operation-- parsing Cisco router outputs using simple string functions (like 'split'). 我正在尝试看似简单的操作-使用简单的字符串函数(如“ split”)解析Cisco路由器输出。 However, I keep getting an error that an index is out of range, and am not seeing why. 但是,我不断收到错误,指出索引超出范围,并且看不到原因。

Here is what I am starting with, simple "show ip int brief" output: 这是我从简单的“ show ip int brief”输出开始的内容:

Interface                  IP-Address      OK? Method Status                Protocol
GigabitEthernet0/0         unassigned      YES NVRAM  up                    up      
GigabitEthernet0/0.50      10.78.1.205     YES NVRAM  up                    up      
GigabitEthernet0/1         10.233.112.17   YES NVRAM  up                    up      
GigabitEthernet0/2         10.233.112.41   YES NVRAM  up                    up      
GigabitEthernet0/3         10.233.112.50   YES NVRAM  up                    up      
Loopback0                  10.233.112.130  YES NVRAM  up                    up      
Tunnel0                    10.233.112.130  YES unset  up                    up      
sdf-a-wan-rt-02#exit

And here is the code I am trying to run against it: 这是我要针对它运行的代码:

links = []
lines = output.split('\n')
for item in lines:
    fields = item.split()
    interface = fields[0]
    ipaddress = fields[1]
    linkstate = fields[4]
    prtcstate = fields[5]
    links.append([interface,ipaddress,linkstate,prtcstate])
print links

And here is the error I get: 这是我得到的错误:

Traceback (most recent call last):
File "C:\Users\dtruman\Documents\PROJECTS\DEVOPS - ITOC CoE\NETWORK    AUTOMATION\parse_output.py", line 32, in <module>
ipaddress = fields[1]

IndexError: list index out of range IndexError:列表索引超出范围

You basically have it, but you need to add a sanity check so that you make sure the data you're getting is what you'd expect. 基本上已经有了,但是您需要添加完整性检查,以确保所获取的数据符合预期。 I'd do something like this: 我会做这样的事情:

links = []
lines = output.split('\n')
for item in lines:
    fields = item.split()
    # make sure data is the proper length so you don't go out of bounds
    if len(fields) != 6:
        continue
    interface = fields[0]
    ipaddress = fields[1]
    linkstate = fields[4]
    prtcstate = fields[5]
    links.append([interface,ipaddress,linkstate,prtcstate])
print links

There are other ways you could do this, but this is the first one I could think of. 您还有其他方法可以执行此操作,但这是我想到的第一个方法。 This ensures that you have all 6 columns in the table populated for that line before any data is filled in. 这样可以确保在填写任何数据之前,已为该行填充了表中的所有6列。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM