Handling key error in python

10,281

Solution 1

This explains the problem you're seeing.

The exception happens when you reference out['Peer'] because out is an empty dict. To see where the KeyError exception can come into play, this is how it operates on an empty dict:

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

Throws the error you're seeing. The following shows how to deal with an unfound key in 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')

Even if the returned object was False, out['Peer'] still fails:

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

I'm not sure how you should proceed, but dealing with the result of session_status not having the values you need is the way forward, and the try: except: block inside the session_status function isn't doing anything at the moment.

Solution 2

The KeyError did not happend in the function session_status,it is happend in your script at status = out['Peer'].So your try and except in session_status will not work.you should make a try and except for status = out['Peer']:

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

or :

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

Solution 3

Your exception is not in the right place. As you said you just return an empty dictionary with your function. The exception is trying to lookup the key on empty dictionary object that is returned status = outertunnel['Peer']. It might be easier to check it with the dict get function. status = outertunnel.get('Peer',False) or improve the test within the function session_status, like testing the length to decide what to return False if len(resultDict) == 0

Share:
10,281
mike
Author by

mike

Updated on June 14, 2022

Comments

  • mike
    mike almost 2 years

    The below function parses the cisco command output,stores the output in dictionary and returns the value for a given key. This function works as expected when the dictionary contains the output. However, if the command returns no output at all the length of dictionary is 0 and the function returns a key error . I have used exception KeyError: But this doesn't seem to work.

    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
    

    test script :

    obj = crypto('uname', 'ipaddr', 'password', 'router')
    out =  obj.session_status('tunnel0')
    status = out['Peer']
    print(status)
    

    Error

    Traceback (most recent call last):
      File "./test_parser.py", line 16, in <module>
        status = out['Peer']
    KeyError: 'Peer'