Processes argv for any options specific to the specified module.

        @module - The module to process argv for.
        @argv   - A list of command line arguments (excluding argv[0]).

        Returns a dictionary of kwargs for the specified module.
335393
def argv(self, module, argv=sys.argv[1:]):
        '''
        
        '''
        kwargs = {'enabled': False}
        last_priority = {}
        parser = argparse.ArgumentParser(add_help=False)
        # Hack: This allows the ListActionParser class to correllate short options to long options.
        # There is probably a built-in way to do this in the
        # argparse.ArgumentParser class?
        parser.short_to_long = {}

        # Must build arguments from all modules so that:
        #
        #    1) Any conflicting arguments will raise an exception
        #    2) The only unknown arguments will be the target files, making them
        #       easy to identify
        for m in self.list(attribute="CLI"):

            for module_option in m.CLI:

                parser_args = []
                parser_kwargs = {}

                if not module_option.long:
                    continue

                if module_option.short:
                    parser_args.append('-' + module_option.short)
                parser_args.append('--' + module_option.long)
                parser_kwargs['dest'] = module_option.long

                if module_option.type is None:
                    parser_kwargs['action'] = 'store_true'
                elif module_option.type is list:
                    parser_kwargs['action'] = 'append'
                    parser.short_to_long[
                        module_option.short] = module_option.long

                parser.add_argument(*parser_args, **parser_kwargs)

        args, unknown = parser.parse_known_args(argv)
        args = args.__dict__

        # Only add parsed options pertinent to the requested module
        for module_option in module.CLI:

            if module_option.type == binwalk.core.common.BlockFile:

                for k in get_keys(module_option.kwargs):
                    kwargs[k] = []
                    for unk in unknown:
                        kwargs[k].append(unk)

            elif has_key(args, module_option.long) and args[module_option.long] not in [None, False]:

                # Loop through all the kwargs for this command line option
                for (name, default_value) in iterator(module_option.kwargs):

                    # If this kwarg has not been previously processed, or if its priority is equal to or
                    # greater than the previously processed kwarg's priority,
                    # then let's process it.
                    if not has_key(last_priority, name) or last_priority[name] <= module_option.priority:

                        # Track the priority for future iterations that may
                        # process the same kwarg name
                        last_priority[name] = module_option.priority

                        try:
                            kwargs[name] = module_option.convert(args[module_option.long], default_value)
                        except KeyboardInterrupt as e:
                            raise e
                        except Exception as e:
                            raise ModuleException("Invalid usage: %s" % str(e))

        binwalk.core.common.debug("%s :: %s => %s" % (module.TITLE, str(argv), str(kwargs)))
        return kwargs
964495
def parse(self, argv=None):
        

        if not argv:
            argv = sys.argv
        elif isinstance(argv, str):
            argv = argv.split()

        self._argv = argv[1:]
        if not self._argv:
            self.validate_options()
            if self._command_func:
                self._command_func(**self._results)
                return True
            return False

        cmd = self._argv[0]

        if not cmd.startswith('-'):
            # parse subcommands
            for command in self._command_list:
                if isinstance(command, Command) and command._name == cmd:
                    command._parent = self
                    return command.parse(self._argv)

        _positional_index = 0
        while self._argv:
            arg = self._argv[0]
            self._argv = self._argv[1:]
            if not self.parse_options(arg):
                self._args_results.append(arg)
                if len(self._positional_list) > _positional_index:
                    # positional arguments
                    key = self._positional_list[_positional_index]
                    self._results[key] = arg
                    _positional_index += 1

        # validate
        self.validate_options()

        if self._parent and isinstance(self._parent, Command):
            self._parent._args_results = self._args_results

        if self._command_func:
            self._command_func(**self._results)
            return True
        return False
626361
def parse_command_line(self, argv=None):
        
        if self.config:
            parser = argparse.ArgumentParser(add_help=False)
            self.settings['config'].add_argument(parser)
            opts, _ = parser.parse_known_args(argv)
            if opts.config is not None:
                self.set('config', opts.config)

            self.params.update(self.import_from_module())

        parser = self.parser()
        opts = parser.parse_args(argv)
        for k, v in opts.__dict__.items():
            if v is None:
                continue
            self.set(k.lower(), v)
197957
function Args() {
    if (argv._.length >= 1) {
        try {
            // Attempt to parse 1st argument as JSON string
            _.extend(this, JSON.parse(argv._[0]));
        } catch (err) {
            // Pass, we must be in the console so don't worry about it
        }
    }
}
1312986
def parse_args(self):
        
        # compile the parser
        self._compile()
        # clear the args
        self.args = None
        self._self_event('before_parse', 'parse', *sys.argv[1:], **{})
        # list commands/subcommands in argv
        cmds = [cmd for cmd in sys.argv[1:] if not cmd.startswith("-")]
        if (len(cmds) > 0 and not utils.check_help() and self.default_cmd
                and cmds[0] not in self.commands):
            # if we have at least one command which is not an help command
            # and we have a default command and the first command in arguments
            # is not in commands we insert the default command as second
            # argument (actually the first command)
            sys.argv.insert(1, self.default_cmd)
        # let's parse the arguments
        self.args = self.parser.parse_args()
        # set up the output.
        if self.args:
            # if we have some arguments
            if self.add_output and self.args.output is not None:
                # If add_output is True and we have an output file
                # setup the encoding
                self.encoding = self.args.encoding
                if self.args.encoding.lower() == 'raw':
                    # if we have passed a raw encoding we will write directly
                    # to the output file.
                    self._output = open(self.args.output, self.args.write_mode)
                else:
                    # else we will use the codecs module to write to the
                    # output file.
                    import codecs
                    self._output = codecs.open(
                        self.args.output, self.args.write_mode,
                        encoding=self.args.encoding)
            if self._cfg_factory:
                # if we have a config factory setup the config file with the
                # right param
                self.cfg_file = self.args.config
            # now is parsed.
            self._is_parsed = True
        return self
1355137
def process_args(args):
    """"""
    passed_args = args
    if isinstance(args, argparse.Namespace):
        passed_args = vars(passed_args)
    elif hasattr(args, "to_dict"):
        passed_args = passed_args.to_dict()

    return Box(passed_args, frozen_box=True, default_box=True)
625656
def _arguments(code, module):
  
  arg_parser = CommandParser.create('')
  try:
    # Define our special argument 'types' and add them to the environment.
    builtins = {'source': _table, 'datestring': _datestring}
    env = {}
    env.update(builtins)

    # Execute the cell which should be one or more calls to arg().
    exec(code, env)

    # Iterate through the module dictionary. For any newly defined objects,
    # add args to the parser.
    for key in env:

      # Skip internal/private stuff.
      if key in builtins or key[0] == '_':
        continue
      # If we want to support importing query modules into other query modules, uncomment next 4
      # Skip imports but add them to the module
      # if isinstance(env[key], types.ModuleType):
      #   module.__dict__[key] = env[key]
      #   continue

      val = env[key]
      key = '--%s' % key

      if isinstance(val, bool):
        if val:
          arg_parser.add_argument(key, default=val, action='store_true')
        else:
          arg_parser.add_argument(key, default=val, action='store_false')
      elif isinstance(val, basestring) or isinstance(val, int) or isinstance(val, float) \
              or isinstance(val, int):
        arg_parser.add_argument(key, default=val)
      elif isinstance(val, list):
        arg_parser.add_argument(key, default=val, nargs='+')
      elif isinstance(val, tuple):
        arg_parser.add_argument(key, default=list(val), nargs='+')

      # Is this one of our pseudo-types for dates/tables?
      elif isinstance(val, dict) and 'type' in val:
        if val['type'] == 'datestring':
          arg_parser.add_argument(key, default='',
                                  type=_make_string_formatter(val['format'],
                                                              offset=val['offset']))
        elif val['type'] == 'table':
          if val['format'] is not None:
            arg_parser.add_argument(key, default='',
                                    type=_make_table_formatter(val['format'],
                                                               offset=val['offset']))
          else:
            arg_parser.add_argument(key, default=val['name'], type=_make_table)
        else:
          raise Exception('Cannot generate argument for %s of type %s' % (key, type(val)))
      else:
        raise Exception('Cannot generate argument for %s of type %s' % (key, type(val)))

  except Exception as e:
    print("%%sql arguments: %s from code '%s'" % (str(e), str(code)))
  return arg_parser
