Command line options and arguments parsing. This function return
    a list of options and the list of arguments (pattern, filenames).
545925
def create_argument_parser():
    
    parser = argparse.ArgumentParser(prog='lograptor', description=__description__, add_help=False)
    parser.usage = """%(prog)s [options] PATTERN [FILE ...]
    %(prog)s [options] [-e PATTERN | -f FILE] [FILE ...]
    Try '%(prog)s --help' for more information."""

    group = parser.add_argument_group("General Options")
    group.add_argument(
        "--conf", dest="cfgfiles", action='append', default=None, metavar="FILE",
        help="use a specific configuration file"
    )
    group.add_argument(
        "-d", dest="loglevel", default=2, type=int, metavar="[0-4]", choices=range(5),
        help="Logging level (default is 2, use 4 for debug). A level of 0 suppress also "
             "error messages about nonexistent or unreadable files."
    )
    group.add_argument('-V', '--version', action='version', version=__version__)
    group.add_argument('--help', action='help', help="show this help message and exit")

    group = parser.add_argument_group("Scope Selection")
    group.add_argument(
        "-a", "--apps", metavar='APP[,APP...]', type=comma_separated_string,
        default=[], help="process the log lines related to a list of applications"
    )
    group.add_argument(
        "--hosts", metavar="HOSTNAME/IP[,HOSTNAME/IP...]", type=comma_separated_string,
        default=[], help="process the log lines related to an hostname/IP"
    )
    group.add_argument(
        "-F", "--filter", metavar="FIELD=PATTERN[,FIELD=PATTERN...]",
        action="append", dest="filters", type=filter_spec, default=[],
        help="process the log lines that match all the conditions for rule's field values"
    )
    group.add_argument(
        "--time", metavar="HH:MM,HH:MM", type=TimeRange, action="store", dest="time_range",
        help="process the log lines related to a time range"
    )
    group.add_argument(
        "--date", metavar="[YYYY]MMDD[,[YYYY]MMDD]", action="store", dest="time_period",
        type=date_interval_spec, help="restrict the search scope to a date or a date interval"
    )
    group.add_argument(
        "--last", action="store", dest="time_period", type=last_period_spec,
        metavar="[hour|day|week|month|Nh|Nd|Nw|Nm]",
        help="restrict the search scope to a previous time period"
    )

    group = parser.add_argument_group("Matcher Selection")
    group.add_argument(
        "-G", "--ruled", dest='matcher', action=StoreOptionAction,
        help="use patterns and application rules (default)"
    )
    group.add_argument(
        "-X", "--unruled", dest='matcher', action=StoreOptionAction,
        help="use patterns only, skip application rules"
    )
    group.add_argument(
        "-U", "--unparsed", dest='matcher', action=StoreOptionAction,
        help="match the patterns, don't match any application rule"
    )

    group = parser.add_argument_group("Matching Control")
    group.add_argument(
        "-e", "--regexp", metavar="PATTERN", dest="patterns", default=[],
        action="append", help="use PATTERN for matching"
    )
    group.add_argument(
        "-f", "--file", metavar="FILE", dest="pattern_files", default=[],
        action="append", help="obtain patterns from FILE"
    )
    group.add_argument(
        "-i", "--ignore-case", action="store_true", dest="case", default=False,
        help="ignore case distinctions"
    )
    group.add_argument(
        "-v", "--invert-match", action="store_true", dest="invert", default=False,
        help="invert the sense of patterns regexp matching"
    )
    group.add_argument(
        "-w", "--word-regexp", action="store_true", dest="word", default=False,
        help="force PATTERN to match only whole words"
    )

    group = parser.add_argument_group("General Output Control")
    group.add_argument(
        "--output", default=['stdout'], metavar='CHANNEL[,CHANNEL...]', dest='channels',
        type=comma_separated_string, help="send output to channels (default: ['stdout'])"
    )
    group.add_argument(
        "-c", "--count", action="store_true", default=False,
        help="print only a count of matching lines per FILE"
    )
    group.add_argument(
        "--color", default='auto', nargs='?', choices=['auto', 'always', 'never'],
        help="use markers to highlight the matching strings"
    )
    group.add_argument(
        "-L", "--files-without-match", action="store_false", dest="files_with_match", default=None,
        help="print only names of FILEs containing no match"
    )
    group.add_argument(
        "-l", "--files-with-match", action="store_true", dest="files_with_match",
        help="print only names of FILEs containing matches"
    )
    group.add_argument(
        "-m", "--max-count", metavar='NUM', action="store", type=positive_integer, default=0,
        help="stop after NUM matches"
    )
    group.add_argument(
        "-o", "--only-matching", action="store_true", default=False,
        help="show only the part of a line matching PATTERN"
    )
    group.add_argument(
        "-q", "--quiet", action="store_true", default=False, help="suppress all normal output"
    )
    group.add_argument(
        "-s", "--no-messages", action="store_const", const=0, dest='loglevel',
        help="suppress error messages (equivalent to -d 0)"
    )

    group = parser.add_argument_group("Output Data Control")
    group.add_argument(
        "--report", metavar='NAME', nargs='?', default=False,
        help="produce a report at the end of processing"
    )
    group.add_argument(
        "--ip-lookup", action="store_true", default=False,
        help="translate IP addresses to DNS names"
    )
    group.add_argument(
        "--uid-lookup", action="store_true", default=False,
        help="translate UIDs to usernames"
    )
    group.add_argument(
        "--anonymize", action="store_true", default=False,
        help="anonymize defined rule's fields value"
    )

    group = parser.add_argument_group("Output Line Prefix Control")
    group.add_argument(
        "-n", "--line-number", action="store_true", default=False,
        help="print line number with output lines"
    )
    group.add_argument(
        "-H", "--with-filename", action="store_true", dest="with_filename", default=None,
        help="print the file name for each match"
    )
    group.add_argument(
        "-h", "--no-filename", action="store_false", dest="with_filename", default=None,
        help="suppress the file name prefix on output"
    )

    group = parser.add_argument_group("Context Line Control")
    group.add_argument(
        "-T", "--thread", action="store_true", default=False,
        help="the context is the log thread of the application"
    )
    group.add_argument(
        "-B", "--before-context", metavar='NUM', type=positive_integer, default=0,
        help="print NUM lines of leading context"
    )
    group.add_argument(
        "-A", "--after-context", metavar='NUM', type=positive_integer, default=0,
        help="print NUM lines of trailing context"
    )
    group.add_argument(
        "-C", "--context", metavar='NUM', type=positive_integer, default=0,
        help="print NUM lines of output context"
    )
    group.add_argument(
        "--group-separator", metavar='SEP', default='--',
        help="use SEP as a group separator. By default SEP is double hyphen (--)."
    )
    group.add_argument(
        "--no-group-separator", dest="group_separator", action="store_const", const='',
        help="use empty string as a group separator"
    )

    group = parser.add_argument_group("File and Directory Selection")
    group.add_argument(
        "-r", "--recursive", action="store_true", default=False,
        help="read all files under each directory, recursively"
    )
    group.add_argument(
        "-R", "--dereference-recursive", action="store_true", default=False,
        help="likewise, but follow all symlinks"
    )
    group.add_argument(
        "--include", metavar='GLOB', default=[], action="append",
        help="search only files that match GLOB"
    )
    group.add_argument(
        "--exclude", metavar='GLOB', default=[], action="append",
        help="skip files and directories matching GLOB"
    )
    group.add_argument(
        "--exclude-from", metavar='FILE', default=[], action="append",
        help="skip files matching any file pattern from FILE"
    )
    group.add_argument(
        "--exclude-dir", metavar='DIR', default=[], action="append",
        help="exclude directories matching the pattern DIR"
    )

    parser.add_argument(
        'files', metavar='[FILE ...]', nargs='*',
        help='Input files. Each argument can be a file path or a glob pathname. '
             'A "-" stands for standard input. If no arguments are given then processes '
             'all the files included within the scope of the selected applications.'
    )
    return parser
617983
def parse_args(self, arguments=None):
        
        self._args = self.parser.parse_args(arguments)
        return self.args
431041
def parse_options(cls, options):
        
        d = {}
        for filename_check, dictionary in cls.filename_checks.items():
            # retrieve the marks from the passed options
            filename_data = getattr(options, filename_check)
            if len(filename_data) != 0:
                parsed_params = {}
                for single_line in filename_data:
                    a = [s.strip() for s in single_line.split('=')]
                    # whitelist the acceptable params
                    if a[0] in ['filter_regex', 'filename_regex']:
                        parsed_params[a[0]] = a[1]
                d[filename_check] = parsed_params
        cls.filename_checks.update(d)
        # delete any empty rules
        cls.filename_checks = {x: y for x, y in cls.filename_checks.items() if len(y) > 0}
356853
def ParseArguments(args):
  
  try:
    (opts, filenames) = getopt.getopt(args, '', ['help', 'output=', 'verbose=',
                                                 'counting=',
                                                 'filter=',
                                                 'root=',
                                                 'linelength=',
                                                 'extensions='])
  except getopt.GetoptError:
    PrintUsage('Invalid arguments.')

  verbosity = _VerboseLevel()
  output_format = _OutputFormat()
  filters = ''
  counting_style = ''

  for (opt, val) in opts:
    if opt == '--help':
      PrintUsage(None)
    elif opt == '--output':
      if val not in ('emacs', 'vs7', 'eclipse'):
        PrintUsage('The only allowed output formats are emacs, vs7 and eclipse.')
      output_format = val
    elif opt == '--verbose':
      verbosity = int(val)
    elif opt == '--filter':
      filters = val
      if not filters:
        PrintCategories()
    elif opt == '--counting':
      if val not in ('total', 'toplevel', 'detailed'):
        PrintUsage('Valid counting options are total, toplevel, and detailed')
      counting_style = val
    elif opt == '--root':
      global _root
      _root = val
    elif opt == '--linelength':
      global _line_length
      try:
          _line_length = int(val)
      except ValueError:
          PrintUsage('Line length must be digits.')
    elif opt == '--extensions':
      global _valid_extensions
      try:
          _valid_extensions = set(val.split(','))
      except ValueError:
          PrintUsage('Extensions must be comma seperated list.')

  if not filenames:
    PrintUsage('No files were specified.')

  _SetOutputFormat(output_format)
  _SetVerboseLevel(verbosity)
  _SetFilters(filters)
  _SetCountingStyle(counting_style)

  return filenames
167782
def parse_arguments():
    
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "-c", dest="count", default=0, type=int,
        help="Number of pings to send"
    )
    parser.add_argument(
        "-i", dest="interval", default=1, type=float, help="Ping interval"
    )
    parser.add_argument(
        "-d", dest="timings", default=False, action="store_true",
        help="Show timings for the entire connection"
    )
    parser.add_argument(
        'destination', nargs='+', help='Destination host or URL'
    )
    args = parser.parse_args()
    return args, args.destination
302068
def parse_args(cls):
        
        # Initialize configuration and userdata directories.
        dirs = appdirs.AppDirs(__title__, 'Mozilla Security')
        if not os.path.isdir(dirs.user_config_dir):
            shutil.copytree(os.path.join(cls.HOME, 'examples'), dirs.user_config_dir)
            shutil.copytree(os.path.join(cls.HOME, 'userdata'), os.path.join(dirs.user_config_dir, 'userdata'))

        parser = argparse.ArgumentParser(
            description='Laniakea Runtime v{}'.format(cls.VERSION),
            prog=__title__,
            add_help=False,
            formatter_class=lambda prog: argparse.ArgumentDefaultsHelpFormatter(prog, max_help_position=40, width=120),
            epilog='The exit status is 0 for non-failures and 1 for failures.')

        subparsers = parser.add_subparsers(dest='provider',
                                           description='Use -h to see the help menu of each provider.',
                                           title='Laniakea Cloud Providers',
                                           metavar='')

        modules = ModuleLoader()
        modules.load(cls.HOME, 'core/providers', 'laniakea')

        for name, module in modules.modules.items():
            globals()[name] = module

        for module, cli in modules.command_line_interfaces():
            getattr(module, cli).add_arguments(subparsers, dirs)

        base = parser.add_argument_group('Laniakea Base Parameters')
        base.add_argument('-verbosity',
                          default=2,
                          type=int,
                          choices=list(range(1, 6, 1)),
                          help='Log sensitivity.')

        base.add_argument('-focus',
                          action='store_true',
                          default=True,
                          help=argparse.SUPPRESS)

        base.add_argument('-settings',
                          metavar='path',
                          type=argparse.FileType(),
                          default=os.path.join(dirs.user_config_dir, 'laniakea.json'),
                          help='Laniakea core settings.')

        base.add_argument('-h', '-help', '--help',
                          action='help',
                          help=argparse.SUPPRESS)

        base.add_argument('-version',
                          action='version',
                          version='%(prog)s {}'.format(cls.VERSION),
                          help=argparse.SUPPRESS)

        userdata = parser.add_argument_group('UserData Parameters')
        userdata.add_argument('-userdata',
                              metavar='path',
                              type=argparse.FileType(),
                              help='UserData script for the provisioning process.')

        userdata.add_argument('-list-userdata-macros',
                              action='store_true',
                              help='List available macros.')

        userdata.add_argument('-print-userdata',
                              action='store_true',
                              help='Print the UserData script to stdout.')

        userdata.add_argument('-userdata-macros',
                              metavar='k=v',
                              nargs='+',
                              type=str,
                              help='Custom macros for the UserData.')

        return parser.parse_args()
