Public: Run the command

 argv   - an array of string args
 opts   - the instance of OptionParser
 config - the output config hash

 Returns the command to be executed
500551
def go(argv, opts, config)
      opts.banner = "Usage: #{syntax}"
      process_options(opts, config)
      add_default_options(opts)

      if argv[0] && cmd = commands[argv[0].to_sym]
        logger.debug "Found subcommand '#{cmd.name}'"
        argv.shift
        cmd.go(argv, opts, config)
      else
        logger.debug "No additional command found, time to exec"
        self
      end
    end
1220516
@Override
  public int run(String[] argv) throws Exception {
    int exitCode = 0;

    Options options = buildOptions();
    if(argv.length == 0) {
      printHelp();
      return -1;
    }

    CommandLineParser parser = new PosixParser();
    CommandLine cmd;

    try {
      cmd = parser.parse(options, argv);
    } catch (ParseException e) {
      System.out.println(
        "Error parsing command-line options: " + e.getMessage());
      printHelp();
      return -1;
    }

    if(cmd.hasOption("h")) { // print help and exit
      printHelp();
      return -1;
    }

    boolean printToScreen    = false;
    String inputFilenameArg  = cmd.getOptionValue("i");
    String outputFilenameArg = cmd.getOptionValue("o");
    String processor         = cmd.getOptionValue("p");
    if(processor == null) { processor = defaultProcessor; }

    if(cmd.hasOption("v")) { // print output to screen too
      printToScreen = true;
      System.out.println("input  [" + inputFilenameArg  + "]");
      System.out.println("output [" + outputFilenameArg + "]");
    }

    try {
      go(EditsVisitorFactory.getEditsVisitor(
        outputFilenameArg,
        processor,
        TokenizerFactory.getTokenizer(inputFilenameArg),
        printToScreen));
    } catch (EOFException e) {
      System.err.println("Input file ended unexpectedly. Exiting");
      exitCode = 255;
    } catch(IOException e) {
      System.err.println("Encountered exception. Exiting: " + e.getMessage());
      exitCode = 1;
    }

    return exitCode;
  }
942066
def run(self):
    
    self.parser = MultioptOptionParser(
      usage="%prog <command> [options] [args]",
      prog=self.clsname,
      version=self.version,
      option_list=self.global_options,
      description=self.desc_short,
      commands=self.command_set,
      epilog=self.footer
    )
    
    try:
      self.options, self.args = self.parser.parse_args(self.argv)    
    except Exception, e:
      print str(e)
      pass

    if len(self.args) < 1:
      self.parser.print_lax_help()
      return 2
    
    self.command = self.args.pop(0)
    showHelp = False
    
    if self.command == 'help': 
      if len(self.args) < 1:
        self.parser.print_lax_help()
        return 2
      else:
        self.command = self.args.pop()
        showHelp = True

    if self.command not in self.valid_commands:
      self.parser.print_cmd_error(self.command)
      return 2

    self.command_set[self.command].set_cmdname(self.command)
    subcmd_parser = self.command_set[self.command].get_parser(self.clsname, self.version, self.global_options)
    subcmd_options, subcmd_args = subcmd_parser.parse_args(self.args)

    if showHelp:
      subcmd_parser.print_help_long()
      return 1

    try:
      self.command_set[self.command].func(subcmd_options, *subcmd_args)
    except (CommandError, TypeError), e:
      # self.parser.print_exec_error(self.command, str(e))
      subcmd_parser.print_exec_error(self.command, str(e))
      print 
      # @TODO show command help
      # self.parser.print_lax_help()
      return 2

      
    return 1
94969
def process_args
      args = @args.dup
      @options[:operands] = nil
      unless args.length >= 2
        puts @opts
        exit 1
      end
      @options[:operands] = args.shift(2)
      @options[:output_filename] = args.shift unless args.empty?
      @options[:output] ||= @options[:output_filename] || $stdout

      run
    end
484348
def run_from_argv(self, argv):
        
        option = '--testrunner='
        for arg in argv[2:]:
            if arg.startswith(option):
                self.test_runner = arg[len(option):]
                break
        super(Command, self).run_from_argv(argv)
202482
def parse_argv(tokens, options, options_first=False):
    
    parsed = []
    while tokens.current() is not None:
        if tokens.current() == '--':
            return parsed + [Argument(None, v) for v in tokens]
        elif tokens.current().startswith('--'):
            parsed += parse_long(tokens, options)
        elif tokens.current().startswith('-') and tokens.current() != '-':
            parsed += parse_shorts(tokens, options)
        elif options_first:
            return parsed + [Argument(None, v) for v in tokens]
        else:
            parsed.append(Argument(None, tokens.move()))
    return parsed
755151
def run_from_argv(self, argv):
        
        # load the command object.
        try:
            app_name = get_commands()[argv[2]]
        except KeyError:
            raise CommandError("Unknown command: %r" % argv[2])

        if isinstance(app_name, BaseCommand):
            # if the command is already loaded, use it directly.
            klass = app_name
        else:
            klass = load_command_class(app_name, argv[2])

        # Ugly, but works. Delete tenant_command from the argv, parse the schema manually
        # and forward the rest of the arguments to the actual command being wrapped.
        del argv[1]
        schema_parser = argparse.ArgumentParser()
        schema_parser.add_argument("-s", "--schema", dest="schema_name", help="specify tenant schema")
        schema_namespace, args = schema_parser.parse_known_args(argv)

        tenant = self.get_tenant_from_options_or_interactive(schema_name=schema_namespace.schema_name)
        connection.set_tenant(tenant)
        klass.run_from_argv(args)
33414
def options(argv=[]):
    
    parser = HendrixOptionParser
    parsed_args = parser.parse_args(argv)
    return vars(parsed_args[0])
291090
def main(argv=None):
    
    # Get command line arguments, validate them, and normalize them
    opts = cmdparse.parse_args(argv)
    assert validate_opts.validate(opts)
    opts = normalize_opts.normalize(opts)

    if opts.verbose:
        # Update client: print input and output directories
        messages.print_input_output(opts)

    file_paths = fileparse.get_file_list(opts)
    assert validate_files.validate(file_paths, opts)

    if opts.verbose and opts.is_dir:
        # Update client: print files that will be parsed
        messages.print_files(opts, file_paths)

    # For now, only using default GitHub Markdown for parsing
    # Collect tag/anchor combinations
    collector = make_github_markdown_collector(opts)
    anchors, duplicate_tags = collector.collect(file_paths)
    assert validate_anchors.validate(anchors, duplicate_tags, opts)

    # Write files using previously found AnchorHub tags and generated anchors
    writer = make_github_markdown_writer(opts)
    counter = writer.write(file_paths, anchors, opts)

    if opts.verbose:
        if opts.is_dir:
            # Update client: print files that had modifications
            messages.print_modified_files(opts, anchors)
        # Print summary statistics
        messages.print_summary_stats(counter)
401905
def run_command(cmd, *args):
    
    command = ' '.join((cmd, args))
    p = Popen(command, shell=True, stdout=PIPE, stderr=PIPE)
    stdout, stderr = p.communicate()
    return p.retcode, stdout, stderr
1002995
public int run(String... argv) {
    if (argv.length == 0) {
      printUsage();
      return -1;
    }

    // Sanity check on the number of arguments
    String cmd = argv[0];
    Command command = mCommands.get(cmd);

    if (command == null) {
      String[] replacementCmd = getReplacementCmd(cmd);
      if (replacementCmd == null) {
        // Unknown command (we didn't find the cmd in our dict)
        System.err.println(String.format("%s is an unknown command.", cmd));
        printUsage();
        return -1;
      } else {
        // Handle command alias
        if (mUnstableAlias != null && mUnstableAlias.contains(cmd)) {
          String deprecatedMsg =
              String.format("WARNING: %s is not a stable CLI command. It may be removed in the "
                      + "future. Use with caution in scripts. You may use '%s' instead.",
                  cmd, StringUtils.join(replacementCmd, " "));
          System.out.println(deprecatedMsg);
        }

        String[] replacementArgv =
            (String[]) ArrayUtils.addAll(replacementCmd, ArrayUtils.subarray(argv, 1, argv.length));
        return run(replacementArgv);
      }
    }

    String[] args = Arrays.copyOfRange(argv, 1, argv.length);
    CommandLine cmdline;
    try {
      cmdline = command.parseAndValidateArgs(args);
    } catch (InvalidArgumentException e) {
      System.out.println("Usage: " + command.getUsage());
      LOG.error("Invalid arguments for command {}:", command.getCommandName(), e);
      return -1;
    }

    // Handle the command
    try {
      return command.run(cmdline);
    } catch (Exception e) {
      System.out.println(e.getMessage());
      LOG.error("Error running " + StringUtils.join(argv, " "), e);
      return -1;
    }
  }
