2

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'
4
  • You are looking for a safe get method. Try using out.get('Peer', None). And the second argument to.get is the default that you would like. Commented Jun 29, 2017 at 0:47
  • @kiran.koduru im curious to know why exception KeyError: is not working Commented Jun 29, 2017 at 0:53
  • The line out = obj.session_status('tunnel0') ran ok and generated a dict. Is it possible that the except KeyError is only thrown when the dict is being built, not when it is referenced by out['Peer']? Commented Jun 29, 2017 at 1:06
  • @mjsqu no in this case,dictionary is empty. Commented Jun 29, 2017 at 1:12

3 Answers 3

4

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)
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.