1348575
def parse_args(self):
        
        parser = ArgumentParser(description='',
                                formatter_class=RawTextHelpFormatter)
        parser.add_argument("--generate", action="store", dest='generate',
                            choices=['command', 'docker-run', 'docker-compose',
                                     'ini', 'env', 'kubernetes', 'readme', 'drone-plugin'],
                            help="Generate a template ")
        parser.add_argument("--settings", action="store", dest='settings',
                            help="Specify a settings file. (ie settings.dev)")
        for key, value in self.spec.items():
            if value['type'] in [str, int, float]:
                parser.add_argument(f"--{key.lower()}", action="store", dest=key,
                                    type=value['type'],
                                    choices=value.get("choices"),
                                    help=self.help(value))
            elif value['type'] == bool:
                parser.add_argument(f"--{key.lower()}", action="store", dest=key,
                                    type=lambda x:bool(strtobool(x)),
                                    choices=value.get("choices"),
                                    help=self.help(value))
            elif value['type'] == list:
                parser.add_argument(f"--{key.lower()}", action="store", dest=key,
                                    nargs='+',
                                    choices=value.get("choices"),
                                    help=self.help(value))
            elif value['type'] == dict:
                parser.add_argument(f"--{key.lower()}", action="store", dest=key,
                                    type=json.loads,
                                    choices=value.get("choices"),
                                    help=self.help(value))
        args, _unknown = parser.parse_known_args()
        return args
1284067
def _parse_args(argv):
    
    parser = make_parser()
    args = parser.parse_args(argv)
    LOGGER.setLevel(to_log_level(args.loglevel))

    if args.inputs:
        if '-' in args.inputs:
            args.inputs = sys.stdin
    else:
        if args.list:
            _show_psrs()
        elif args.env:
            cnf = os.environ.copy()
            _output_result(cnf, args.output, args.otype or "json", None, None)
            sys.exit(0)
        else:
            parser.print_usage()
            sys.exit(1)

    if args.validate and args.schema is None:
        _exit_with_output("--validate option requires --scheme option", 1)

    return args
1153502
def _parse_args():
    """"""
    class HelpOnErrorArgParser(argparse.ArgumentParser):
        """Print help message as well when an error is raised."""
        def error(self, message):
            sys.stderr.write("Error: %s\n" % message)
            self.print_help()
            sys.exit(2)

    def validate(_file):
        """Validate if the given target argument is a valid file or a valid directory"""
        _file = abspath(_file)
        if not exists(_file):
            if not exists(dirname(_file)):
                # Argparse uses the ArgumentTypeError to give a rejection message like:
                # error: argument input: x does not exist
                raise argparse.ArgumentTypeError("{0} does not exist".format(_file))
        return _file

    def expand_cg_args(cg_args):
        """Separate clubbed flags in command line args for the generator.py

        Allows flags to be clubbed like, -ilt example.txt.
        """
        expanded = list()
        for item in cg_args:
            if len(item) < 3:
                # If at all a flag, must be single flag
                expanded.append(item)
                continue
            if item.startswith("-"):
                if not item.startswith("--"):
                    for flag in item[1:]:
                        expanded.append('-' + flag)
                    continue
            expanded.append(item)
        return expanded

    class AssignDefaultIgnore(argparse.Action):
        """If argument is specified but nothing provided, use pre-defined.

        nargs="*" doesn't allow const and default kwarg can't be used as we might not want to
        ignore as well.
        """
        def __call__(self, parser, args, values, option_string=None):
            if values is not None and not len(values):
                values = IGNORE_METHODS
            setattr(args, self.dest, values)

    try:
        indx = sys.argv.index('--')
        cg_args, sys.argv = sys.argv[1:indx], sys.argv[:1] + sys.argv[indx + 1:]
    except ValueError:
        cg_args = []

    cg_args = expand_cg_args(cg_args)  # allow -il type of usage
    parser = HelpOnErrorArgParser(description=DESCRIPTION)
    parser.add_argument(
        "-l", "--long", action='store_true', default=False,
        help="File reference of method in call graph is absolute, i.e. starts with ansible, "
             "otherwise just the basename if not __init__.py")
    parser.add_argument(
        "-t", "--target", nargs="?", type=validate, const=TARGET_FILE, default=TARGET_FILE,
        help="Filepath to write call graph, defaults to %(default)s")
    parser.add_argument(
        "-i", "--ignore", nargs='*', action=AssignDefaultIgnore,
        help="Methods to ignore while generating call graph")
    # TODO: Aloow classes that can be intercepted
    parser.usage = \
        parser.format_usage()[len("usage: "):].rstrip() + " -- <ansible-playbook options>\n"
    cg_args = parser.parse_args(cg_args)

    if not len(sys.argv[1:]):
        parser.print_help()
        sys.exit(2)

    return cg_args
