def FancyGetopt(cmd, option_table, args): """ Parses command line options and parameter list. args is the argument list to be parsed, without the leading reference to the running program. Typically, this means "sys.argv[1:]". option_table is an instance of Ft.Lib.CommandLine.Options.Options. Raises an exception if args contains syntax errors. Returns a tuple of (options, args) where options is a dictionary and args is the list of args after the first arg that wasn't in option_table. Note the options return value is different than what getopt.getopt() returns. cmd is an Ft.Lib.CommandLine.Command instance, and is only used in reporting errors. """ short_opts = [] long_opts = [] short2long = {} takes_arg = {} # the resulting options options = {} for option in option_table: (short, long) = option.getForGetOpt(short2long, takes_arg) short_opts.append(short) long_opts.extend(long) short_opts = ''.join(short_opts) try: (opts, args) = getopt.getopt(args, short_opts, long_opts) except getopt.error, msg: raise CommandLineUtil.ArgumentError(cmd, str(msg))
def _parse_command_opts(self, arglist): options, arglist = FancyGetOpt.FancyGetopt(self, self.options, arglist) if not self.validate_options(options): return None # Args can either be a subcommand, or the start of the argument # list. Subcommand takes precedence. if self.subCommands: try: cmd = arglist[0] except IndexError: msg = "subcommand required" raise CommandLineUtil.ArgumentError(self, msg) try: cmd = self.subCommands[cmd] except KeyError: msg = "invalid subcommand: %s" % cmd raise CommandLineUtil.ArgumentError(self, msg) parsed = cmd._parse_command_opts(arglist[1:]) else: parsed = (self, options, self.validate_arguments(arglist)) return parsed
def run(self, options, arguments): if not self.function: raise CommandLineUtil.ArgumentError(self, "subcommand required") return self.function(options, arguments)