CLI command line arguments handling
542140
def get_command_line_args():
    """"""
    parser = argparse.ArgumentParser(description='Send logs to Django Sentry.')

    parser.add_argument('--sentryconfig', '-c', default=None,
                        help='A configuration file (.ini, .yaml) of some '
                             'Sentry integration to extract the Sentry DSN from')
    parser.add_argument('--sentrydsn', '-s', default="",
                        help='The Sentry DSN string (overrides -c)')
    parser.add_argument('--daemonize', '-d', default=False,
                        action='store_const', const=True,
                        help='Run this script in background')
    parser.add_argument('--follow', '-f', default="all",
                        help='Which logs to follow, default ALL')
    parser.add_argument('--nginxerrorpath', '-n', default=None,
                        help='Nginx error log path')

    return parser.parse_args()
1004699
def cli():
    """"""
    parser = argparse.ArgumentParser(prog="sphinx-serve",
                                     formatter_class=argparse.ArgumentDefaultsHelpFormatter,
                                     conflict_handler="resolve",
                                     description=__doc__
                                     )

    parser.add_argument("-v", "--version", action="version",
                        version="%(prog)s {0}".format(__version__)
                        )

    parser.add_argument("-h", "--host", action="store",
                        default="0.0.0.0",
                        help="Listen to the given hostname"
                        )

    parser.add_argument("-p", "--port", action="store",
                        type=int, default=8081,
                        help="Listen to given port"
                        )

    parser.add_argument("-b", "--build", action="store",
                        default="_build",
                        help="Build folder name"
                        )

    parser.add_argument("-s", "--single", action="store_true",
                        help="Serve the single-html documentation version"
                        )

    return parser.parse_args()
1069210
def handle_args(args):
  
  parser = argparse.ArgumentParser()
  parser.add_argument("configpath", default=None, nargs="?",
                      help="/path/to/configs (always a directory; if omitted, all /configs are checked")
  parser.add_argument("--verbose", action="store_true", default=False)
  parsed_args = vars(parser.parse_args(args))
  # If a config path wasn't given, calculate it based on location of the script
  if parsed_args["configpath"] is None:
    script_dir = os.path.abspath(os.path.dirname(sys.argv[0]))
    parsed_args["configpath"] = os.path.normpath("{}/{}".format(script_dir, CONFIGS_RELATIVE_PATH_FROM_SCRIPT_DIR))
  else:
    parsed_args["configpath"] = os.path.normpath(parsed_args["configpath"])
  # If the path is a directory, all good. if it's a file, find the directory the file is in and check that instead
  if os.path.isdir(parsed_args["configpath"]):
    parsed_args["configdir"] = parsed_args["configpath"]
  else:
    parsed_args["configdir"] = os.path.dirname(parsed_args["configpath"])
  return parsed_args
114901
def main(argv=None):
    
    if not argv:
        argv = sys.argv[1:]
    try:
        global COMMAND_LINE_FLAG
        COMMAND_LINE_FLAG = True
        parser = argparse.ArgumentParser(description=_HELP_TEXT)
        parser.add_argument('command', nargs='?', default=None,
                            help="One of 'ls', 'rm', 'put' or 'get'.")
        parser.add_argument('path', nargs='?', default=None,
                            help="Use when a file needs referencing.")
        parser.add_argument('target', nargs='?', default=None,
                            help="Use to specify a target filename.")
        args = parser.parse_args(argv)
        if args.command == 'ls':
            list_of_files = ls()
            if list_of_files:
                print(' '.join(list_of_files))
        elif args.command == 'rm':
            if args.path:
                rm(args.path)
            else:
                print('rm: missing filename. (e.g. "ufs rm foo.txt")')
        elif args.command == 'put':
            if args.path:
                put(args.path, args.target)
            else:
                print('put: missing filename. (e.g. "ufs put foo.txt")')
        elif args.command == 'get':
            if args.path:
                get(args.path, args.target)
            else:
                print('get: missing filename. (e.g. "ufs get foo.txt")')
        else:
            # Display some help.
            parser.print_help()
    except Exception as ex:
        # The exception of no return. Print exception information.
        print(ex)
1219109
def parse_args(self, args=None, namespace=None):
        
        self._expand_prefixed_files(args)
        return super(CLICommandParser, self).parse_args(args)
169435
CommandLine parse(DefaultCommandLine cl, String[] args) {
        parseInternal(cl, args, true);
        return cl;
    }
