Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from getopt import getopt
- from inspect import getargspec, ismethod
- import sys
- class POC:
- """
- A class for simple command line scripts
- It is used by inheriting from this class,
- the methods are mapped as command line arguments -
- methods name with more than 1 character become long options
- e.g. self.f() becomes -f
- self.foo(bar) becomes --foo bar
- POC(sys.argv)
- If a method returns something it will print out the value
- and exit the script
- NOTE: As a limitation of getopt you can't use default values
- for short options
- """
- def __init__(self, argv):
- self._script = argv[0]
- self._flags, self._short_options, self._long_options = ([], [], [])
- for i in dir(self):
- if i[0] == "_":
- pass
- elif not ismethod(getattr(self, i)):
- pass
- elif len(i) == 1:
- if len(getargspec(
- getattr(self, i)).args) > 1:
- self._short_options.append(i)
- else:
- self._flags.append(i)
- else:
- self._long_options.append(i)
- optlist, args = getopt(argv[1:],
- "".join(self._flags)+ ":".join(self._short_options) + ":",
- self._long_options)
- for i in [ (self._stripDash(x[0]), x[1]) for x in optlist ]:
- if i[1]:
- getattr(self, i[0])(i[1])
- else:
- getattr(self, i[0])()
- self.main(*args)
- def _stripDash(self, opt):
- """
- Strips 1-2 dashes from the front of a string.
- Expects at least one dash at front.
- """
- if opt.startswith("-", 1):
- return opt[2:]
- else:
- return opt[1:]
- def h(self):
- """Shows help"""
- self.help(False)
- def help(self, arg = False):
- """Shows help"""
- if arg:
- print getattr(self, arg).__doc__
- else:
- opts = self._flags+self._short_options+self._long_options
- opts.remove("main")
- opts.sort()
- print self.__doc__
- # We will abuse the doc-string of main here
- # until Py3k with function annotations is there
- print "Usage: %s [options] %s" % (self._script,
- self.main.__doc__)
- print "\nOptions:"
- for i in opts:
- print "\t%s - %s" % (i, getattr(self, i).__doc__)
- sys.exit()
- class App(POC):
- """A dummy App"""
- def __init__(self, argv):
- self.flag = False
- self.out = ""
- POC.__init__(self, argv)
- def f(self):
- """Some Flag"""
- self.flag = True
- def o(self, foo):
- """Some argument with a parameter"""
- self.out = foo
- def main(self, a="2", b="2"):
- """one thing other thing"""
- print "%s -> %s, %s, o = %s" % (a, b, str(self.flag), self.out)
- if __name__ == "__main__":
- app = App(sys.argv)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement