Parse the args and fill the global data
        Currently we disregard the free parameters
        :param command_selected:
        :param flags:
        :param _free_args:
        :return:
510140
def parse_args(self, command_selected, flags, _free_args):
        # type: (str, Dict[str, str], List[str]) -> bool
        
        configs = self.function_name_to_configs[command_selected]
        suggested_configs = self.function_name_to_suggest_configs[command_selected]

        # create the attribute_to_config map
        attribute_to_config = dict()  # type: Dict[str, Config]
        for config in itertools.chain(configs, suggested_configs):
            for attribute in config.get_attributes():
                if attribute in attribute_to_config:
                    raise ValueError("attribute [{}] double".format(attribute))
                attribute_to_config[attribute] = config

        # set the flags into the "default" field
        unknown_flags = []
        for flag_raw, value in flags.items():
            edit = value.startswith('=')
            if flag_raw not in attribute_to_config:
                unknown_flags.append(flag_raw)
            config = attribute_to_config[flag_raw]
            param = config.get_param_by_name(flag_raw)
            if edit:
                v = param.s2t_generate_from_default(value[1:])
            else:
                v = param.s2t(value)
            setattr(config, flag_raw, v)

        # check for missing parameters and show help if there are any missing
        missing_parameters = []
        for config in configs:
            for attribute in config.get_attributes():
                value = getattr(config, attribute)
                if value is NO_DEFAULT:
                    missing_parameters.append(attribute)
        if unknown_flags or missing_parameters:
            if missing_parameters:
                print()
                print_warn("missing parameters [{}]".format(",".join(missing_parameters)))
            if unknown_flags:
                print()
                print_warn("unknown flags [{}]".format(",".join(unknown_flags)))
            print("problems found, not running")
            print()
            self.show_help_for_function(command_selected, show_help_full=False, show_help_suggest=False)
            return False

        # move all default values to place
        for config in itertools.chain(configs, self._configs):
            for attribute in config.get_attributes():
                param = getattr(config, attribute)  # type: Param
                if isinstance(param, Param):
                    if param.default is not NO_DEFAULT:
                        setattr(config, attribute, param.default)
        return True
830393
def parse_command_line_arguments(argparse_parser, init_indent=5, subs_indent=5,
                                 line_width=76):
    """"""
    # Redirect stdout and stderr to prettify help or usage output from argparse.
    old_stdout = sys.stdout # save stdout
    old_stderr = sys.stderr # save stderr
    sys.stdout = RedirectHelp(sys.stdout, help_string_replacement_pairs,
            init_indent, subs_indent, line_width) # redirect stdout to add postprocessor
    sys.stderr = RedirectHelp(sys.stderr, help_string_replacement_pairs,
            init_indent, subs_indent, line_width) # redirect stderr to add postprocessor

    # Run the actual argument-parsing operation via argparse.
    args = argparse_parser.parse_args()

    # The argparse class has finished its argument-processing, so now no more
    # usage or help messages will be printed.  So restore stdout and stderr
    # to their usual settings, except with self-flushing added.
    sys.stdout = SelfFlushingOutstream(old_stdout)
    sys.stderr = SelfFlushingOutstream(old_stderr)

    return args
838596
def option_parser
      @_option_parser ||= Slop.new do |command|
        command.banner "Usage: #{program_name} [options] [template_name]"

        command.on('-V', 'Shows version and exits') do
          print_and_exit Snp::VERSION
        end

        command.on('-h', 'Shows this message') do
          print_and_exit command.to_s
        end
      end
    end
1044226
def load_flag_values(self, flags=None):
    
    if flags is None:
      flags = self._flags
    for keyval in flags.config_value:
      k, v = keyval.split('=', 1)
      v = self._modules['yaml'].load(v) if isinstance(v, str) else v

      # Force any command line keys and values that are bytes to unicode.
      k = k.decode() if isinstance(k, bytes) else k
      v = v.decode() if isinstance(v, bytes) else v

      self._flag_values.setdefault(k, v)
1267672
def arg(params)
      rpc_desc.input.decode_json(params.reject { |k, _v| k == :selections }.to_json)
    end
1126409
def parsed_options_from_arguments(argv)
      options_to_merge = {}

      OptionParser.new do |opts|
        opts.banner = 'Usage: phare [options]'

        opts.on('--version', 'Display Phare’s version') do
          options_to_merge[:version] = true
        end

        opts.on('--directory x', 'The directory in which to run the checks (default is the current directory') do |directory|
          options_to_merge[:directory] = directory
        end

        opts.on('--skip x,y,z', 'Skip checks') do |checks|
          options_to_merge[:skip] = checks.split(',')
        end

        opts.on('--only x,y,z', 'Only run the specified checks') do |checks|
          options_to_merge[:only] = checks.split(',')
        end

        opts.on('--diff', 'Only run checks on modified files') do
          options_to_merge[:diff] = true
        end
      end.parse! argv

      options_to_merge
    end
942066
def run(self):
    
    self.parser = MultioptOptionParser(
      usage="%prog <command> [options] [args]",
      prog=self.clsname,
      version=self.version,
      option_list=self.global_options,
      description=self.desc_short,
      commands=self.command_set,
      epilog=self.footer
    )
    
    try:
      self.options, self.args = self.parser.parse_args(self.argv)    
    except Exception, e:
      print str(e)
      pass

    if len(self.args) < 1:
      self.parser.print_lax_help()
      return 2
    
    self.command = self.args.pop(0)
    showHelp = False
    
    if self.command == 'help': 
      if len(self.args) < 1:
        self.parser.print_lax_help()
        return 2
      else:
        self.command = self.args.pop()
        showHelp = True

    if self.command not in self.valid_commands:
      self.parser.print_cmd_error(self.command)
      return 2

    self.command_set[self.command].set_cmdname(self.command)
    subcmd_parser = self.command_set[self.command].get_parser(self.clsname, self.version, self.global_options)
    subcmd_options, subcmd_args = subcmd_parser.parse_args(self.args)

    if showHelp:
      subcmd_parser.print_help_long()
      return 1

    try:
      self.command_set[self.command].func(subcmd_options, *subcmd_args)
    except (CommandError, TypeError), e:
      # self.parser.print_exec_error(self.command, str(e))
      subcmd_parser.print_exec_error(self.command, str(e))
      print 
      # @TODO show command help
      # self.parser.print_lax_help()
      return 2

      
    return 1
514563
def parse_args():
    
    parser = argparse.ArgumentParser()
    parser.add_argument('-M', action='store_true')
    parser.add_argument('-m', action='store_true')
    parser.add_argument('-f', action='store_true')
    args = parser.parse_args()
    major, minor, fix = args.M, args.m, args.f
    if major + minor + fix != 1:
        fail('Please select one and only one action.')
    return major, minor, fix
797498
def _arguments(ctx, command_name=None):
    
    ctx = ctx.parent
    main = ctx.command
    if command_name:
        command = main.get_command(ctx, command_name)
        if not command:
            return
    else:
        command = main

    types = ["option", "argument"]
    all_params = sorted(
        command.get_params(ctx), key=lambda p: types.index(p.param_type_name)
    )

    def get_name(param):
        return max(param.opts, key=len)

    for param in all_params:
        if param.param_type_name == "option":
            option = get_name(param)
            same_dest = [
                get_name(p) for p in all_params if p.name == param.name
            ]
            if same_dest:
                option = "({})".format(" ".join(same_dest)) + option
            if param.help:
                option += "[{}]".format(param.help or "")
            if not param.is_flag:
                option += "=:( )"
            click.echo(option)
        elif param.param_type_name == "argument":
            option = get_name(param)
            click.echo(":{}".format(option))
267193
def select_defined(args)
      args.select { |k, v| (ATTRS.include? k) && !v.nil? }
    end
193531
def _build_flags(self):
        
        # Check if all entries for selected arguments are nonempty
        for arg_dict in [x for x in self.args.values() if self.arg_is_selected(x)]:
            if 'entry' in arg_dict and not arg_dict['entry'].get_text():
                self.gui_helper.execute_dialog("Entry {0} is empty".format(arg_dict['label']))
                return False

        # Check for active CheckButtons
        for arg_dict in [x for x in self.args.values() if self.arg_is_selected(x)]:
            arg_name = arg_dict['arg'].get_dest()
            if 'entry' in arg_dict:
                self.kwargs[arg_name] = arg_dict['entry'].get_text()
            else:
                if arg_dict['arg'].get_gui_hint('type') == 'const':
                    self.kwargs[arg_name] = arg_dict['arg'].kwargs['const']
                else:
                    self.kwargs[arg_name] = True

        # Check for non active CheckButtons but with defaults flag
        for arg_dict in [x for x in self.args.values() if not self.arg_is_selected(x)]:
            arg_name = arg_dict['arg'].get_dest()
            if 'default' in arg_dict['arg'].kwargs:
                self.kwargs[arg_name] = arg_dict['arg'].get_gui_hint('default')
            elif arg_name in self.kwargs:
                del self.kwargs[arg_name]

        return True