975124
def argument_run(self, sp_r):
		
		arg_run = []

		for line in sp_r:
			logging.debug("argument run: handling: " + str(line))
			if(line[1] == "data"):
				arg_run.append( (line[0], line[1], line[2], line[2].get_words(line[3])))
				continue
			if(line[1] == "command"):
				self.checkargs(line[0], line[2], line[3])
				arg_run.append( (line[0], line[1], line[2], [a for a in self.convert_args(line[2], line[3])]))
		return arg_run
1232756
def cli_main():
    """"""
    import argparse
    import os

    def is_file_or_pipe(arg):
        if not os.path.exists(arg) or os.path.isdir(arg):
            parser.error('The file {0} does not exist!'.format(arg))
        else:
            return arg

    def is_dir(arg):
        if not os.path.isdir(arg):
            parser.error('The directory {0} does not exist!'.format(arg))
        else:
            return arg

    parser = argparse.ArgumentParser(description=__doc__)

    parser.add_argument('-v', '--version', action='version',
                        version=version)

    parser.add_argument('template', help='The mustache file',
                        type=is_file_or_pipe)

    parser.add_argument('-d', '--data', dest='data',
                        help='The json data file',
                        type=is_file_or_pipe, default={})

    parser.add_argument('-p', '--path', dest='partials_path',
                        help='The directory where your partials reside',
                        type=is_dir, default='.')

    parser.add_argument('-e', '--ext', dest='partials_ext',
                        help='The extension for your mustache\
                              partials, \'mustache\' by default',
                        default='mustache')

    parser.add_argument('-l', '--left-delimiter', dest='def_ldel',
                        help='The default left delimiter, "{{" by default.',
                        default='{{')

    parser.add_argument('-r', '--right-delimiter', dest='def_rdel',
                        help='The default right delimiter, "}}" by default.',
                        default='}}')

    args = vars(parser.parse_args())

    try:
        sys.stdout.write(main(**args))
        sys.stdout.flush()
    except SyntaxError as e:
        print('Chevron: syntax error')
        print('    ' + '\n    '.join(e.args[0].split('\n')))
        exit(1)
352270
def parse_arguments():
    
    parser = argparse.ArgumentParser()

    parser.add_argument('file', metavar="FILE", nargs='+',
                        help='file to be made executable')
    parser.add_argument("-p", "--python", metavar="VERSION",
                        help="python version (2 or 3)")
    parser.add_argument('-v', '--version', action='version',
                        version='%(prog)s ' + __version__, help='show version')
    parser.add_argument('-r', '--recursive', action='store_true',
                        help='recursively iterate the directories')

    args = parser.parse_args()
    return args
946863
def batch_arguments(arguments)
      batch = Batch.new do |x|
        arguments.each do |argument|
          # step: is the argument a subcommand?
          if subcommand?(argument)
            parser = subcommand(argument)
            # step: get the command and set the cursor to the parser
            x.cursor = parser.name
            # step: call the on_command block
            parser.on_command.call
          else
            # step: is this argument a parser argument
            parser = subcommand(x.cursor)
            if !is_switch?(argument)
              if x.previous
                x.global(argument)
              else
                x.add argument
              end
            elsif !parser.switch?(argument) and global_parser.switch?(argument)
              x.global(argument)
              x.previous = x.cursor
            else
              x.add argument
            end
          end
        end
      end
      yield batch if block_given?
      batch
    end
176675
public void runArgs(String[] args) {
        CommandLineParser clParser = new DefaultParser();
        CommandLine line;
        String host;
        String port;
        CMD cmd;
        String[] cmdArgs;
        final PrintStream CONSOLE = System.out;
        try {
            // parse the command line arguments
            line = clParser.parse(options, args);

            if (line.hasOption("output")){
                String location = line.getOptionValue("output");
                File output = new File(location);
                FileOutputStream fos;
                try {
                    fos = new FileOutputStream(output);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                    throw new ParseException(String.format("Wrong -o option. args %s\n",Arrays.asList(args)));
                }
                PrintStream out = new PrintStream(fos);
                System.setOut(out);

            }
            if (line.getOptions().length==0 || line.hasOption("help")) {
                if ((line.getOptions().length > 2) || (line.getOptions().length==2 && !line.hasOption("output"))){
                    throw new ParseException(String.format("Wrong -help option. args %s\n", Arrays.asList(args)));
                }
                printUsage(System.out);
            }
            if (line.hasOption("server")) {
                String server = line.getOptionValue("server");
                try {
                    host = server.split(":")[0];
                    port = server.split(":")[1];
                }catch (Exception e){
                    throw new ParseException(String.format("Wrong -server option. args %s\n", Arrays.asList(args)));
                }
                ServiceDirectory.getServiceDirectoryConfig().setProperty(
                        DirectoryServiceRestfulClient.SD_API_SD_SERVER_FQDN_PROPERTY,
                        host);
                ServiceDirectory.getServiceDirectoryConfig().setProperty(
                        DirectoryServiceRestfulClient.SD_API_SD_SERVER_PORT_PROPERTY,
                        port);
            }

            if (line.hasOption("exec")) {
                String commandString = line.getOptionValue("exec");
                cmdArgs = parseCommand(commandString);
                try {
                    cmd = CMD.valueOf(cmdArgs[0]);
                } catch (IllegalArgumentException e) {
                    throw new ParseException(String.format("Unknown command [ %s ] \n", commandString));
                }
                if (cmd.sizeOfArgs + 1 != cmdArgs.length) {
                    throw new ParseException(
                            String.format("Wrong arguments number for command %s, required %s but %s \n",
                                    cmdArgs[0], cmd.sizeOfArgs, cmdArgs.length - 1));
                }
                switch (cmd) {
                    case getInstanceOf:
                        lookupInstance(cmdArgs);
                        break;
                    case getAllInstancesOf:
                        lookupInstances(cmdArgs);
                        break;
                    case getAllServices:
                        getAllServices();
                        break;
                    case registerService:
                        registerService(cmdArgs);
                        break;
                    default:
                        fail("command " + cmd + " is unsupported yet");
                        break;
                }

            }
        } catch (ParseException exp) {
            // oops, something went wrong
            exp.printStackTrace();
            try {
                TimeUnit.MILLISECONDS.sleep(100L);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            printUsage(System.err);
        }
        System.setOut(CONSOLE);
    }
797498
def _arguments(ctx, command_name=None):
    
    ctx = ctx.parent
    main = ctx.command
    if command_name:
        command = main.get_command(ctx, command_name)
        if not command:
            return
    else:
        command = main

    types = ["option", "argument"]
    all_params = sorted(
        command.get_params(ctx), key=lambda p: types.index(p.param_type_name)
    )

    def get_name(param):
        return max(param.opts, key=len)

    for param in all_params:
        if param.param_type_name == "option":
            option = get_name(param)
            same_dest = [
                get_name(p) for p in all_params if p.name == param.name
            ]
            if same_dest:
                option = "({})".format(" ".join(same_dest)) + option
            if param.help:
                option += "[{}]".format(param.help or "")
            if not param.is_flag:
                option += "=:( )"
            click.echo(option)
        elif param.param_type_name == "argument":
            option = get_name(param)
            click.echo(":{}".format(option))
858629
def process_args_from_command_line(self):
        """"""
        # Yes, this is ugly, but we don't want to interfere with setup.py's own
        # option handling
        opts_to_remove = []
        for idx, option in enumerate(sys.argv):
            if not option.startswith("--"):
                continue
            if option == "--static":
                opts_to_remove.append(idx)
                self.static_extension = True
            elif option == "--no-download":
                opts_to_remove.append(idx)
                self.download_igraph_if_needed = False
            elif option == "--no-pkg-config":
                opts_to_remove.append(idx)
                self.use_pkgconfig = False
            elif option == "--no-progress-bar":
                opts_to_remove.append(idx)
                self.show_progress_bar = False
            elif option == "--no-wait":
                opts_to_remove.append(idx)
                self.wait = False                
            elif option.startswith("--c-core-version"):
                opts_to_remove.append(idx)
                if option == "--c-core-version":
                    value = sys.argv[idx+1]
                    opts_to_remove.append(idx+1)
                else:
                    value = option.split("=", 1)[1]
                self.c_core_versions = [value]
            elif option.startswith("--c-core-url"):
                opts_to_remove.append(idx)
                if option == "--c-core-url":
                    value = sys.argv[idx+1]
                    opts_to_remove.append(idx+1)
                else:
                    value = option.split("=", 1)[1]
                self.c_core_url = value

        for idx in reversed(opts_to_remove):
            sys.argv[idx:(idx+1)] = []
785548
def handle_invalid_args(command_info_module)
      if !@invalid_args.empty?
        message = 'Invalid argument'
        message += 's' if @invalid_args.length > 1
        args = @invalid_args.map { |arg| "\"#{arg}\"" }.join(', ')

        puts " !    #{message}: #{args}"
      else
        puts " !    Invalid command usage"
      end

      respond_with_command_help(command_info_module)
    end
770804
def simple_cmd():
    
    parser = argparse.ArgumentParser(
        prog="Simple command-line function toolkit.",
        description="""Input function name and args and kwargs.
        python xxx.py main -a 1 2 3 -k a=1,b=2,c=3""",
    )
    parser.add_argument("-f", "--func_name", default="main")
    parser.add_argument("-a", "--args", dest="args", nargs="*")
    parser.add_argument("-k", "--kwargs", dest="kwargs")
    parser.add_argument(
        "-i",
        "-s",
        "--info",
        "--show",
        "--status",
        dest="show",
        action="store_true",
        help="show the args, kwargs and function's source code.",
    )
    params = parser.parse_args()
    func_name = params.func_name
    func = globals().get(func_name)
    if not (callable(func)):
        Config.utils_logger.warning("invalid func_name: %s" % func_name)
        return
    args = params.args or []
    kwargs = params.kwargs or {}
    if kwargs:
        items = [re.split("[:=]", i) for i in re.split("[,;]+", kwargs)]
        kwargs = dict(items)
    if params.show:
        from inspect import getsource

        Config.utils_logger.info("args: %s; kwargs: %s" % (args, kwargs))
        Config.utils_logger.info(getsource(func))
        return
    func(*args, **kwargs)
406998
def argument(value, options = {})
      return unless @shell.applicable?(options)
      value = value.to_s
      if @shell.requires_escaping?(value)
        value = @shell.escape_value(value)
      end
      @command << ' ' << value
      @last_arg = :argument
    end
45383
def command_line_arguments(command_line_parameters):
  """"""

  # create parser
  parser = argparse.ArgumentParser(description='Execute baseline algorithms with default parameters', formatter_class=argparse.ArgumentDefaultsHelpFormatter)

  # add parameters
  # - the algorithm to execute
  parser.add_argument('-a', '--algorithms', choices = all_algorithms, default = ('gmm-voxforge',), nargs = '+', help = 'Select one (or more) algorithms that you want to execute.')
  parser.add_argument('--all', action = 'store_true', help = 'Select all algorithms.')
  # - the database to choose
  parser.add_argument('-d', '--database', choices = available_databases, default = 'voxforge', help = 'The database on which the baseline algorithm is executed.')
  # - the database to choose
  parser.add_argument('-b', '--baseline-directory', default = 'baselines', help = 'The sub-directory, where the baseline results are stored.')
  # - the directory to write
  parser.add_argument('-f', '--directory', help = 'The directory to write the data of the experiment into. If not specified, the default directories of the verify.py script are used (see verify.py --help).')

  # - use the Idiap grid -- option is only useful if you are at Idiap
  parser.add_argument('-g', '--grid', action = 'store_true', help = 'Execute the algorithm in the SGE grid.')
  # - run in parallel on the local machine
  parser.add_argument('-l', '--parallel', type=int, help = 'Run the algorithms in parallel on the local machine, using the given number of parallel threads')
  # - perform ZT-normalization
  parser.add_argument('-z', '--zt-norm', action = 'store_false', help = 'Compute the ZT norm for the files (might not be availabe for all databases).')

  # - just print?
  parser.add_argument('-q', '--dry-run', action = 'store_true', help = 'Just print the commands, but do not execute them.')

  # - evaluate the algorithm (after it has finished)
  parser.add_argument('-e', '--evaluate', nargs='+', choices = ('EER', 'HTER', 'ROC', 'DET', 'CMC', 'RR'), help = 'Evaluate the results of the algorithms (instead of running them) using the given evaluation techniques.')
  # TODO: add MIN-DCT measure
  # - other parameters that are passed to the underlying script
  parser.add_argument('parameters', nargs = argparse.REMAINDER, help = 'Parameters directly passed to the verify.py script.')

  bob.core.log.add_command_line_option(parser)
  args = parser.parse_args(command_line_parameters)
  if args.all:
    args.algorithms = all_algorithms

  bob.core.log.set_verbosity_level(logger, args.verbose)

  return args