1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 """Extend OptionParser with commands.
20
21 Example:
22
23 >>> parser = OptionParser()
24 >>> parser.usage = '%prog COMMAND [options] <arg> ...'
25 >>> parser.add_command('build', 'mymod.build')
26 >>> parser.add_command('clean', run_clean, add_opt_clean)
27 >>> run, options, args = parser.parse_command(sys.argv[1:])
28 >>> return run(options, args[1:])
29
30 With mymod.build that defines two functions run and add_options
31 """
32 __docformat__ = "restructuredtext en"
33
34 from warnings import warn
35 warn('lgc.optparser module is deprecated, use lgc.clcommands instead', DeprecationWarning,
36 stacklevel=2)
37
38 import sys
39 import optparse
40
42
47
49 """name of the command, name of module or tuple of functions
50 (run, add_options)
51 """
52 assert isinstance(mod_or_funcs, str) or isinstance(mod_or_funcs, tuple), \
53 "mod_or_funcs has to be a module name or a tuple of functions"
54 self._commands[name] = (mod_or_funcs, help)
55
57 optparse.OptionParser.print_help(self)
58 print('\ncommands:')
59 for cmdname, (_, help) in list(self._commands.items()):
60 print('% 10s - %s' % (cmdname, help))
61
63 if len(args) == 0:
64 self.print_main_help()
65 sys.exit(1)
66 cmd = args[0]
67 args = args[1:]
68 if cmd not in self._commands:
69 if cmd in ('-h', '--help'):
70 self.print_main_help()
71 sys.exit(0)
72 elif self.version is not None and cmd == "--version":
73 self.print_version()
74 sys.exit(0)
75 self.error('unknown command')
76 self.prog = '%s %s' % (self.prog, cmd)
77 mod_or_f, help = self._commands[cmd]
78
79 self.description = help
80 if isinstance(mod_or_f, str):
81 exec('from %s import run, add_options' % mod_or_f)
82 else:
83 run, add_options = mod_or_f
84 add_options(self)
85 (options, args) = self.parse_args(args)
86 if not (self.min_args <= len(args) <= self.max_args):
87 self.error('incorrect number of arguments')
88 return run, options, args
89