正则表达式的名称错误

时间:2014-08-30 02:38:44

标签: python regex

我正在尝试使用正则表达式解析文件内容,如下面的代码所示。如果我在'IF'套件中打印系统名称,它可以工作。但是,如果我尝试在外面的任何地方做,它的投掷名称错误。任何帮助都会非常感激。

#!/usr/bin/python
import re
f=open("cdp-nei1.txt")
f=f.readlines()

for data in f:
    cdp_line = data.split("\n")
    for line in cdp_line:
        if "System Name" in line:
            systemname = re.search(r"System Name:(.+)",line)
            systemname =  systemname.group(1)
            print systemname

./ show-cdp.py

路由器1


#!/usr/bin/python
import re
f=open("cdp-nei1.txt")
f=f.readlines()

for data in f:
    cdp_line = data.split("\n")
    for line in cdp_line:
        if "System Name" in line:
            systemname = re.search(r"System Name:(.+)",line)
            systemname =  systemname.group(1)
        print systemname

***

 ./show-cdp.py 

Traceback (most recent call last):
  File "./show-cdp.py", line 12, in <module>
    print systemname
NameError: name 'systemname' is not defined

文件内容(截断只显示一个块)


Device ID:Router1
System Name: Router1

Interface address(es):
    IPv4 Address: 10.0.0.1
Platform: N5K-C5672UP, Capabilities: Router Switch IGMP Filtering Supports-STP-Dispute
Interface: mgmt0, Port ID (outgoing port): Ethernet101/1/47
Holdtime: 179 sec

Version:
Cisco Nexus Operating System (NX-OS) Software, Version 7.0(1)N1(1)

Advertisement Version: 2

Native VLAN: 1
Duplex: full

MTU: 1500
Physical Location: Somewhere,United States
Mgmt address(es):
    IPv4 Address: 10.0.0.1

1 个答案:

答案 0 :(得分:0)

如果您的第一行不包含&#34;系统名称&#34;,则系统名称变量未定义,因为您不会进入if块。但是在if块之后,你还在尝试打印它......而且它还没有定义,因此你的错误。