Skip to content

Instantly share code, notes, and snippets.

@JasonGiedymin
Created November 25, 2011 22:47
Show Gist options
  • Save JasonGiedymin/1394599 to your computer and use it in GitHub Desktop.
Save JasonGiedymin/1394599 to your computer and use it in GitHub Desktop.
Testing some parsing.
from time import strftime
import math
'''
Parse `input.conf`, store [access_key] in dict with tupple of IPs.
# `input.conf` file
access1, key1, 192.168.0.1; 192.168.0.2; 192.168.0.3
access2, key1, 192.168.0.1; 192.168.0.2; 192.168.0.3
access3, key1, 192.168.0.1; 192.168.0.2; 192.168.0.3
access1, key2, 192.168.0.1; 192.168.0.2; 192.168.0.3
access2, key2, 192.168.0.1; 192.168.0.2; 192.168.0.3
access3, key2, 192.168.0.1; 192.168.0.2; 192.168.0.3
'''
class Logger(object):
''' Simple Logger - keep it simple J! '''
_debug = True
_timestamp_format = '%a, %d %b %Y %H:%M:%S %z'
@staticmethod
def _logit(msg_type, msg, pre, post):
print "%s %s - [%s]: %s%s" % (pre, msg_type, strftime(Logger._timestamp_format), msg, post)
@staticmethod
def info(msg, pre="", post=""):
''' Direct info logger '''
Logger._logit("INFO", msg, pre, post)
@staticmethod
def debug(msg, pre="", post=""):
''' Direct debug logger '''
if Logger._debug:
Logger._logit("DEBUG", msg, pre, post)
@staticmethod
def error(msg, pre="", post=""):
''' Direct error logger '''
if Logger._debug:
Logger._logit("ERROR", msg, pre, post)
class AccessParser:
def __init__(self, input_file_name=""):
if len(input_file_name) == 0:
Logger.error("No input file was specified!")
raise Exception, "No input file was specified!"
self.file_name = input_file_name
self.file = open(input_file_name, 'r')
self.access_list = {}
def isProper(self, line):
is_proper = True
data = line.split(',')
is_proper = False if (len(data) < 3) else True
#print map(lambda x: 1 if len(x) == 0 else 0, data)
if math.fsum([1 if len(x.strip()) == 0 else 0 for x in data]) > 0:
is_proper = False
if is_proper == True and math.fsum([1 if len(x.strip()) == 0 else 0 for x in data[2].split(';')]) > 0:
is_proper = False
#Logger.debug("Input line: [%s] is_proper = %s" % (line, is_proper) )
return is_proper
def parse(self):
for line in self.file:
if self.isProper(line):
data = line.split(',')
self.access_list["%s_%s" % (data[0].strip(), data[1].strip())] = data[2].strip().split(';')
else:
Logger.error("Input data from file:[%s] is not proper." % self.file_name)
self.file.close()
def printList(self):
print self.access_list
new_obj = AccessParser('input.conf')
new_obj.parse()
new_obj.printList()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment