Parse out command line arguments
344286
def parse_args(add_args, docstring):
    """"""

    def run_args():
        """Run any global methods eponymous with args"""
        valuable_args = {k for k, v in args.__dict__.items() if v}
        arg_methods = {globals()[a] for a in valuable_args if a in globals()}
        if not arg_methods:
            return
        for method in arg_methods:
            method()
        raise SystemExit(_exit_ok)

    parser = argparse.ArgumentParser(
        description=docstring and docstring.splitlines()[0] or "No docstring")
    result = add_args(parser)
    parser = result if result else parser
    parser.add_argument('-v', '--version', action='store_true',
                        help='Show version [default: %s]' % __version__)
    # parser.add_argument('-q', '--quiet', action='store_true',
    # help='Do not show stdout')
    # parser.add_argument('-Q', '--quiet_errors', action='store_true',
    # help='Do not show stderr')
    global args  # pylint: disable=global-statement
    args = parser.parse_args()
    run_args()
    return args
714539
def cmdline(argv, flags):
    """"""
    rules = dict([(flag, {'flags': ["--%s" % flag]}) for flag in flags])
    return parse(argv, rules)
134091
def _parse_argv(argv=copy(sys.argv)):
    

    cfg = DotDict()
    cfg_files = []

    argv = argv[1:] # Skip command name
    while argv:
        arg = argv.pop(0)

        # split up arg in format --arg=val
        key_val = re.split('=| ', arg)
        arg = key_val[0]
        try:
            val = key_val[1]
        except IndexError:
            if len(argv) > 0 and argv[0][0] != '-':
                val = argv.pop(0)
            else:
                # No val available, probably a flag
                val = None

        if arg[0] == '-':
            key = arg.lstrip('-')
            if not val:
                val = True
            new_cfg = _dict_from_dotted(key, val)
            cfg = dict_merge(cfg, new_cfg)
        else:
            if arg.endswith(".yml"):
                cfg_files.append(arg)

    return cfg, cfg_files
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
373970
def __parse_arguments(self, *args):
        """"""

        params = self.parser.parse_args(args)

        uuid = params.uuid

        kw = {}

        if params.name:
            kw['name'] = params.name
        if params.email:
            kw['email'] = params.email
        if params.gender:
            kw['gender'] = params.gender
        if params.country:
            kw['country_code'] = params.country

        if params.is_bot:
            kw['is_bot'] = True
        elif params.no_bot:
            kw['is_bot'] = False

        return uuid, kw
790803
def parse_args(args):
    ''' 
    '''
    parser = argparse.ArgumentParser()
    parser.add_argument('config_file', nargs='?',
                        help='Configuration yaml file', default=None)
    parser.add_argument(
        '--log', '-l',
        help='Logging level (e.g. DEBUG, INFO, WARNING, ERROR, CRITICAL)',
        default='INFO')
    args_parsed = parser.parse_args(args)
    if not args_parsed.config_file:
        parser.error("You have to specify "
                     "a configuration file")  # pragma: no cover, sysexit
    return args_parsed
235282
def _parse_arguments():
        
        parser = get_base_arguments(get_parser())
        parser = get_tc_arguments(parser)
        args, unknown = parser.parse_known_args()
        return args, unknown
934582
def _parse_arguments():
    
    parser = argparse.ArgumentParser(
        description='eg provides examples of common command usage.'
    )

    parser.add_argument(
        '-v',
        '--version',
        action='store_true',
        help='Display version information about eg'
    )

    parser.add_argument(
        '-f',
        '--config-file',
        help='Path to the .egrc file, if it is not in the default location.'
    )

    parser.add_argument(
        '-e',
        '--edit',
        action='store_true',
        help="""Edit the custom examples for the given command. If editor-cmd
        is not set in your .egrc and $VISUAL and $EDITOR are not set, prints a
        message and does nothing."""
    )

    parser.add_argument(
        '--examples-dir',
        help='The location to the examples/ dir that ships with eg'
    )

    parser.add_argument(
        '-c',
        '--custom-dir',
        help='Path to a directory containing user-defined examples.'
    )

    parser.add_argument(
        '-p',
        '--pager-cmd',
        help='String literal that will be invoked to page output.'
    )

    parser.add_argument(
        '-l',
        '--list',
        action='store_true',
        help='Show all the programs with eg entries.'
    )

    parser.add_argument(
        '--color',
        action='store_true',
        dest='use_color',
        default=None,
        help='Colorize output.'
    )

    parser.add_argument(
        '-s',
        '--squeeze',
        action='store_true',
        default=None,
        help='Show fewer blank lines in output.'
    )

    parser.add_argument(
        '--no-color',
        action='store_false',
        dest='use_color',
        help='Do not colorize output.'
    )

    parser.add_argument(
        'program',
        nargs='?',
        help='The program for which to display examples.'
    )

    args = parser.parse_args()

    if len(sys.argv) < 2:
        # Too few arguments. We can't specify this using argparse alone, so we
        # have to manually check.
        parser.print_help()
        parser.exit()
    elif not args.version and not args.list and not args.program:
        parser.error(_MSG_BAD_ARGS)
    else:
        return args
