Parses the commandline. Typically called by Trollop::options,
 but you can call it directly if you need more control.

 throws CommandlineError, HelpNeeded, and VersionNeeded exceptions.
17553
def parse(cmdline = ARGV)
			vals = {}
			required = {}

			opt :version, "Print version and exit" if @version && ! (@specs[:version] || @long["version"])
			opt :help, "Show this message" unless @specs[:help] || @long["help"]

			@specs.each do |sym, opts|
				required[sym] = true if opts.required?
				vals[sym] = opts.default
				vals[sym] = [] if opts.multi && !opts.default # multi arguments default to [], not nil
			end

			resolve_default_short_options!

			## resolve symbols
			given_args = {}
			@leftovers = each_arg cmdline do |arg, params|
				## handle --no- forms
				arg, negative_given = if arg =~ /^--no-([^-]\S*)$/
																["--#{$1}", true]
															else
																[arg, false]
															end

				sym = case arg
							when /^-([^-])$/      then @short[$1]
							when /^--([^-]\S*)$/  then @long[$1] || @long["no-#{$1}"]
							else                       raise CommandlineError, "invalid argument syntax: '#{arg}'"
							end

				sym = nil if arg =~ /--no-/ # explicitly invalidate --no-no- arguments

				next nil if ignore_invalid_options && !sym
				raise CommandlineError, "unknown argument '#{arg}'" unless sym

				if given_args.include?(sym) && !@specs[sym].multi?
					raise CommandlineError, "option '#{arg}' specified multiple times"
				end

				given_args[sym] ||= {}
				given_args[sym][:arg] = arg
				given_args[sym][:negative_given] = negative_given
				given_args[sym][:params] ||= []

				# The block returns the number of parameters taken.
				num_params_taken = 0

				unless params.empty?
					if @specs[sym].single_arg?
						given_args[sym][:params] << params[0, 1]  # take the first parameter
						num_params_taken = 1
					elsif @specs[sym].multi_arg?
						given_args[sym][:params] << params        # take all the parameters
						num_params_taken = params.size
					end
				end

				num_params_taken
			end

			## check for version and help args
			raise VersionNeeded if given_args.include? :version
			raise HelpNeeded if given_args.include? :help

			## check constraint satisfaction
			@constraints.each do |type, syms|
				constraint_sym = syms.find { |sym| given_args[sym] }
				next unless constraint_sym

				case type
				when :depends
					syms.each { |sym| raise CommandlineError, "--#{@specs[constraint_sym].long} requires --#{@specs[sym].long}" unless given_args.include? sym }
				when :conflicts
					syms.each { |sym| raise CommandlineError, "--#{@specs[constraint_sym].long} conflicts with --#{@specs[sym].long}" if given_args.include?(sym) && (sym != constraint_sym) }
				end
			end

			required.each do |sym, val|
				raise CommandlineError, "option --#{@specs[sym].long} must be specified" unless given_args.include? sym
			end

			## parse parameters
			given_args.each do |sym, given_data|
				arg, params, negative_given = given_data.values_at :arg, :params, :negative_given

				opts = @specs[sym]
				if params.empty? && !opts.flag?
					raise CommandlineError, "option '#{arg}' needs a parameter" unless opts.default
					params << (opts.array_default? ? opts.default.clone : [opts.default])
				end

				params[0].each do |p|
					raise CommandlineError, "option '#{arg}' only accepts one of: #{opts.permitted.join(', ')}" unless opts.permitted.include? p
				end unless opts.permitted.nil?

				vals["#{sym}_given".intern] = true # mark argument as specified on the commandline

				vals[sym] = opts.parse(params, negative_given)

				if opts.single_arg?
					if opts.multi?        # multiple options, each with a single parameter
						vals[sym] = vals[sym].map { |p| p[0] }
					else                  # single parameter
						vals[sym] = vals[sym][0][0]
					end
				elsif opts.multi_arg? && !opts.multi?
					vals[sym] = vals[sym][0]  # single option, with multiple parameters
				end
				# else: multiple options, with multiple parameters

				opts.callback.call(vals[sym]) if opts.callback
			end

			## modify input in place with only those
			## arguments we didn't process
			cmdline.clear
			@leftovers.each { |l| cmdline << l }

			## allow openstruct-style accessors
			class << vals
				def method_missing(m, *_args)
					self[m] || self[m.to_s]
				end
			end
			vals
		end
1301224
def parse_args
      parser = Trollop::Parser.new do
        opt :max_attempts, "", :default => DEFAULT_MAX_ATTEMPTS, :long => "--attempts", :short => "-a"
        opt :retry_interval, "", :default => DEFAULT_RETRY_INTERVAL
        opt :time_limit, "", :type => :int
        opt :daemon, "", :long => "--start"
        opt :stop
        opt :ping
        opt :verbose
        opt :state_path, "", :type => String
        version ""
      end
      
      parse do
        options = parser.parse
        options.delete(:max_attempts) unless options[:max_attempts] > 0
        if options[:delete]
          options.delete(:time_limit) unless options[:time_limit] > 0
        end
        options.delete(:retry_interval) unless options[:retry_interval] > 0
        options
      end
    end
485984
def parse(self, lines):
        
        # states:
        #   0: start state
        #   1: saw user-agent line
        #   2: saw an allow or disallow line
        state = 0
        entry = Entry()

        for line in lines:
            if not line:
                if state == 1:
                    entry = Entry()
                    state = 0
                elif state == 2:
                    self._add_entry(entry)
                    entry = Entry()
                    state = 0
            # remove optional comment and strip line
            i = line.find('#')
            if i >= 0:
                line = line[:i]
            line = line.strip()
            if not line:
                continue
            line = line.split(':', 1)
            if len(line) == 2:
                line[0] = line[0].strip().lower()
                line[1] = urllib.parse.unquote(line[1].strip())
                if line[0] == "user-agent":
                    if state == 2:
                        self._add_entry(entry)
                        entry = Entry()
                    entry.useragents.append(line[1])
                    state = 1
                elif line[0] == "disallow":
                    if state != 0:
                        entry.rulelines.append(RuleLine(line[1], False))
                        state = 2
                elif line[0] == "allow":
                    if state != 0:
                        entry.rulelines.append(RuleLine(line[1], True))
                        state = 2
        if state == 2:
            self._add_entry(entry)
1281175
def parse (cls, line, lineno, log, cmddict):
    
    delay   = SeqDelay   .parse(line, lineno, log, cmddict)
    attrs   = SeqCmdAttrs.parse(line, lineno, log, cmddict)
    comment = SeqComment .parse(line, lineno, log, cmddict)
    stop    = len(line)

    if comment:
      stop = comment.pos.col.start - 1

    if attrs and attrs.pos.col.stop != -1:
      stop = attrs.pos.col.start - 1

    tokens = line[:stop].split()
    name   = tokens[1]
    args   = tokens[2:]
    start  = line.find(name)
    pos    = SeqPos(line, lineno, start + 1, stop)

    if name not in cmddict:
      log.error('Unrecognized command "%s".' % name, pos)
    elif cmddict[name].nargs != len(args):
      msg = 'Command argument size mismatch: expected %d, but encountered %d.'
      log.error(msg % (cmddict[name].nargs, len(args)), pos)

    args   = [ util.toNumber(a, a) for a in args ]
    cmd    = cmddict.create(name, *args)

    return cls(cmd, delay, attrs, comment, pos)
418054
def parse(self, line, **options):
        
        line = line.strip()
        if not line:
            return (False, (), {})
        split = line.split()
        cmd, args = split[0], split[1:]
        return (cmd, args, {})
152866
public void run(String[] args) {
    // Add and parse options.
    OptionParser parser = new OptionParser();
    initializeCommonOptions(parser);
    initializeOptions(parser);

    String errorMessage = null;
    try {
      parsedOptions = parser.parse(args);
    } catch (OptionException e) {
      errorMessage = e.getMessage();
    }

    boolean printHelp = false;
    if (errorMessage != null) {
      // If an error occurs, the options don't parse.
      // Therefore, we must manually check if the help option was
      // given.
      for (int i = 0; i < args.length; i++) {
        if (args[i].equals("--help")) {
          printHelp = true;
        }
      }
    }

    if (errorMessage != null && !printHelp) {
      System.err.println(errorMessage);
      System.err.println("Try --help for more information about options.");
      System.exit(1);
    }

    if (printHelp || parsedOptions.has(helpOpt)) {
      // If a help option is given, print help then quit.
      try {
        parser.printHelpOn(System.err);
      } catch (IOException ioException) {
        throw new RuntimeException(ioException);
      }
      System.exit(0);
    }

    // Log any passed-in options.
    if (!parsedOptions.has(noPrintOptions)) {
      System.out.println("Command-line options:");
      for (OptionSpec<?> optionSpec : parsedOptions.specs()) {
        if (parsedOptions.hasArgument(optionSpec)) {
          System.out.println("--" + Iterables.getFirst(optionSpec.options(), "") + " "
              + Joiner.on(" ").join(parsedOptions.valuesOf(optionSpec)));
        } else {
          System.out.println("--" + Iterables.getFirst(optionSpec.options(), ""));
        }
      }
      System.out.println("");
    }

    // Run the program.
    long startTime = System.currentTimeMillis();
    processOptions(parsedOptions);
    run(parsedOptions);
    long endTime = System.currentTimeMillis();

    if (!parsedOptions.has(noPrintOptions)) {
      System.out.println("Total time elapsed: " + TimeUtils.durationToString(endTime - startTime));
    }

    System.exit(0);
  }
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
328390
def parse_command_line
      begin
        opts = GetoptLong.new(
          [ '--logfile', '-l',      GetoptLong::REQUIRED_ARGUMENT ],
          [ '--verbose', '-v',      GetoptLong::NO_ARGUMENT ],
          [ '--quiet',   '-q',      GetoptLong::NO_ARGUMENT ],
          [ '--concurrency', '-c',  GetoptLong::REQUIRED_ARGUMENT ],
          [ '--delay', '-d',        GetoptLong::REQUIRED_ARGUMENT ],
          [ '--retry', '-y',        GetoptLong::REQUIRED_ARGUMENT ],
          [ '--port', '-p',         GetoptLong::REQUIRED_ARGUMENT ],
          [ '--bind-address', '-b', GetoptLong::REQUIRED_ARGUMENT ],
          [ '--help', '-h',         GetoptLong::NO_ARGUMENT ],
          [ '--exit', '-x', 				GetoptLong::NO_ARGUMENT ]
        )

        opts.each do |opt, arg|
          case opt
            when '--logfile', '-l'
              @logfile = arg
              Log.logger = Logger.new(@logfile)
            when '--concurrency', '-c'
              @concurrency = arg.to_i
            when '--delay', '-d'
              @delay = arg.to_i
            when '--retry', '-y'
              @retry_count = arg.to_i
            when '--verbose', '-v'
              @verbose = true
            when '--quiet',   '-q'
              @quiet = true
            when '--port', '-p'
              @port = arg
            when '--bind-address', '-b'
              @bind_address = arg.to_s
            when '--help', '-h'
              help
            when '--exit', '-x'
              uri = "http://localhost:#{@port}/admin"
              response = RestClient.post uri, { 'shutdown' => true }.to_yaml
              exit 0
          end
        end
      rescue GetoptLong::InvalidOption => ex
        puts "Syntax: chimpd [--logfile=<name>] [--concurrency=<c>] [--delay=<d>] [--retry=<r>] [--port=<p>] [--bind-address=<addr> ] [--verbose]"
        exit 1
      end

      #
      # Set up logging/verbosity
      #
      Chimp.set_verbose(@verbose, @quiet)

      if not @verbose
      	ENV['REST_CONNECTION_LOG'] = "/dev/null"
      	ENV['RESTCLIENT_LOG'] = "/dev/null"
        Log.threshold= Logger::INFO
      else
        Log.threshold= Logger::DEBUG
      end

      if @quiet
        Log.threshold = Logger::WARN
      end
    end
