Skip to content

Instantly share code, notes, and snippets.

@kladd
Created March 20, 2012 14:30
Show Gist options
  • Save kladd/2136188 to your computer and use it in GitHub Desktop.
Save kladd/2136188 to your computer and use it in GitHub Desktop.
command line flag parser
##
# Flag Parse
#
# Command line flag/switch parsing
##
import sys
class ParserError(Exception):
def __init__(self, m):
self.message = "ParserError: "+m
class FlagParser(object):
_SETFLAGS = []
_POSFLAGS = []
_USAGEMSGS = {}
_DELIMETER = ''
def __init__(self, flags=None, delim='-'):
if flags is not None:
self._POSFLAGS = flags
self._DELIMETER = delim
def setFlags(self, flags):
# make sure they're string type for later
for flag in flags:
if len(flag) > 1: raise ParserError("Invalid Flag Set")
self._POSFLAGS.append(str(flag))
def flagSet(self, flag):
return flag in self._SETFLAGS
def setUsage(self, flag, message):
# disallow messages for flags that don't exist
if not self.flagSet(flag): raise ParserError("Flag "+flag+" does not exist.")
self._USAGEMSGS[flag] = message
def showUsage(self,flag):
if flag in self._USAGEMSGS:
print "Usage", flag, self._USAGEMSGS[flag]
else:
print "No usage information available."
def dumpSetFlags(self):
print self._SETFLAGS
def dumpPosFlags(self):
print self._POSFLAGS
def parse(self, rawArgs=None):
# Check if we've actually got args if not then get them
if rawArgs==None: rawArgs = sys.argv
# TODO: Support Flags with parameters
for arg in rawArgs[1::]:
# check if correct delimeter used
if arg[0] is not self._DELIMETER:
raise ParserError("Invalid delimeter \'"+arg[0]+'\'')
elif len(arg) <= 1:
raise ParserError("Unknown option \'"+arg[0]+'\'')
else:
# loop through flags add to setFlags
for flag in arg[1::]:
# make sure it's a valid flag or none are specefied
if flag in self._POSFLAGS or not self._POSFLAGS:
self._SETFLAGS.append(flag)
else: raise ParserError("Unknown flag \'"+flag+'\'')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment