parses `cmdline` and constructs a :class:`Command`.

    :param cmdline: command line to interpret
    :type cmdline: str
    :param mode: mode identifier
    :type mode: str
508552
def commandfactory(cmdline, mode='global'):
    
    # split commandname and parameters
    if not cmdline:
        return None
    logging.debug('mode:%s got commandline "%s"', mode, cmdline)
    # allow to shellescape without a space after '!'
    if cmdline.startswith('!'):
        cmdline = 'shellescape \'%s\'' % cmdline[1:]
    cmdline = re.sub(r'"(.*)"', r'"\\"\1\\""', cmdline)
    try:
        args = split_commandstring(cmdline)
    except ValueError as e:
        raise CommandParseError(str(e))
    args = [string_decode(x, 'utf-8') for x in args]
    logging.debug('ARGS: %s', args)
    cmdname = args[0]
    args = args[1:]

    # unfold aliases
    # TODO: read from settingsmanager

    # get class, argparser and forced parameter
    (cmdclass, parser, forcedparms) = lookup_command(cmdname, mode)
    if cmdclass is None:
        msg = 'unknown command: %s' % cmdname
        logging.debug(msg)
        raise CommandParseError(msg)

    parms = vars(parser.parse_args(args))
    parms.update(forcedparms)

    logging.debug('cmd parms %s', parms)

    # create Command
    cmd = cmdclass(**parms)

    # set pre and post command hooks
    get_hook = settings.get_hook
    cmd.prehook = get_hook('pre_%s_%s' % (mode, cmdname)) or \
        get_hook('pre_global_%s' % cmdname)
    cmd.posthook = get_hook('post_%s_%s' % (mode, cmdname)) or \
        get_hook('post_global_%s' % cmdname)

    return cmd
971460
def command(name, mode):
    
    def decorator(fn):
        commands[name] = fn.__name__
        _Client._addMethod(fn.__name__, name, mode)
        return fn
    return decorator
1018929
def format_cmdline(args, maxwidth=80):
    '''
    '''

    # Leave room for the space and backslash at the end of each line
    maxwidth -= 2

    def lines():
        line = ''
        for a in (shell_quote(a) for a in args):
            # If adding this argument will make the line too long,
            # yield the current line, and start a new one.
            if len(line) + len(a) + 1 > maxwidth:
                yield line
                line = ''

            # Append this argument to the current line, separating
            # it by a space from the existing arguments.
            if line:
                line += ' ' + a
            else:
                line = a

        yield line

    return ' \\\n'.join(lines())
787414
def parse_command(bot: NoneBot,
                  cmd_string: str) -> Tuple[Optional[Command], Optional[str]]:
    
    logger.debug(f'Parsing command: {cmd_string}')

    matched_start = None
    for start in bot.config.COMMAND_START:
        # loop through COMMAND_START to find the longest matched start
        curr_matched_start = None
        if isinstance(start, type(re.compile(''))):
            m = start.search(cmd_string)
            if m and m.start(0) == 0:
                curr_matched_start = m.group(0)
        elif isinstance(start, str):
            if cmd_string.startswith(start):
                curr_matched_start = start

        if curr_matched_start is not None and \
                (matched_start is None or
                 len(curr_matched_start) > len(matched_start)):
            # a longer start, use it
            matched_start = curr_matched_start

    if matched_start is None:
        # it's not a command
        logger.debug('It\'s not a command')
        return None, None

    logger.debug(f'Matched command start: '
                 f'{matched_start}{"(empty)" if not matched_start else ""}')
    full_command = cmd_string[len(matched_start):].lstrip()

    if not full_command:
        # command is empty
        return None, None

    cmd_name_text, *cmd_remained = full_command.split(maxsplit=1)
    cmd_name = _aliases.get(cmd_name_text)

    if not cmd_name:
        for sep in bot.config.COMMAND_SEP:
            # loop through COMMAND_SEP to find the most optimized split
            curr_cmd_name = None
            if isinstance(sep, type(re.compile(''))):
                curr_cmd_name = tuple(sep.split(cmd_name_text))
            elif isinstance(sep, str):
                curr_cmd_name = tuple(cmd_name_text.split(sep))

            if curr_cmd_name is not None and \
                    (not cmd_name or len(curr_cmd_name) > len(cmd_name)):
                # a more optimized split, use it
                cmd_name = curr_cmd_name

        if not cmd_name:
            cmd_name = (cmd_name_text,)

    logger.debug(f'Split command name: {cmd_name}')
    cmd = _find_command(cmd_name)
    if not cmd:
        logger.debug(f'Command {cmd_name} not found')
        return None, None

    logger.debug(f'Command {cmd.name} found, function: {cmd.func}')
    return cmd, ''.join(cmd_remained)