380275
def parse_arguments(argv):
    

    parser = argparse.ArgumentParser(description="GNS3 server version {}".format(__version__))
    parser.add_argument("-v", "--version", help="show the version", action="version", version=__version__)
    parser.add_argument("--host", help="run on the given host/IP address")
    parser.add_argument("--port", help="run on the given port", type=int)
    parser.add_argument("--ssl", action="store_true", help="run in SSL mode")
    parser.add_argument("--no-ubridge", action="store_false", help="do not use ubridge to handle node connections")
    parser.add_argument("--config", help="Configuration file")
    parser.add_argument("--certfile", help="SSL cert file")
    parser.add_argument("--certkey", help="SSL key file")
    parser.add_argument("--record", help="save curl requests into a file (for developers)")
    parser.add_argument("-L", "--local", action="store_true", help="local mode (allows some insecure operations)")
    parser.add_argument("-A", "--allow", action="store_true", help="allow remote connections to local console ports")
    parser.add_argument("-q", "--quiet", action="store_true", help="do not show logs on stdout")
    parser.add_argument("-d", "--debug", action="store_true", help="show debug logs")
    parser.add_argument("--shell", action="store_true", help="start a shell inside the server (debugging purpose only you need to install ptpython before)")
    parser.add_argument("--log", help="send output to logfile instead of console")
    parser.add_argument("--daemon", action="store_true", help="start as a daemon")
    parser.add_argument("--pid", help="store process pid")
    parser.add_argument("--profile", help="Settings profile (blank will use default settings files)")

    args = parser.parse_args(argv)
    if args.config:
        Config.instance(files=[args.config], profile=args.profile)
    else:
        Config.instance(profile=args.profile)

    config = Config.instance().get_section_config("Server")
    defaults = {
        "host": config.get("host", "0.0.0.0"),
        "port": config.get("port", 3080),
        "ssl": config.getboolean("ssl", False),
        "certfile": config.get("certfile", ""),
        "certkey": config.get("certkey", ""),
        "record": config.get("record", ""),
        "local": config.getboolean("local", False),
        "allow": config.getboolean("allow_remote_console", False),
        "quiet": config.getboolean("quiet", False),
        "debug": config.getboolean("debug", False),
        "logfile": config.getboolean("logfile", "")
    }

    parser.set_defaults(**defaults)
    return parser.parse_args(argv)
229769
def parse_from_args(self, l):
        """"""
        if self.multiple:
            return [self.parse_from_arg(arg) for arg in l]
        return self.parse_from_arg(l[0])
