Return an OptionParser for the script.
165197
def parse_args(sys_argv, usage):
    
    args = sys_argv[1:]

    parser = OptionParser(usage=usage)
    options, args = parser.parse_args(args)

    template, context = args

    return template, context
270008
def process_options(opts):
    """"""
    # Convert match and exclude args into pattern lists
    match = opts.get("match")
    if match and type(match) is str:
        opts["match"] = [pat.strip() for pat in match.split(",")]
    elif match:
        assert type(match) is list
    else:
        opts["match"] = []

    exclude = opts.get("exclude")
    if exclude and type(exclude) is str:
        opts["exclude"] = [pat.strip() for pat in exclude.split(",")]
    elif exclude:
        assert type(exclude) is list
    else:
        # opts["exclude"] = DEFAULT_OMIT
        opts["exclude"] = []
708390
def _load_options(parser):
    
    config = dict(
        MESSAGE_DURATION=parser.getint('gui', 'message_duration'),
        GUI_WELCOME_LABLE=parser.get('gui', 'gui_welcome_label'),
        FULL_USER_NAMES=parser.getboolean('gui', 'full_user_names'),
        LARGE_FONT_SIZE=parser.getint('gui', 'large_font_size'),
        MEDIUM_FONT_SIZE=parser.getint('gui', 'medium_font_size'),
        SMALL_FONT_SIZE=parser.getint('gui', 'small_font_size'),
        TINY_FONT_SIZE=parser.getint('gui', 'tiny_font_size'),
        MAX_INPUT_LENGTH=parser.getint('gui', 'max_input_length'),
    )
    return config
1204172
def add_command_line_options(cls, parser):
        """"""
        if "add_argument" in dir(parser):
            return cls.add_command_line_options_argparse(parser)
        else:
            return cls.add_command_line_options_optparse(parser)
15578
def options(self):
        """"""
        arg = self.get(0)
        if arg.startswith('-') and not self.is_asking_for_help:
            return arg[1:]
        return ''.join(x for x in arg if x in 'dgktz')
958259
function parseOptions(opts) {
  opts = opts || {};
  var argv = [];
  var options = {};
  var process_argv = process.argv;
  for (var i = 2; i < process_argv.length; i++) {
    if (process_argv[i].indexOf('--') == 0) {
      var arg = process_argv[i];
      if (arg.indexOf("=") > 0) {
        var arg_kv = arg.split('=');
        arg = arg_kv[0];
        arg = arg.replace('--','');
        arg = replaceAll(arg, '-', '_');
        options[arg] = arg_kv[1];
        if (typeof opts[arg] == 'string') {
          if (opts[arg] == 'int' || opts[arg] == 'integer') {
            options[arg] = parseInt(options[arg]);
          } else if (opts[arg] == 'float') {
            options[arg] = parseFloat(options[arg]);
          }
        } else if (typeof opts[arg] == 'object') {
          if (opts[arg].type == 'array') {
            var sep = opts[arg].separator || opts[arg].sep || ',';
            options[arg] = options[arg].split(sep);
          }
        }
      } else {
        arg = arg.replace('--','');
        arg = replaceAll(arg, '-', '_');
        options[arg] = true;
      }
    } else {
      argv.push(process_argv[i]);
    }
  }
  options.argv = argv;
  return options;
}
207709
def get_parser():
    """"""
    from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter
    parser = ArgumentParser(description=__doc__,
                            formatter_class=ArgumentDefaultsHelpFormatter)
    parser.add_argument("-n",
                        dest="n", default=10, type=int,
                        help="Show TOP-N results")
    parser.add_argument("--port",
                        dest="port", default=5000, type=int,
                        help="where should the webserver run")
    parser.add_argument("--use_segmenter",
                        dest="use_segmenter",
                        default=False,
                        action='store_true',
                        help=("try to segment the input for multiple symbol "
                              "recognition"))
    return parser
555147
def create_parser(self):
        
        return OptionParser(prog=self.prog_name,
                            usage=self.usage(),
                            version='%%prog %s' % self.get_version(),
                            option_list=self.option_list)
702985
def build_option_parser(parser):
    """"""
    parser.add_argument(
        "--os-data-processing-api-version",
        metavar="<data-processing-api-version>",
        default=utils.env(
            'OS_DATA_PROCESSING_API_VERSION',
            default=DEFAULT_DATA_PROCESSING_API_VERSION),
        help=("Data processing API version, default=" +
              DEFAULT_DATA_PROCESSING_API_VERSION +
              ' (Env: OS_DATA_PROCESSING_API_VERSION)'))
    parser.add_argument(
        "--os-data-processing-url",
        default=utils.env(
            "OS_DATA_PROCESSING_URL"),
        help=("Data processing API URL, "
              "(Env: OS_DATA_PROCESSING_API_URL)"))
    return parser