682750
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 0 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.nil?
        if SINGLE_ARG_TYPES.include?(@specs[sym][:type])
          given_args[sym][:params] << params[0, 1]  # take the first parameter
          num_params_taken = 1
        elsif MULTI_ARG_TYPES.include?(@specs[sym][:type])
          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[:type] != :flag
        raise CommandlineError, "option '#{arg}' needs a parameter" unless opts[:default]
        params << (opts[:default].kind_of?(Array) ? opts[:default].clone : [opts[:default]])
      end

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

      case opts[:type]
      when :flag
        vals[sym] = (sym.to_s =~ /^no_/ ? negative_given : !negative_given)
      when :int, :ints
        vals[sym] = params.map { |pg| pg.map { |p| parse_integer_parameter p, arg } }
      when :float, :floats
        vals[sym] = params.map { |pg| pg.map { |p| parse_float_parameter p, arg } }
      when :string, :strings
        vals[sym] = params.map { |pg| pg.map(&:to_s) }
      when :io, :ios
        vals[sym] = params.map { |pg| pg.map { |p| parse_io_parameter p, arg } }
      when :date, :dates
        vals[sym] = params.map { |pg| pg.map { |p| parse_date_parameter p, arg } }
      end

      if SINGLE_ARG_TYPES.include?(opts[:type])
        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 MULTI_ARG_TYPES.include?(opts[:type]) && !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.key?(: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
1325741
def parse_command_line(args: List[str] = None, final: bool = True) -> List[str]:
    
    return options.parse_command_line(args, final=final)
844144
def read_command(self):
        

        reader = self.reader

        line = yield from reader.readline()
        if line == b'':  # lost connection
            raise ConnectionResetError()

        try:
            # skip the newline to make CommandCompiler work as advertised
            codeobj = self.attempt_compile(line.rstrip(b'\n'))
        except SyntaxError:
            yield from self.send_exception()
            return

        return codeobj
380501
def parse(cls, expression):
        
        parsed = {"name": None, "arguments": [], "options": []}

        if not expression.strip():
            raise ValueError("Console command signature is empty.")

        expression = expression.replace(os.linesep, "")

        matches = re.match(r"[^\s]+", expression)

        if not matches:
            raise ValueError("Unable to determine command name from signature.")

        name = matches.group(0)
        parsed["name"] = name

        tokens = re.findall(r"\{\s*(.*?)\s*\}", expression)

        if tokens:
            parsed.update(cls._parameters(tokens))

        return parsed
169435
CommandLine parse(DefaultCommandLine cl, String[] args) {
        parseInternal(cl, args, true);
        return cl;
    }
560128
def split_cmdline(cmdline):
    """"""
    path, cmd = os.path.split(cmdline[0])
    arguments = ' '.join(cmdline[1:])
    return path, cmd, arguments
45771
def detect_mode(cls, **params):
        
        modes = []
        for mode in cls.modes:
            if params.get(mode) is not None:
                modes.append(mode)
        if len(modes) > 1:
            error_message = 'ambiguous mode, must be one of {}'
            modes_csv = ', '.join(list(cls.modes))
            raise ValueError(error_message.format(modes_csv))
        return modes[0] if modes else cls.default_mode
789565
def cmd():
    ''''''

    # Try to handle any reasonable thing thrown at this.
    # Consume '-f' and '-o' as input/output, allow '-' for stdin/stdout
    # and treat any subsequent arguments as a space separated string to
    # be titlecased (so it still works if people forget quotes)
    parser = argparse.ArgumentParser()
    in_group = parser.add_mutually_exclusive_group()
    in_group.add_argument('string', nargs='*', default=[],
            help='String to titlecase')
    in_group.add_argument('-f', '--input-file',
            help='File to read from to titlecase')
    parser.add_argument('-o', '--output-file',
            help='File to write titlecased output to)')

    args = parser.parse_args()

    if args.input_file is not None:
        if args.input_file == '-':
            ifile = sys.stdin
        else:
            ifile = open(args.input_file)
    else:
        ifile = sys.stdin

    if args.output_file is not None:
        if args.output_file == '-':
            ofile = sys.stdout
        else:
            ofile = open(args.output_file, 'w')
    else:
        ofile = sys.stdout

    if len(args.string) > 0:
        in_string = ' '.join(args.string)
    else:
        with ifile:
            in_string = ifile.read()

    with ofile:
        ofile.write(titlecase(in_string))
301199
def main(args=sys.argv):
    

    parser = create_optparser(args[0])
    return cli(parser.parse_args(args[1:]))
1149925
def command_packet(cmd):
    
    return message('Command',
                   Container(string_length=len(cmd),
                             string=bytes(cmd, ENCODING)),
                   len(cmd) + 2)
1289528
def _cmdline(argv=None):
    
    parser = ArgumentParser()
    parser.add_argument("-c", "--config", action="append",
            help="config file [etc/config.yml]")
    parser.add_argument("-v", "--version", action="version",
            version="pipsort {:s}".format(__version__),
            help="print version and exit")
    parser.add_argument("-w", "--warn", default="WARNING",
            help="logger warning level [WARNING]")
    parser.add_argument("search_term", type=str,
                        help="Search term for PyPI")
    args = parser.parse_args(argv)
    if not args.config:
        args.config = ["etc/config.yml"]
    return args
1197289
def do_cmd(self, line):
        ''''''
        try:
            args = self.cmd_parser.parse_args(line.split())
        except ValueError as err:
            return error(err)

        # Check if args.service is valid
        if args.service not in SUPPORTED_SERVICES:
            return error('No Service: ' + args.service)

        args.params = ''.join(args.params)
        # params is optional
        if not args.params.strip():
            args.params = '{}'

        # params must be a dictionary format string
        match = re.match(r"^.*?(\{.*\}).*$", args.params)
        if not match:
            return error('Invalid params')

        try:
            args.params = dict(literal_eval(match.group(1)))
        except ValueError as err:
            return error('Invalid params')

        try:
            # Get ONVIF service
            service = self.client.get_service(args.service)
            # Actually execute the command and get the response
            response = getattr(service, args.operation)(args.params)
        except MethodNotFound as err:
            return error('No Operation: %s' % args.operation)
        except Exception as err:
            return error(err)

        if isinstance(response, (Text, bool)):
            return success(response)
        # Try to convert instance to dictionary
        try:
            success(ONVIFService.to_dict(response))
        except ONVIFError:
            error({})
863092
def cmd_split(self, line):
        
        cmd, *args = line.lstrip().split(' ', 1)
        return self.root_command.subcommands[cmd], ' '.join(args)