以下のコードのように、正規表現を使用してファイルの内容を解析しようとしています。'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
ファイルの内容(1つのブロックのみを表示するために切り捨てられます)
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
最初の行に「SystemName」が含まれていない場合、ifブロック内に入らないため、systemname変数は定義されていません。しかし、ifブロックの後、あなたはまだそれを印刷しようとしています...そしてそれはまだ定義されていないので、あなたのエラーです。
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加