76821
def _parse_known_pattern(self, pattern: str) -> List[str]:
        
        if pattern.endswith(os.path.sep):
            patterns = [
                filename
                for filename in os.listdir(pattern)
                if os.path.isdir(os.path.join(pattern, filename))
            ]
        else:
            patterns = [pattern]

        return patterns
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
730126
def parse_arg_list(param_start):
    
    values = [arg[len(param_start):]
              for arg in sys.argv
              if arg.startswith(param_start)]

    # remove recognized arguments from the sys.argv
    otherArgs = [arg
                 for arg in sys.argv
                 if not arg.startswith(param_start)]
    sys.argv = otherArgs

    return values
1353729
def _parse_command_line_arguments():
    
    global config
    # Get command line args for vispy
    argnames = ['vispy-backend=', 'vispy-gl-debug', 'vispy-glir-file=',
                'vispy-log=', 'vispy-help', 'vispy-profile=', 'vispy-cprofile',
                'vispy-dpi=', 'vispy-audit-tests']
    try:
        opts, args = getopt.getopt(sys.argv[1:], '', argnames)
    except getopt.GetoptError:
        opts = []
    # Use them to set the config values
    for o, a in opts:
        if o.startswith('--vispy'):
            if o == '--vispy-backend':
                config['default_backend'] = a
                logger.info('vispy backend: %s', a)
            elif o == '--vispy-gl-debug':
                config['gl_debug'] = True
            elif o == '--vispy-glir-file':
                config['glir_file'] = a
            elif o == '--vispy-log':
                if ',' in a:
                    verbose, match = a.split(',')
                else:
                    verbose = a
                    match = None
                config['logging_level'] = a
                set_log_level(verbose, match)
            elif o == '--vispy-profile':
                config['profile'] = a
            elif o == '--vispy-cprofile':
                _enable_profiling()
            elif o == '--vispy-help':
                print(VISPY_HELP)
            elif o == '--vispy-dpi':
                config['dpi'] = int(a)
            elif o == '--vispy-audit-tests':
                config['audit_tests'] = True
            else:
                logger.warning("Unsupported vispy flag: %s" % o)
853188
def command_line(argv):
    
    arguments = parse_command_line(argv)
    if arguments.generate:
        generate_fixer_file(arguments.generate)
    paths = edit_files(arguments.patterns,
                       expressions=arguments.expressions,
                       functions=arguments.functions,
                       executables=arguments.executables,
                       start_dirs=arguments.start_dirs,
                       max_depth=arguments.max_depth,
                       dry_run=arguments.dry_run,
                       output=arguments.output,
                       encoding=arguments.encoding,
                       newline=arguments.newline)
    # If the output is not sys.stdout, we need to close it because
    # argparse.FileType does not do it for us.
    is_sys = arguments.output in [sys.stdout, sys.stderr]
    if not is_sys and isinstance(arguments.output, io.IOBase):
        arguments.output.close()
    return paths
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)
920723
def parseargs(argv):
    ''''''
    args = []
    options = {}
    key = None
    for arg in argv:
        if arg in DEFAULT_OPTION_VALUES:
            key = arg.strip('=').replace('-', '_')
            options[key] = ()
        elif key is None:
            args.append(arg)
        else:
            options[key] += (arg,)

    if set(args) & {'-h', '--help'}:
        print(__doc__, end='')
        exit(0)
    elif set(args) & {'-V', '--version'}:
        print(__version__)
        exit(0)
    elif args:
        exit('invalid option: %s\nTry --help for more information.' % args[0])

    return options
1304158
public static CommandLine parse(Options options, String... args) throws Exception {
        return CommandLineParser.parse(options, args);
    }