以下の関数は、ciscoコマンドの出力を解析し、出力を辞書に格納し、指定されたキーの値を返します。この関数は、ディクショナリに出力が含まれている場合に期待通りに機能します。ただし、辞書の長さがすべて0であるときにコマンドが何も出力しない場合、関数はキーエラーを返します。私は使用したexception KeyError:
しかし、これは動作していないようです。Pythonのキーエラーの処理
from qa.ssh import Ssh
import re
class crypto:
def __init__(self, username, ip, password, machinetype):
self.user_name = username
self.ip_address = ip
self.pass_word = password
self.machine_type = machinetype
self.router_ssh = Ssh(ip=self.ip_address,
user=self.user_name,
password=self.pass_word,
machine_type=self.machine_type
)
def session_status(self, interface):
command = 'show crypto session interface '+interface
result = self.router_ssh.cmd(command)
try:
resultDict = dict(map(str.strip, line.split(':', 1))
for line in result.split('\n') if ':' in line)
return resultDict
except KeyError:
return False
テストスクリプト:
obj = crypto('uname', 'ipaddr', 'password', 'router')
out = obj.session_status('tunnel0')
status = out['Peer']
print(status)
エラー
Traceback (most recent call last):
File "./test_parser.py", line 16, in <module>
status = out['Peer']
KeyError: 'Peer'
あなたは安全な 'get'メソッドを探しています。 'out.get( 'Peer'、None)'を使って試してください。 '.get'の2番目の引数は、あなたが望むデフォルトです。 –
@ kiran.koduruなぜ例外KeyError:が動作していないか知りたい – mike
'out = obj.session_status( 'tunnel0')'行が正常に実行され、dictが生成されました。 'except KeyError'は、' out ['Peer'] 'によって参照されているときではなく、辞書が構築されているときにだけスローされる可能性がありますか? – mjsqu