Handling key error in python(处理python中的键错误)
                            本文介绍了处理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')
即使返回的对象是False,out['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中的键错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
				 沃梦达教程
				
			本文标题为:处理python中的键错误
 
				
         
 
            
        基础教程推荐
             猜你喜欢
        
	     - 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01
- 修改列表中的数据帧不起作用 2022-01-01
- 求两个直方图的卷积 2022-01-01
- 包装空间模型 2022-01-01
- 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
- Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
- 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
- 在Python中从Azure BLOB存储中读取文件 2022-01-01
- PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
- PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
 
    	 
    	 
    	 
    	 
    	 
    	 
    	 
    	 
				 
				 
				 
				