1241666
def parse_options():
    """"""

    server, username, password, auto_update_soa = False, False, False, False

    prs = argparse.ArgumentParser(description='usage')
    prs.add_argument('-v', '--version', action='version',
                     version=__version__)
    if os.environ.get('HOME'):
        config_file = os.environ.get('HOME') + '/.tdclirc'
        if os.path.isfile(config_file):
            (server, username,
             password, auto_update_soa) = check_config(config_file)

    conn = dict(server=server, username=username,
                password=password, auto_update_soa=auto_update_soa)

    subprs = prs.add_subparsers(help='commands')

    # Convert and print JSON
    parse_show(subprs)

    # Retrieve records
    parse_get(subprs, conn)

    # Create record
    parse_create(subprs, conn)

    # Create bulk_records
    parse_bulk_create(subprs, conn)

    # Delete record
    parse_delete(subprs, conn)

    # Delete bulk_records
    parse_bulk_delete(subprs, conn)

    # Update a record
    parse_update(subprs, conn)

    # Update SOA serial
    parse_update_soa(subprs, conn)

    # Create zone
    parse_create_zone(subprs, conn)

    # Delete zone
    parse_delete_zone(subprs, conn)

    # Retrieve template
    parse_get_tmpl(subprs, conn)

    # Delete template
    parse_delete_tmpl(subprs, conn)

    args = prs.parse_args()
    return args
264345
def make_parser():
    """"""
    p = optparse.OptionParser()
    p.add_option('--prefix', metavar='DIR', help='install SDK in DIR')
    p.add_option('--bindir', metavar='DIR', help='install tools in DIR')
    p.add_option('--force', action='store_true', default=False,
        help='over-write existing installation')
    p.add_option('--no-bindir', action='store_true', default=False,
        help='do not install tools on DIR')

    return p
1252129
def main():
    
    from optparse import OptionParser, OptionGroup
    from os import sep
    from os.path import basename, getsize
    from sys import argv, exit as sysExit
    from chardet import detect
    from codecs import BOM_UTF8, open as codecsOpen

    def optParse():
        """
        Parses command line options.

        Generally we're supporting all the command line options that doxypy.py
        supports in an analogous way to make it easy to switch back and forth.
        We additionally support a top-level namespace argument that is used
        to trim away excess path information.
        """

        parser = OptionParser(prog=basename(argv[0]))

        parser.set_usage("%prog [options] filename")
        parser.add_option(
            "-a", "--autobrief",
            action="store_true", dest="autobrief",
            help="parse the docstring for @brief description and other information"
        )
        parser.add_option(
            "-c", "--autocode",
            action="store_true", dest="autocode",
            help="parse the docstring for code samples"
        )
        parser.add_option(
            "-n", "--ns",
            action="store", type="string", dest="topLevelNamespace",
            help="specify a top-level namespace that will be used to trim paths"
        )
        parser.add_option(
            "-t", "--tablength",
            action="store", type="int", dest="tablength", default=4,
            help="specify a tab length in spaces; only needed if tabs are used"
        )
        parser.add_option(
            "-s", "--stripinit",
            action="store_true", dest="stripinit",
            help="strip __init__ from namespace"
        )
        parser.add_option(
            "-O", "--object-respect",
            action="store_true", dest="object_respect",
            help="By default, doxypypy hides object class from class dependencies even if class inherits explictilty from objects (new-style class), this option disable this."
        )
        group = OptionGroup(parser, "Debug Options")
        group.add_option(
            "-d", "--debug",
            action="store_true", dest="debug",
            help="enable debug output on stderr"
        )
        parser.add_option_group(group)

        ## Parse options based on our definition.
        (options, filename) = parser.parse_args()

        # Just abort immediately if we are don't have an input file.
        if not filename:
            stderr.write("No filename given." + linesep)
            sysExit(-1)

        # Turn the full path filename into a full path module location.
        fullPathNamespace = filename[0].replace(sep, '.')[:-3]
        # Use any provided top-level namespace argument to trim off excess.
        realNamespace = fullPathNamespace
        if options.topLevelNamespace:
            namespaceStart = fullPathNamespace.find(options.topLevelNamespace)
            if namespaceStart >= 0:
                realNamespace = fullPathNamespace[namespaceStart:]
        if options.stripinit:
            realNamespace = realNamespace.replace('.__init__', '')
        options.fullPathNamespace = realNamespace

        return options, filename[0]

    # Figure out what is being requested.
    (options, inFilename) = optParse()

    # Figure out encoding of input file.
    numOfSampleBytes = min(getsize(inFilename), 32)
    sampleBytes = open(inFilename, 'rb').read(numOfSampleBytes)
    sampleByteAnalysis = detect(sampleBytes)
    encoding = sampleByteAnalysis['encoding'] or 'ascii'

    # Switch to generic versions to strip the BOM automatically.
    if sampleBytes.startswith(BOM_UTF8):
        encoding = 'UTF-8-SIG'
    if encoding.startswith("UTF-16"):
        encoding = "UTF-16"
    elif encoding.startswith("UTF-32"):
        encoding = "UTF-32"

    # Read contents of input file.
    if encoding == 'ascii':
        inFile = open(inFilename)
    else:
        inFile = codecsOpen(inFilename, encoding=encoding)
    lines = inFile.readlines()
    inFile.close()
    # Create the abstract syntax tree for the input file.
    astWalker = AstWalker(lines, options, inFilename)
    astWalker.parseLines()
    # Output the modified source.
    print(astWalker.getLines())
