1
2 """Extend OptionParser with commands.
3
4 Example:
5
6 >>> parser = OptionParser()
7 >>> parser.usage = '%prog COMMAND [options] <arg> ...'
8 >>> parser.add_command('build', 'mymod.build')
9 >>> parser.add_command('clean', run_clean, add_opt_clean)
10 >>> run, options, args = parser.parse_command(sys.argv[1:])
11 >>> return run(options, args[1:])
12
13 With mymod.build that defines two functions run and add_options
14
15 :copyright: 2000-2008 LOGILAB S.A. (Paris, FRANCE), all rights reserved.
16 :contact: http://www.logilab.fr/ -- mailto:contact@logilab.fr
17 :license: General Public License version 2 - http://www.gnu.org/licenses
18 """
19 __docformat__ = "restructuredtext en"
20
21
22
23 import sys
24 import optparse
25
27
32
34 """name of the command
35 name of module or tuple of functions (run, add_options)
36 """
37 assert isinstance(mod_or_funcs, str) or isinstance(mod_or_funcs, tuple), \
38 "mod_or_funcs has to be a module name or a tuple of functions"
39 self._commands[name] = (mod_or_funcs, help)
40
42 optparse.OptionParser.print_help(self)
43 print '\ncommands:'
44 for cmdname, (_, help) in self._commands.items():
45 print '% 10s - %s' % (cmdname, help)
46
48 if len(args) == 0:
49 self.print_main_help()
50 sys.exit(1)
51 cmd = args[0]
52 args = args[1:]
53 if cmd not in self._commands:
54 if cmd in ('-h', '--help'):
55 self.print_main_help()
56 sys.exit(0)
57 elif self.version is not None and cmd == "--version":
58 self.print_version()
59 sys.exit(0)
60 self.error('unknown command')
61 self.prog = '%s %s' % (self.prog, cmd)
62 mod_or_f, help = self._commands[cmd]
63
64 self.description = help
65 if isinstance(mod_or_f, str):
66 exec 'from %s import run, add_options' % mod_or_f
67 else:
68 run, add_options = mod_or_f
69 add_options(self)
70 (options, args) = self.parse_args(args)
71 if not (self.min_args <= len(args) <= self.max_args):
72 self.error('incorrect number of arguments')
73 return run, options, args
74