在python中处理密钥错误

2024-04-18 13:26:38 发布

您现在位置:Python中文网/ 问答频道 /正文

下面的函数解析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'

Tags: 函数selfipsessiontypestatuslinepassword
3条回答

这就解释了你所看到的问题。

当引用out['Peer']时会发生异常,因为out是一个空dict。要查看KeyError异常在哪里起作用,这是它在空dict上的操作方式:

out = {}
status = out['Peer']

抛出你看到的错误。下面显示如何处理out中未找到的密钥:

out = {}
try:
    status = out['Peer']
except KeyError:
    status = False
    print('The key you asked for is not here status has been set to False')

即使返回的对象是Falseout['Peer']仍然失败:

>>> out = False
>>> out['Peer']
Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    out['Peer']
TypeError: 'bool' object is not subscriptable

我不知道该如何继续,但处理session_status没有所需值的结果是前进的方向,而session_status函数中的try:except:块目前没有做任何事情。

你的例外不在正确的地方。正如你所说,你只需返回一个空字典和你的功能。异常正在尝试查找返回的空字典对象status = outertunnel['Peer']上的键。使用dict get函数检查它可能更容易。status = outertunnel.get('Peer',False)或者改进函数会话状态中的测试,比如测试长度来决定返回什么Falseif len(resultDict) == 0

函数session_status中没有发生KeyError,它发生在status = out['Peer']的脚本中。因此session_status中的try and except将不起作用。您应该为status = out['Peer']生成一个try and except

try:
    status = out['Peer']
except KeyError:
    print 'no Peer'

或:

status = out.get('Peer', None)

相关问题 更多 >