387573
def parse(args)
      @options = { :report => false }

      OptionParser.new do |parser|
        parser.banner = "Usage: todo_lint [options] [files]"
        add_config_options parser
        exclude_file_options parser
        include_extension_options parser
        report_version parser
        report_report_options parser
      end.parse!(args)

      # Any remaining arguments are assumed to be files
      options[:files] = args

      options
    end
580096
def parse(args):
    
    parser = make_parser()
    if not len(args):
        parser.print_help()
        sys.exit(1)
    parsed_args = parser.parse_args(args)
    if parsed_args.error == '-':
        parsed_args.error = None
    # 'micro' is False by default. If version is set to a Micro QR Code version,
    # encoder.encode raises a VersionError.
    # Small problem: --version=M4 --no-micro is allowed
    version = parsed_args.version
    if version is not None:
        version = str(version).upper()
    if not parsed_args.micro and version in ('M1', 'M2', 'M3', 'M4'):
        parsed_args.micro = None
    return _AttrDict(vars(parsed_args))
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
1150576
protected boolean processLine(final CommandLine line, final Options options)
            throws Exception {
        if (line.hasOption("version")) {
            System.out.println("version " + getVersion());
            return false;
        }
        if (line.hasOption("help")) {
            produceHelp(options);
            return false;
        }
        if (line.hasOption("config")) {
            setConfigFile(line.getOptionValue("config").trim());
        }
        if (line.hasOption("input")) {
            setInput(line.getOptionValue("input").trim());
        }
        if (line.hasOption("inputEncoding")) {
            setInputEncoding(line.getOptionValue("inputEncoding").trim());
        }
        if (line.hasOption("output")) {
            setOutput(line.getOptionValue("output").trim());
        }
        if (line.hasOption("targetNamespacePrefix")) {
            setTargetNamespacePrefix(line.getOptionValue(
                    "targetNamespacePrefix").trim());
        }
        if (line.hasOption("xsltFileName")) {
            setXsltFileName(line.getOptionValue(
                    "xsltFileName").trim());
        }

        return true;
    }
1128537
def parse_options!(args)
			@options = {}
			opts = ::OptionParser.new do |opts|
				opts.banner = "Usage: syswatch [options]\n\n  Options:"

				opts.on("-f", "--foreground", "Do not daemonize, just run in foreground.") do |f|
					@options[:foreground] = f
				end

				opts.on("-v", "--verbose", "Be verbose, print out some messages.") do |v|
					@options[:verbose] = v
				end

				opts.on("-t", "--test", "Test notifications.") do |t|
					@options[:test] = t
				end

				opts.on("-c", "--config [FILE]", "Use a specific config file, instead of `#{SysWatch::DEFAULTS[:config]}`") do |config|
					@options[:config] = config
				end
			end
			opts.parse! args
		end