1282808
def parse_args
      options = {:thin_command_client => false}

      opts = OptionParser.new do |opts|
        parse_common(opts, options)
        parse_other_args(opts, options)

        opts.on("-s", "--start AGENT") do |a|
          options[:action] = 'start'
          options[:agent_name] = a
        end

        opts.on("-p", "--stop AGENT") do |a|
          options[:action] = 'stop'
          options[:agent_name] = a
        end

        opts.on("--stop-agent ID") do |id|
          options[:action] = 'stop'
          options[:identity] = id
        end

        opts.on("-k", "--kill PIDFILE") do |file|
          options[:pid_file] = file
          options[:action] = 'kill'
        end

        opts.on("-K", "--killall") do
          options[:action] = 'killall'
        end

        opts.on("-U", "--status") do
          options[:action] = 'show'
        end

        opts.on("-l", "--list") do
          options[:list] = true
        end

        opts.on("--log-level LVL") do |lvl|
          options[:log_level] = lvl
        end

        opts.on("-c", "--cfg-dir DIR") do |d|
          options[:cfg_dir] = d
        end

        opts.on("-z", "--pid-dir DIR") do |dir|
          options[:pid_dir] = dir
        end

        opts.on("--log-dir DIR") do |dir|
          options[:log_dir] = dir

          # Ensure log directory exists (for windows, etc.)
          FileUtils.mkdir_p(dir) unless File.directory?(dir)
        end

        opts.on("-f", "--foreground") do
          options[:daemonize] = false
          #Squelch Ruby VM warnings about various things
          $VERBOSE = nil
        end

        opts.on("-I", "--interactive") do
          options[:console] = true
        end

        opts.on_tail("--help") do
          puts Usage.scan(__FILE__)
          exit
        end

      end

      begin
        opts.parse(ARGV)
      rescue Exception => e
        exit 0 if e.is_a?(SystemExit)
        fail(e.message, print_usage = true)
      end

      # allow specific arguments to use a thin command client for faster
      # execution (on Windows, etc.)
      unless options[:thin_command_client]
        # require full right_agent for any commands which do not specify thin
        # command client.
        require File.normalize_path(File.join(File.dirname(__FILE__), '..', '..', 'right_agent'))
      end
      resolve_identity(options)
      options
    end
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
182194
def parse_args():
  ''' 
  '''
  parser = optparse.OptionParser()

  parser.add_option("-v", "--verbose", action="store_true")

  mode_group = optparse.OptionGroup(parser, "Program Mode")
  mode_group.add_option("-u", "--update-status", action="store_const",
                        dest="mode", const="update_status")
  mode_group.add_option("-g", "--generate-cfg", action="store_const",
                        dest="mode", const="generate_cfg")
  parser.add_option_group(mode_group)
  parser.set_defaults(mode="update_status")

  general_options = optparse.OptionGroup(parser, "CM API Configuration")
  general_options.add_option("-H", "--host", metavar="HOST",
                             help="CM API hostname")
  general_options.add_option("-p", "--port", help="CM API port", default=None)
  general_options.add_option("-P", "--passfile", metavar="FILE",
                             help="File containing CM API username and password, "
                                  "colon-delimited on a single line.  E.g. "
                                  "\"user:pass\"")
  general_options.add_option("--use-tls", action="store_true",
                             help="Use TLS", default=False)
  parser.add_option_group(general_options)

  polling_options = optparse.OptionGroup(parser, "Status Update Options")
  polling_options.add_option("-c", "--cmd-file", metavar="FILE",
                             help="Path to the file that Nagios checks for "
                                  "external command requests.")
  polling_options.add_option("-n", "--use-send-nsca", action="store_true",
                             default=False,
                             help="Use send_nsca to report status via a nsca "
                                  "daemon. When using this option, the "
                                  "send_nsca program must be available and the "
                                  "nsca daemon host and port must be provided."
                                  "Default is false.")
  polling_options.add_option("--send-nsca-path", metavar="PATH",
                             default="/usr/sbin/send_nsca",
                             help="Path to send_nsca, default is "
                                  "/usr/sbin/send_nsca")
  polling_options.add_option("--nsca-host", metavar="HOST",
                             default="localhost",
                             help="When using send_nsca, the hostname of NSCA "
                                  "server, default is localhost.")
  polling_options.add_option("--nsca-port", metavar="PORT", default=None,
                             help="When using send_nsca, the port on which the "
                                  "server is running, default is 5667.")
  polling_options.add_option("--send-nsca-config", metavar="FILE", default=None,
                             help="Config file passed to send_nsca -c. Default"
                                  " is to not specify the config parameter.")
  parser.add_option_group(polling_options)


  generate_options = optparse.OptionGroup(parser, "Generate Config Options")
  generate_options.add_option("--cfg-dir", metavar="DIR", default=getcwd(),
                              help="Directory for generated Nagios cfg files.")
  parser.add_option_group(generate_options)

  (options, args) = parser.parse_args()

  ''' Parse the 'passfile' - it must contain the username and password,
      colon-delimited on a single line. E.g.:
      $ cat ~/protected/cm_pass
      admin:admin
  '''
  required = ["host", "passfile"]

  if options.mode == "update_status":
    if not options.use_send_nsca:
      required.append("cmd_file")

  for required_opt in required:
    if getattr(options, required_opt) is None:
      parser.error("Please specify the required argument: --%s" %
                   (required_opt.replace('_','-'),))

  return (options, args)
1187805
def _parse_args(self, args=None, values=None):
        """"""
        options, arguments = self._parser.parse_args(args, values)
        return self._fix_set_options(options), arguments
874498
def manual_argument_parsing(argv):
    """"""

    # Special case these for a better error message
    if not argv or argv == ['-h'] or argv == ['--help']:
        print_help_and_exit()

    try:
        dashdash_index = argv.index('--')
    except ValueError:
        print_std_err('Must separate command by `--`')
        print_help_and_exit()

    patches, cmd = argv[:dashdash_index], argv[dashdash_index + 1:]

    if '--help' in patches or '-h' in patches:
        print_help_and_exit()

    if '--all' in patches:
        all_patches = True
        patches.remove('--all')
    else:
        all_patches = False

    unknown_options = [patch for patch in patches if patch.startswith('-')]
    if unknown_options:
        print_std_err('Unknown options: {!r}'.format(unknown_options))
        print_help_and_exit()

    if patches and all_patches:
        print_std_err('--all and patches specified: {!r}'.format(patches))
        print_help_and_exit()

    return Arguments(all=all_patches, patches=tuple(patches), cmd=tuple(cmd))
325639
def getArguments(parser):
    ""
    args = parser.parse_args()    
    # check output image exists if override not forced
    if not args.force:
        if os.path.exists(args.output + args.image[-4:]):
            raise ArgumentError('The supplied output file {} already exists. Run -f/force flag to override.'.format(args.output))

    return args
519291
function parseCommandLine() {
	var commands = process.argv.slice(2);
	var args = {};

	for (var i = 0; i < commands.length; i++) {
		var match = commands[i].match(/^--(.+)=(.+)$/);
		if (match)
			args[match[1]] = match[2];
		else if (i < commands.length - 1 && commands[i].substr(0, 1) === "-") {
			args[commands[i].substr(1)] = commands[i + 1];
			i++;
		}
		else if (i === 0) args[commandKey] = commands[i];
		else if (i === 1) args[commandHost] = commands[i];
	}

	return args;
}