557925
def run_from_argv(self, argv):
        
        if (len(argv) > 2 and not argv[2].startswith('-') and
                argv[2] in self.subcommands.keys()):
            subcommand = argv[2]
            klass = self.get_subcommand(subcommand)
            parser = OptionParser(
                prog=argv[0],
                usage=klass.usage('{0} {1}'.format(argv[1], subcommand)),
                version=klass.get_version(), option_list=klass.option_list)
            options, args = parser.parse_args(argv[3:])
            args = [subcommand] + args
        else:
            parser = self.create_parser(argv[0], argv[1])
            options, args = parser.parse_args(argv[2:])

        handle_default_options(options)
        self.execute(*args, **options.__dict__)
98238
def main(argv: Optional[Sequence[str]] = None, *, check: bool = True, **runargs) -> Optional[CompletedProcess]:
    
    parser = ArgumentParser(description="There are a few packages providing commands. Try e.g. `pip install scanpy-scripts`!")
    parser.set_defaults(func=parser.print_help)
    
    subparsers: DelegatingSubparsersAction = parser.add_subparsers(
        action=DelegatingSubparsersAction,
        _command='scanpy',
        _runargs={**runargs, 'check': check},
    )
    
    parser_settings = subparsers.add_parser('settings')
    parser_settings.set_defaults(func=cmd_settings)
    
    args = parser.parse_args(argv)
    return args.func()
646310
def main(args=None):
    
    # Base command line parser. Help is not allowed because command
    # line is parsed in two stages - in the first stage is found setting
    # module of the application, in the second stage are found management
    # command's arguments.
    parser = ArgumentParser(add_help=False)
    parser.add_argument(
        '-s', '--settings',
        dest='settings', action='store', type=str, default=None,
        help=_('application settings module')
    )

    # Get settings module
    try:
        settings = get_app_settings(parser, args)
    except ImportError as exc:
        parser.error(_("Invalid application settings module: {}").format(exc))

    # Get management commands and add their arguments into command
    # line parser
    commands = get_management_commands(settings)
    subparsers = parser.add_subparsers(
        dest='action', help=_('specify action')
    )
    for command_cls in six.itervalues(commands):
        subparser = subparsers.add_parser(
            command_cls.name, help=command_cls.help)
        for command_args, kwargs in command_cls.arguments:
            subparser.add_argument(*command_args, **kwargs)

    # Get config class and add its arguments into command line parser
    if settings:
        config_cls = get_config_class(settings)
        if not issubclass(config_cls, Config):
            raise TypeError(
                "Config class must be subclass of the "
                "shelter.core.config.Config")
        for config_args, kwargs in config_cls.arguments:
            parser.add_argument(*config_args, **kwargs)
    else:
        config_cls = Config

    # Add help argument and parse command line
    parser.add_argument(
        '-h', '--help', action='help',
        help=_('show this help message and exit')
    )
    cmdline_args = parser.parse_args(args)
    if not cmdline_args.action:
        parser.error(_('No action'))

    # Run management command
    command_cls = commands[cmdline_args.action]
    if command_cls.settings_required and not settings:
        parser.error(_(
            "Settings module is not defined. You must either set "
            "'SHELTER_SETTINGS_MODULE' environment variable or "
            "'-s/--settings' command line argument."
        ))
    try:
        config = config_cls(settings, cmdline_args)
    except ImproperlyConfiguredError as exc:
        parser.error(str(exc))
    command = command_cls(config)
    try:
        command()
    except Exception:
        traceback.print_exc(file=sys.stderr)
        sys.stderr.flush()
        if multiprocessing.active_children():
            # If main process has children processes, exit immediately without
            # cleaning. It is a workaround, because parent process waits for
            # non-daemon children.
            os._exit(1)
        sys.exit(1)
    sys.exit(0)
547351
def kwargs(self, obj, kwargs):
        '''
        
        '''
        if hasattr(obj, "KWARGS"):
            for module_argument in obj.KWARGS:
                if has_key(kwargs, module_argument.name):
                    arg_value = kwargs[module_argument.name]
                else:
                    arg_value = copy(module_argument.default)

                setattr(obj, module_argument.name, arg_value)

            for (k, v) in iterator(kwargs):
                if not hasattr(obj, k):
                    setattr(obj, k, v)
        else:
            raise Exception("binwalk.core.module.Modules.process_kwargs: %s has no attribute 'KWARGS'" % str(obj))
102029
def run_from_argv(self, prog, subcommand, global_options, argv):
        
        self.prog_name = prog
        parser = self.create_parser(prog, subcommand)
        options, args = parser.parse_args(argv)
        self.global_options = global_options
        self.options = options
        self.args = args
        self.execute(args, options, global_options)
651515
def parse_options(args) # :nodoc:
      option_parser_class = self.class.const_get("#{options[:subcommand_option_handling_strategy].to_s.capitalize}CommandOptionParser")
      OptionParsingResult.new.tap { |parsing_result|
        parsing_result.arguments = args
        parsing_result = @global_option_parser.parse!(parsing_result)
        option_parser_class.new(@accepts).parse!(parsing_result, options[:argument_handling_strategy])
      }
    end
679266
def process_list_arg(arg):
    
    if isinstance(arg, list):
        return arg
    elif isinstance(arg, basestring):
        args = []
        for part in arg.split(","):
            args.append(part.strip())
        return args
94969
def process_args
      args = @args.dup
      @options[:operands] = nil
      unless args.length >= 2
        puts @opts
        exit 1
      end
      @options[:operands] = args.shift(2)
      @options[:output_filename] = args.shift unless args.empty?
      @options[:output] ||= @options[:output_filename] || $stdout

      run
    end
774328
def process_args(pos_vals, kw_vals, rest_vals)
            result = {}

            # Process positional arguments
            pos_args = @definition.positional_args
            pos_args.each_with_index do |arg, i|
                break if i >= pos_vals.length
                result[arg.key] = process_arg_val(arg, pos_vals[i], result)
            end
            if pos_vals.size > pos_args.size
                if @definition.rest_args?
                    rest_vals = pos_vals[pos_args.size..-1] + rest_vals
                else
                    self.errors << "#{pos_vals.size} positional #{pos_vals.size == 1 ? 'argument' : 'arguments'} #{
                        pos_vals.size == 1 ? 'was' : 'were'} supplied, but only #{pos_args.size} #{
                        pos_args.size == 1 ? 'is' : 'are'} defined"
                end
            end

            # Process key-word based arguments
            kw_vals.each do |arg, val|
                result[arg.key] = process_arg_val(arg, val, result)
            end

            # Process rest values
            if rest_vals.size > 0
                if rest_arg = @definition.rest_args
                    result[rest_arg.key] = process_arg_val(rest_arg, rest_vals, result)
                else
                    self.errors << "#{rest_vals.size} rest #{rest_vals.size == 1 ? 'value' : 'values'} #{
                        rest_vals.size == 1 ? 'was' : 'were'} supplied, but no rest argument is defined"
                end
            end

            # Default unspecified arguments
            @definition.args.select{ |arg| !result.has_key?(arg.key) }.each do |arg|
                result[arg.key] = process_arg_val(arg, arg.default, result, true)
            end

            # Validate if any set requirements have been satisfied
            self.errors.concat(@definition.validate_requirements(result))
            if self.errors.size > 0
                @show_usage = true
            elsif result.empty?
                EmptyArgs.new
            else
                props = result.keys
                @definition.args.each{ |arg| props << arg.key unless result.has_key?(arg.key) }
                args = Struct.new(*props)
                args.new(*result.values)
            end
        end
1315205
def main(argv=None):
    
    if not argv:
        argv = sys.argv[1:]

    parser = argparse.ArgumentParser(description=_HELP_TEXT)
    parser.add_argument('input', nargs='?', default=None)
    parser.add_argument('output', nargs='?', default=None)
    parser.add_argument('--version', action='version',
                        version='%(prog)s ' + get_version())
    args = parser.parse_args(argv)

    if not args.input:
        print("No file specified", file=sys.stderr)
        sys.exit(1)

    try:
        with open(args.input, 'r') as f:
            res = mangle(f.read())
            if not args.output:
                print(res, end='')
            else:
                with open(args.output, 'w') as o:
                    o.write(res)
    except Exception as ex:
        print("Error mangling {}: {!s}".format(args.input, ex),
              file=sys.stderr)
        sys.exit(1)