1035375
def parse_command_line():
    

    import argparse

    parser = argparse.ArgumentParser(description=__doc__.split("\n")[0])
    parser.add_argument('-v',
                        '--version',
                        action='version',
                        version='%(prog)s ' + __version__,
                        help="Show version number and exit.")
    parser.add_argument('input_filename',
                        metavar='INPUT_FILE',
                        type=str,
                        help='Path of the input file to be preprocessed')
    parser.add_argument('-q',
                        '--quiet',
                        dest='should_be_quiet',
                        action='store_true',
                        default=False,
                        help="Disables verbose logging")
    parser.add_argument('-L',
                        '--log-level',
                        '--logging-level',
                        dest='logging_level',
                        choices=[
                            'DEBUG',
                            'INFO',
                            'WARNING',
                            'ERROR',
                            'CRITICAL',
                            'NONE',
                            ],
                        default='INFO',
                        help="Logging level.")
    parser.add_argument('-o',
                        '--output',
                        metavar="OUTPUT_FILE",
                        dest='output_filename',
                        default=None,
                        help='Output file name (default STDOUT)')
    parser.add_argument('-f',
                        '--force',
                        dest='should_force_overwrite',
                        action='store_true',
                        default=False,
                        help='Force overwrite existing output file.')
    parser.add_argument('-D',
                        '--define',
                        metavar="EXPR",
                        dest='definitions',
                        action='append',
                        help="""\
Define a variable for preprocessing. <define>
can simply be a variable name (in which case it
will be true) or it can be of the form
<var>=<val>. An attempt will be made to convert
<val> to an integer so -D 'FOO=0' will create a
false value.""")
    parser.add_argument('-I',
                        '--include',
                        metavar="DIR_PATH",
                        dest='include_paths',
                        action='append',
                        default=['.'],
                        help='Add a directory to the include path for #include directives.')
    parser.add_argument('-k',
                        '--keep-lines',
                        dest='should_keep_lines',
                        action='store_true',
                        default=False,
                        help='''\
Emit empty lines for preprocessor statement
lines and skipped output lines. This allows line
numbers to stay constant.''')
    parser.add_argument('-s',
                        '--substitute',
                        dest='should_substitute',
                        action='store_true',
                        default=False,
                        help='''\
Substitute #defines into emitted lines.
(Disabled by default to avoid polluting strings)''')
    parser.add_argument('--default-content-type',
                        metavar="CONTENT_TYPE",
                        dest='default_content_type',
                        default=None,
                        help='If the content type of the file cannot be determined this will be used. (Default: an error is raised)')
    parser.add_argument('-c',
                        '--content-types-path',
                        '--content-types-config',
                        metavar="PATH",
                        dest='content_types_config_files',
                        default=[],
                        action='append',
                        help="""\
Specify a path to a content.types file to assist
with file type determination. Use the -p or -P flags
to display content types as read by pepe.""")
    parser.add_argument('-p',
                        '--print-content-types',
                        dest='should_print_content_types',
                        action='store_true',
                        default=False,
                        help='Display content types and exit.')
    parser.add_argument('-P',
                        '--print-content-types-config',
                        dest='should_print_content_types_config',
                        action='store_true',
                        default=False,
                        help='Display content types configuration and exit.')
    return parser.parse_args()
545945
def parse_known_args():
    
    parser = ArgumentParser()
    parser.add_argument("-l", "--loop", type=int, help="Loop every X seconds")
    parser.add_argument('-V', '--version',
                        action='store_true',
                        dest='version',
                        help='Print the version number and exit')
    parser.add_argument("-u", "--update",
                        action='store_true',
                        dest="update",
                        help="Update the software from online repo")
    parser.add_argument("-p", "--problem",
                        action='store_true',
                        dest="problem",
                        help="Report a problem")
    parser.add_argument("-m", "--memory",
                        action='store_true',
                        dest="memory",
                        help="Run memory tests")
    args, otherthings = parser.parse_known_args()
    return args, otherthings, parser
1178909
def parse_command_line() -> Namespace:
    
    import tornado.options
    parser.parse_known_args(namespace=config)
    set_loglevel()  # set new log level based on commanline option
    for k, v in vars(config).items():
        if k.startswith('log'):
            tornado.options.options.__setattr__(k, v)
    return config
348213
public static String parseCommandArgs(String commandLine, final CommandLineParser.CallbackHandler handler) throws CommandFormatException {
        if(commandLine == null) {
            return null;
        }
        final ParsingStateCallbackHandler callbackHandler = getCallbackHandler(handler);
        return StateParser.parse(commandLine, callbackHandler, ArgumentListState.INSTANCE);
    }