377507
def run(args)
      options = parse_args(args)
      po_file = Extractor.new.extract(options[:path])

      if options[:output_file]
        with_output_file(options[:output_file]) { |f| po_file.write_to(f) }
      else
        po_file.write_to(STDOUT)
      end
    rescue => e
      error(e)
    end
1337380
function run(argv, done) {
  if (!argv) {
    argv = parser.argv;
  }

  if (argv.h) {
    parser.showHelp();
    return done(null);
  }

  if (!argv._.length) {
    return done(new Error('Requires an input argument'));
  } else if (argv._.length > 2) {
    return done(new Error('Too many arguments given!'));
  }

  var input = argv._[0];
  if (input.indexOf('http://') === 0 || input.indexOf('https://') === 0) {
    request(input, function (err, res, body) {
      if (err) {
        return done(err);
      }
      convert(body, done);
    });
  } else {
    if (!fs.existsSync(input)) {
      return done(new Error('`' + input + '` does not exist!'));
    }

    fs.readFile(input, 'utf-8', function (err, content) {
      if (err) {
        return done(err);
      }

      convert(content, done);
    });
  }
}
183034
def runner(Options, buffering=True):
    
    def run(argv=None):
        if not buffering:
            sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
            sys.stderr = os.fdopen(sys.stderr.fileno(), 'w', 0)

        if argv is None:
            argv = sys.argv
        o = Options()
        try:
            o.parseOptions(argv[1:])
        except usage.UsageError, e:
            if hasattr(o, 'subOptions'):
                print str(o.subOptions)
            else:
                print str(o)
            print str(e)
            return 1

        return 0

    return run
1315931
def run_option_parser(args)
      optparse = OptionParser.new do |opts|
        opts.banner = 'Usage: synvert [project_path]'
        opts.on '-d', '--load SNIPPET_PATHS', 'load custom snippets, snippet paths can be local file path or remote http url' do |snippet_paths|
          @options[:custom_snippet_paths] = snippet_paths.split(',').map(&:strip)
        end
        opts.on '-l', '--list', 'list all available snippets' do
          @options[:command] = 'list'
        end
        opts.on '-o', '--open SNIPPET_NAME', 'Open a snippet' do |snippet_name|
          @options[:command] = 'open'
          @options[:snippet_name] = snippet_name
        end
        opts.on '-q', '--query QUERY', 'query specified snippets' do |query|
          @options[:command] = 'query'
          @options[:query] = query
        end
        opts.on '--skip FILE_PATTERNS', 'skip specified files or directories, separated by comma, e.g. app/models/post.rb,vendor/plugins/**/*.rb' do |file_patterns|
          @options[:skip_file_patterns] = file_patterns.split(',')
        end
        opts.on '-s', '--show SNIPPET_NAME', 'show specified snippet description, SNIPPET_NAME is combined by group and name, e.g. ruby/new_hash_syntax' do |snippet_name|
          @options[:command] = 'show'
          @options[:snippet_name] = snippet_name
        end
        opts.on '--sync', 'sync snippets' do
          @options[:command] = 'sync'
        end
        opts.on '-r', '--run SNIPPET_NAMES', 'run specified snippets, each SNIPPET_NAME is combined by group and name, e.g. ruby/new_hash_syntax,ruby/new_lambda_syntax' do |snippet_names|
          @options[:snippet_names] = snippet_names.split(',').map(&:strip)
        end
        opts.on '-v', '--version', 'show this version' do
          puts Core::VERSION
          exit
        end
      end
      paths = optparse.parse(args)
      Core::Configuration.instance.set :path, paths.first || Dir.pwd
      if @options[:skip_file_patterns] && !@options[:skip_file_patterns].empty?
        skip_files = @options[:skip_file_patterns].map do |file_pattern|
          full_file_pattern = File.join(Core::Configuration.instance.get(:path), file_pattern)
          Dir.glob(full_file_pattern)
        end.flatten
        Core::Configuration.instance.set :skip_files, skip_files
      end
    end
169560
def execute(argv, filename='Runfile')
      @ignore_settings = !filename
      argv = expand_shortcuts argv
      filename and File.file?(filename) or handle_no_runfile argv

      begin
        load settings.helper if settings.helper
        load filename
      rescue => ex
        abort "Runfile error:\n#{ex.message}\n#{ex.backtrace[0]}"
      end
      run(*argv)
    end
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