下面的函数解析cisco命令输出,将输出存储在字典中,并返回给定密钥的值。当字典包含输出时,此函数按预期工作。但是,如果命令不返回任何输出,那么dictionary的长度为0,并且函数返回一个键错误。我用过exception KeyError:
,但这似乎不起作用。
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'
这就解释了你所看到的问题。
当引用
out['Peer']
时会发生异常,因为out
是一个空dict。要查看KeyError异常在哪里起作用,这是它在空dict上的操作方式:抛出你看到的错误。下面显示如何处理
out
中未找到的密钥:即使返回的对象是
False
,out['Peer']
仍然失败:我不知道该如何继续,但处理
session_status
没有所需值的结果是前进的方向,而session_status
函数中的try:
except:
块目前没有做任何事情。你的例外不在正确的地方。正如你所说,你只需返回一个空字典和你的功能。异常正在尝试查找返回的空字典对象
status = outertunnel['Peer']
上的键。使用dict get函数检查它可能更容易。status = outertunnel.get('Peer',False)
或者改进函数会话状态中的测试,比如测试长度来决定返回什么False
if len(resultDict) == 0
函数
session_status
中没有发生KeyError
,它发生在status = out['Peer']
的脚本中。因此session_status
中的try and except
将不起作用。您应该为status = out['Peer']
生成一个try and except
:或:
相关问题 更多 >
编程相关推荐