Advertisement
Guest User

madhatter

a guest
May 21st, 2009
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.50 KB | None | 0 0
  1. from getopt import getopt
  2. from inspect import getargspec, ismethod
  3. import sys
  4.  
  5. class POC:
  6.     """
  7.     A class for simple command line scripts
  8.  
  9.     It is used by inheriting from this class,
  10.     the methods are mapped as command line arguments -
  11.     methods name with more than 1 character become long options
  12.      e.g. self.f() becomes -f
  13.           self.foo(bar) becomes --foo bar
  14.  
  15.           POC(sys.argv)
  16.  
  17.     If a method returns something it will print out the value
  18.     and exit the script
  19.  
  20.     NOTE: As a limitation of getopt you can't use default values
  21.     for short options
  22.     """
  23.  
  24.     def __init__(self, argv):
  25.         self._script = argv[0]
  26.  
  27.         self._flags, self._short_options, self._long_options = ([], [], [])
  28.         for i in dir(self):
  29.             if i[0] == "_":
  30.                 pass
  31.             elif not ismethod(getattr(self, i)):
  32.                 pass
  33.             elif len(i) == 1:
  34.                 if len(getargspec(
  35.                     getattr(self, i)).args) > 1:
  36.                     self._short_options.append(i)
  37.                 else:
  38.                     self._flags.append(i)
  39.             else:
  40.                 self._long_options.append(i)
  41.         optlist, args = getopt(argv[1:],
  42.             "".join(self._flags)+ ":".join(self._short_options) + ":",
  43.                 self._long_options)
  44.  
  45.         for i in [ (self._stripDash(x[0]), x[1]) for x in optlist ]:
  46.             if i[1]:
  47.                 getattr(self, i[0])(i[1])
  48.             else:
  49.                 getattr(self, i[0])()
  50.  
  51.         self.main(*args)
  52.  
  53.     def _stripDash(self, opt):
  54.         """
  55.         Strips 1-2 dashes from the front of a string.
  56.         Expects at least one dash at front.
  57.         """
  58.         if opt.startswith("-", 1):
  59.             return opt[2:]
  60.         else:
  61.             return opt[1:]
  62.  
  63.  
  64.     def h(self):
  65.         """Shows help"""
  66.         self.help(False)
  67.  
  68.     def help(self, arg = False):
  69.         """Shows help"""
  70.         if arg:
  71.             print getattr(self, arg).__doc__
  72.         else:
  73.             opts = self._flags+self._short_options+self._long_options
  74.             opts.remove("main")
  75.             opts.sort()
  76.  
  77.             print self.__doc__
  78.             # We will abuse the doc-string of main here
  79.             # until Py3k with function annotations is there
  80.             print "Usage: %s [options] %s" % (self._script,
  81.                     self.main.__doc__)
  82.            
  83.             print "\nOptions:"
  84.             for i in opts:
  85.                 print "\t%s - %s" % (i, getattr(self, i).__doc__)
  86.  
  87.         sys.exit()
  88.  
  89.  
  90.  
  91. class App(POC):
  92.     """A dummy App"""
  93.  
  94.     def __init__(self, argv):
  95.         self.flag = False
  96.         self.out = ""
  97.  
  98.         POC.__init__(self, argv)
  99.  
  100.     def f(self):
  101.         """Some Flag"""
  102.         self.flag = True
  103.  
  104.     def o(self, foo):
  105.         """Some argument with a parameter"""
  106.         self.out = foo
  107.    
  108.     def main(self, a="2", b="2"):
  109.         """one thing other thing"""
  110.         print "%s -> %s, %s, o = %s" % (a, b, str(self.flag), self.out)
  111.  
  112.  
  113. if __name__ == "__main__":
  114.     app = App(sys.argv)
  115.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement