处理python中的键错误 [英] Handling key error in python

查看:37
本文介绍了处理python中的键错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下函数解析Cisco命令输出,将输出存储在字典中,并返回给定键的值。当字典包含输出时,此函数按预期工作。但是,如果该命令始终不返回任何输出,则字典长度为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('
') 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是空词典。要查看KeyError异常可以在何处发挥作用,下面是它在空字典上的操作方式:

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没有您需要的值的结果是前进的方向,try:except:函数中的try:except:挡路目前没有任何作用。

这篇关于处理python中的键错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