685454
def command_with_options(self):
        """"""
        if 'args' in self.config:
            return ' '.join((self.command, self.config['args']))
        return self.command
169361
def _create_option_parser(cls):
        """"""
        from optparse import OptionParser, OptionGroup

        parser = OptionParser(
            version=__version__,
            usage='Usage: pydocstyle [options] [<file|dir>...]')

        option = parser.add_option

        # Run configuration options
        option('-e', '--explain', action='store_true', default=False,
               help='show explanation of each error')
        option('-s', '--source', action='store_true', default=False,
               help='show source for each error')
        option('-d', '--debug', action='store_true', default=False,
               help='print debug information')
        option('-v', '--verbose', action='store_true', default=False,
               help='print status information')
        option('--count', action='store_true', default=False,
               help='print total number of errors to stdout')
        option('--config', metavar='<path>', default=None,
               help='use given config file and disable config discovery')

        parser.add_option_group(OptionGroup(
            parser,
            'Note',
            'When using --match, --match-dir or --ignore-decorators consider '
            'whether you should use a single quote (\') or a double quote ("), '
            'depending on your OS, Shell, etc.'))

        check_group = OptionGroup(
            parser,
            'Error Check Options',
            'Only one of --select, --ignore or --convention can be '
            'specified. If none is specified, defaults to '
            '`--convention=pep257`. These three options select the "basic '
            'list" of error codes to check. If you wish to change that list '
            '(for example, if you selected a known convention but wish to '
            'ignore a specific error from it or add a new one) you can '
            'use `--add-[ignore/select]` in order to do so.')
        add_check = check_group.add_option

        # Error check options
        add_check('--select', metavar='<codes>', default=None,
                  help='choose the basic list of checked errors by '
                       'specifying which errors to check for (with a list of '
                       'comma-separated error codes or prefixes). '
                       'for example: --select=D101,D2')
        add_check('--ignore', metavar='<codes>', default=None,
                  help='choose the basic list of checked errors by '
                       'specifying which errors to ignore out of all of the '
                       'available error codes (with a list of '
                       'comma-separated error codes or prefixes). '
                       'for example: --ignore=D101,D2')
        add_check('--convention', metavar='<name>', default=None,
                  help='choose the basic list of checked errors by specifying '
                       'an existing convention. Possible conventions: {}.'
                       .format(', '.join(conventions)))
        add_check('--add-select', metavar='<codes>', default=None,
                  help='add extra error codes to check to the basic list of '
                       'errors previously set by --select, --ignore or '
                       '--convention.')
        add_check('--add-ignore', metavar='<codes>', default=None,
                  help='ignore extra error codes by removing them from the '
                       'basic list previously set by --select, --ignore '
                       'or --convention.')

        parser.add_option_group(check_group)

        # Match clauses
        option('--match', metavar='<pattern>', default=None,
               help=("check only files that exactly match <pattern> regular "
                     "expression; default is --match='{}' which matches "
                     "files that don't start with 'test_' but end with "
                     "'.py'").format(cls.DEFAULT_MATCH_RE))
        option('--match-dir', metavar='<pattern>', default=None,
               help=("search only dirs that exactly match <pattern> regular "
                     "expression; default is --match-dir='{}', which "
                     "matches all dirs that don't start with "
                     "a dot").format(cls.DEFAULT_MATCH_DIR_RE))

        # Decorators
        option('--ignore-decorators', metavar='<decorators>', default=None,
               help=("ignore any functions or methods that are decorated "
                     "by a function with a name fitting the <decorators> "
                     "regular expression; default is --ignore-decorators='{}'"
                     " which does not ignore any decorated functions."
                     .format(cls.DEFAULT_IGNORE_DECORATORS_RE)))

        return parser
1241850
def get_parser(parser=None):
    """"""
    from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter
    if parser is None:
        parser = ArgumentParser(description=__doc__,
                                formatter_class=ArgumentDefaultsHelpFormatter)
    subparsers = parser.add_subparsers()
    pkg_init_parser = subparsers.add_parser('init')
    pkg_init_parser.add_argument("root",
                                 nargs='?',
                                 help="project root - should be empty")
    pkg_init_parser.set_defaults(func=run_init)
    return parser
678974
def program_options(self, args):
        """"""
        options = {}
        for name, rule in self.option_rules.items():
            val = rule(args)
            if val is not None:
                options[name] = val
        return options
213181
def _apply2parser(arguments, options, parser):
    
    for args, kwargs in options:
        parser.option(*args, **kwargs)
    for args, kwargs in arguments:
        parser.argument(*args, **kwargs)
    return parser