0
我試圖用正則表達式解析文件內容,如下面的代碼所示。如果我在'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
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
文件內容(截斷爲只顯示一個塊)
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
請參閱http://stackoverflow.com/questions/2829528/whats-the-scope-of-a-python-variable-declared-in-an-if-statement – 2014-08-30 03:00:02
再次感謝。但是他們在那裏說If語句沒有它的範圍。所以這應該工作。沒有? – deepa 2014-08-30 03:17:41
你是說「系統名稱」可能在文件中出現多次? – whitebeard 2014-08-30 03:23:12