1099305
def parse(self, arguments=None):
        
        arguments = self.arguments or arguments
        # FIXME: prep/normalize arguments in __init__
        # Split arguments if given as string and run the parser
        if isinstance(arguments, basestring):
            arguments = utils.split(arguments)

        # run the wrapped argparser command to gather user set arg values
        # FROM: https://docs.python.org/3/library/argparse.html
        # Sometimes a script may only parse a few of the command-line
        # arguments, passing the remaining arguments on to another script or
        # program.  In these cases, the parse_known_args() method can be
        # useful. It works much like parse_args() except that it does not
        # produce an error when extra arguments are present. Instead, it
        # returns a two item tuple containing the populated namespace and
        # the list of remaining argument strings.
        opts, _arguments = self.parser.parse_known_args(arguments)

        if not opts.config_file:
            opts.config_file = os.path.expanduser(DEFAULT_IDID_CONFIG)
        opts.config = Configuration().from_file(opts.config_file)
        # alias shortcut
        self.config = opts.config

        # if we're passing arguments in as a string we might get \n's or null
        # strings '' that we want to be sure to ignore
        _arguments = filter(
            lambda x: x if x else None, [_.strip() for _ in _arguments if _])

        # Now let the subclass parse the remaining special opts that
        # weren't consumed by default argparser
        opts = self._parse(opts, _arguments)

        return opts
390316
def cmdline(executable):
    

    args = [executable.executable]
    indexed_args = []

    for parameter in executable:

        optional = (parameter.type == 'boolean') or parameter.default
        has_value = parameter.type != 'boolean'


        if parameter.longflag:  # use longflag where possible
            flag = "--%s" % parameter.longflag
        elif parameter.flag:
            flag = "-%s VALUE" % parameter.flag
        elif parameter.index:
            flag = parameter.name
            optional = False


        if has_value:
            flag += " VALUE"

        if optional:
            flag = "[" + flag + "]"

        if parameter.index:
            indexed_args.insert(int(parameter.index), flag)
        else:
            args.append(flag)

    return args + indexed_args
411682
def selected_shells(command):
    """"""
    if not command or command == '*':
        for i in dispatchers.all_instances():
            yield i
        return
    selected = set()
    instance_found = False
    for pattern in command.split():
        found = False
        for expanded_pattern in expand_syntax(pattern):
            for i in dispatchers.all_instances():
                instance_found = True
                if fnmatch(i.display_name, expanded_pattern):
                    found = True
                    if i not in selected:
                        selected.add(i)
                        yield i
        if instance_found and not found:
            console_output('{} not found\n'.format(pattern).encode())
1175264
def bind_global
      opts = get_all_commands
      cmd = rb_gets("Select a command (<tab> for choices) : ", opts)
      if cmd.nil? || cmd == ""
        rb_puts "Aborted."
        return
      end
      key = []
      str = ""
      # the next is fine but does not allow user to enter a control or alt or function character
      # since it uses Field. It is fine if you want to force alphanum input
      ch = rb_getchar("Enter one or two keys. Finish with <ENTER>. Enter first key:")
      unless ch
        rb_puts "Aborted. <Press a key>"
        return
      end
      key << ch
      str << keycode_tos(ch)
      ch = rb_getchar  "Got #{str}. Enter second key or hit return:"
      unless ch
        rb_puts "Aborted. <Press a key>"
        return
      end
      if ch == KEY_ENTER || ch == 13
      else
        key << ch
        str << keycode_tos(ch)
      end
      if !key.empty?
        rb_puts "Binding #{cmd} to #{str}. "
        key = key[0] if key.size == 1
        #@form.bind_key(key, cmd.to_sym) # not finding it, getting called by that comp
        @form.bind_key(key){ send(cmd.to_sym) }
      end
    end
1337937
def load_args(self, args, clargs):
        
        # Parse All Arguments
        args = self.parser.parse_args(args=clargs, namespace=args)

        # Print the help information if no subcommand is given
        # subcommand is required for operation
        if args.subcommand is None:
            self.parser.print_help()
            args = None

        return args
1336103
def create_default_commands
			command :help do
        syntax 'commander help [command]'
        description 'Display global or [command] help documentation'
        example 'Display global help', 'command help'
        example "Display help for 'foo'", 'command help foo'
        when_called do |args, _options|
          UI.enable_paging
          if args.empty?
            say help_formatter.render
          else
            command = command args.join(' ')
            begin
              require_valid_command command
            rescue InvalidCommandError => e
              abort "#{e}. Use --help for more information"
            end
            say help_formatter.render_command(command)
          end
        end
      end
    end