In the below Python script, the getLogMapping() method may return a value of zero. In this event, I'm naturally unable to reference attributes from the re_mapping class. What I'm interested in doing (and this is only a cosmetic thing) is to respond via Python that this attribute is unavailable. I'm unable to figure out how to do this w/the "try:" and "else:" exception handlers. The error that gets raised is:
AttributeError: 'int' object has no attribute 'log_filename'
-----
class re_mapping():
"""Class: re_mapping - an instance of a mapping between a log file and a regular expression term from the re_finding class
"""
log_filename = ""
line_number_in_log_file = 0
complete_line_in_log_file = ""
class re_finding():
"""Class: re_finding - a discovery/finding matrix using a regular expression from an input source (e.g. a log file)
"""
def addLogMapping(self, logFileName, lineNumberInLogFile, lineInLogFile):
newLogEntry = re_mapping()
newLogEntry.log_filename = logFileName
newLogEntry.line_number_in_log_file = lineNumberInLogFile
newLogEntry.complete_line_in_log_file = lineInLogFile
self.log_mapping.append(newLogEntry)
def getSizeOfMapping(self):
return len(self.log_mapping)
def getLogMapping(self, mappingIndex):
if mappingIndex > (len(self.log_mapping) - 1) or mappingIndex < 0:
return 0
else:
return self.log_mapping[mappingIndex]
def __init__(self, regexp = "abc"):
self.regexp = regexp
self.occurrences = 0
self.log_mapping = []
finding = re_finding("xyz")
finding.finding_index = "127.0.0.1"
finding.occurrences = 5
print("Reg. expression: " + finding.regexp)
print("Size of log mapping: " + str(finding.getSizeOfMapping()))
# The below line will error, as it should. How can I get Python to say this attribute doesn't exist by gracefully handling the exception that gets
# raised
print("Log filename: " + finding.getLogMapping(1).log_filename)
finding.addLogMapping("firewall1.log", "1", "127.0.0.1: access denied.")
finding.addLogMapping("firewall2.log", "1", "127.0.0.5: access denied.")
print("Size of log mapping: " + str(finding.getSizeOfMapping()))
print("Occurrences: " + str(finding.occurrences))
print("Complete line from \"" + finding.getLogMapping(1).log_filename + "\": " + finding.getLogMapping(1).complete_line_in_log_file)
1 reply to this topic
#1
Posted 28 September 2011 - 10:21 AM
|
|
|
#2
Posted 28 September 2011 - 11:06 PM
try:
print("Log filename: " + finding.getLogMapping(1).log_filename)
except AttributeError as e:
print("Exceeption : AttributeError: %s", s)
Next time please post using code tags ( # button ) since indents are vital in Python.
A conclusion is where you got tired of thinking.
#define class struct // All is public.
1 user(s) are reading this topic
0 members, 1 guests, 0 anonymous users


Sign In
Create Account

Back to top









