Reputation: 27
Here's a snippet of the config file:
[{u'sequenceNumber': 10, u'text': u'--- 10-999 are broad permits'},
{u'action': u'permit',
u'counterData': {},
u'log': False,
u'payload': {u'payload': []},
u'ruleFilter': {u'destination': {u'ip': u'0.0.0.0', u'mask': 0},
u'dscp': {u'match': False, u'value': 0},
u'dstPort': {u'maxPorts': 10,
u'oper': u'any',
u'ports': []},
u'established': False,
u'fragments': False,
u'gre': {u'protoMask': 0, u'protocol': 0},
u'gtp': {u'teid': 0, u'teidMask': 0},
u'icmp': {u'code': 65535, u'type': 65535},
u'nvgre': {u'protoMask': 0,
u'protocol': 0,
u'tni': 0,
u'tniMask': 0},
u'protocol': 2,
u'source': {u'ip': u'0.0.0.0', u'mask': 0},
u'srcPort': {u'maxPorts': 10,
u'oper': u'any',
u'ports': []},
u'standard': False,
u'tcpFlags': 0,
u'tracked': False,
u'ttl': {u'oper': u'any', u'value': 0},
u'userL4': {u'pattern': 0, u'patternMask': 0},
u'vlan': {u'id': 0,
u'innerId': 0,
u'innerMask': 0,
u'mask': 0},
u'vxlan': {u'vni': 0, u'vniMask': 0, u'vxlanValid': False}},
u'sequenceNumber': 20,
u'text': u'permit igmp any any'},
Snippet of code with problem.
Hereby, I'm trying to run through loop with KeyError
and NameError
handlers as not all lines in input have a value of 'src_mk'.
for seq in acl:
try:
src_mk = seq['ruleFilter']['source']['mask']
except (KeyError, NameError):
pass
print src_mk
I'm getting a NameError - name not defined
. I tired handling exception separately but it didn't work.
Traceback (most recent call last):
File "<stdin>", line 6, in <module>
NameError: name 'src_mk' is not defined
Upvotes: 0
Views: 66
Reputation: 4866
You need to define the variable outside the try-except
block beforehand. See in the comments section @Daniel Roseman's comment for WHY your code doesn't work
Something in this lines should work:
for seq in acl:
src_mk = None
try:
src_mk = seq['ruleFilter']['source']['mask']
except (KeyError,NameError):
pass
print src_mk # Note that if it is None it means there was an exception
Upvotes: 1