decorator to parse options for single command
authorAlexander Solovyov <piranha@piranha.org.ua>
Thu, 02 Jul 2009 22:17:21 +0300
changeset 29 d9a2fc1e5e90
parent 28 1a90a706e10d
child 30 1fc9a029d760
decorator to parse options for single command
fancycmd.py
test_opts.py
--- a/fancycmd.py	Thu Jul 02 21:45:38 2009 +0300
+++ b/fancycmd.py	Thu Jul 02 22:17:21 2009 +0300
@@ -5,19 +5,32 @@
 import sys, traceback, getopt, types, textwrap
 from itertools import imap
 
-__all__ = ['fancyopts', 'dispatch']
+__all__ = ['fancyopts', 'dispatch', 'optionize']
 
 # --------
 # Public interface
 # --------
 
+def optionize(options, usage):
+    if '%prog' in usage.split():
+        name = sys.argv[0]
+        if name.startswith('./'):
+            name = name[2:]
+        usage = usage.replace('%prog', name, 1)
+
+    def wrapper(cmd):
+        def inner():
+            args = sys.argv[1:]
+            return fancyopts(cmd, options, usage)(args)
+        return inner
+    return wrapper
+
 def fancyopts(cmd, options, usage):
     def inner(args):
         if not args:
-            help_cmd(cmd, usage, options)
-        else:
-            opts, args = parse(args, options)
-            cmd(*args, **opts)
+            return help_cmd(cmd, usage, options)
+        opts, args = parse(args, options)
+        return cmd(*args, **opts)
     return inner
 
 def dispatch(args, cmdtable, globalopts=None):
--- a/test_opts.py	Thu Jul 02 21:45:38 2009 +0300
+++ b/test_opts.py	Thu Jul 02 22:17:21 2009 +0300
@@ -2,13 +2,14 @@
 
 import sys
 
-from fancycmd import fancyopts
+from fancycmd import optionize
 
 opts = [('l', 'listen', 'localhost', 'ip to listen on'),
         ('p', 'port', 8000, 'port to listen on'),
         ('d', 'daemonize', False, 'daemonize process'),
         ('', 'pid-file', '', 'name of file to write process ID to')]
 
+@optionize(opts, usage='%prog [-l HOST] DIR')
 def main(dirname, **opts):
     '''This is some command
 
@@ -17,4 +18,4 @@
     print opts.get('pid_file')
 
 if __name__ == '__main__':
-    fancyopts(main, opts, usage='%s [-l HOST] DIR' % sys.argv[0])(sys.argv[1:])
+    main()