1

I am trying to parse the a file content with regular expression as in the code below. If I print the system name inside 'IF' suite, it works. But If I try to do anywhere outside, its throwing name error. Any help would be really appreciated.

#!/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

Router1


#!/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

File Content (Truncated to show only one block)


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
deepa
  • 53
  • 1
  • 3

1 Answers1

0

If your first line doesn't contain "System Name", the systemname variable is not defined because you don't get inside the if block. But after the if block, you're still trying to print it... And it's not defined yet, hence your error.

Max Noel
  • 8,810
  • 1
  • 27
  • 35
  • Thanks. That was it. I created a empty list and appended the system name to it inside for loop. it works now. Thanks for the help. – deepa Aug 30 '14 at 03:38