input is needed for the `TestRunner` so it can use it with stubbing
 otherwise it is ignored when building a local cmd
13332
def build_local_cmd(task, cmd_str, input, given_opts)
      Local::Cmd.new(cmd_str, given_opts)
    end
1143167
public static void main(String[] args) {
		CrawljaxConfigurationBuilder builder = CrawljaxConfiguration
				.builderFor("http://demo.crawljax.com/");

		// Add the invariant that checks that the string isn't present.
		builder.crawlRules()
				.addInvariant(
						"Detect a string",
						new NotRegexCondition(
								"Invariants can be used to perform tests on the current state"));

		// This plugin will just print the error.
		builder.addPlugin(new OnInvariantViolationPlugin() {

			@Override
			public void onInvariantViolation(Invariant invariant,
					CrawlerContext context) {
				LOG.error("\n\n!!! Invariant {} violated !!!\n", invariant);
			}

		});

		CrawljaxRunner crawljax = new CrawljaxRunner(builder.build());
		crawljax.call();
	}
531768
def main():
    
    # Define Parser object and add to Toil
    if mock_mode():
        usage_msg = 'You have the TOIL_SCRIPTS_MOCK_MODE environment variable set, so this pipeline ' \
                    'will run in mock mode. To disable mock mode, set TOIL_SCRIPTS_MOCK_MODE=0'
    else:
        usage_msg = None

    parser = argparse.ArgumentParser(usage=usage_msg)
    subparsers = parser.add_subparsers(dest='command')
    subparsers.add_parser('generate-config', help='Generates an editable config in the current working directory.')
    subparsers.add_parser('generate-manifest', help='Generates an editable manifest in the current working directory.')
    subparsers.add_parser('generate', help='Generates a config and manifest in the current working directory.')
    # Run subparser                                                                                                              
    parser_run = subparsers.add_parser('run', help='Runs the ADAM/GATK pipeline')
    default_config = 'adam-gatk-mock.config' if mock_mode() else 'adam-gatk.config'
    default_manifest = 'adam-gatk-mock-manifest.csv' if mock_mode() else 'adam-gatk-manifest.csv'
    parser_run.add_argument('--config', default=default_config, type=str,
                            help='Path to the (filled in) config file, generated with "generate-config".')
    parser_run.add_argument('--manifest', default=default_manifest,
                            type=str, help='Path to the (filled in) manifest file, generated with "generate-manifest". '
                                           '\nDefault value: "%(default)s".')
    Job.Runner.addToilOptions(parser_run)
    args = parser.parse_args()

    cwd = os.getcwd()
    if args.command == 'generate-config' or args.command == 'generate':
        generate_file(os.path.join(cwd, default_config), generate_config)
    if args.command == 'generate-manifest' or args.command == 'generate':
        generate_file(os.path.join(cwd, default_manifest), generate_manifest)
    # Pipeline execution
    elif args.command == 'run':
        require(os.path.exists(args.config), '{} not found. Please run '
                                             'generate-config'.format(args.config))
        if not hasattr(args, 'sample'):
            require(os.path.exists(args.manifest), '{} not found and no samples provided. Please '
                                                   'run "generate-manifest"'.format(args.manifest))
        # Parse config
        parsed_config = {x.replace('-', '_'): y for x, y in yaml.load(open(args.config).read()).iteritems()}
        inputs = argparse.Namespace(**parsed_config)

        # Parse manifest file
        uuid_list = []
        with open(args.manifest) as f_manifest:
            for line in f_manifest:
                if not line.isspace() and not line.startswith('#'):
                    uuid_list.append(line.strip())

        inputs.sort = False
        if not inputs.dir_suffix:
            inputs.dir_suffix = ''
        if not inputs.s3_bucket:
            inputs.s3_bucket = ''

        if inputs.master_ip and inputs.num_nodes:
            raise ValueError("Exactly one of master_ip (%s) and num_nodes (%d) must be provided." %
                             (inputs.master_ip, inputs.num_nodes))

        if not hasattr(inputs, 'master_ip') and inputs.num_nodes <= 1:
            raise ValueError('num_nodes allocates one Spark/HDFS master and n-1 workers, and thus must be greater '
                             'than 1. %d was passed.' % inputs.num_nodes)

        if (inputs.pipeline_to_run != "adam" and
            inputs.pipeline_to_run != "gatk" and
            inputs.pipeline_to_run != "both"):
            raise ValueError("pipeline_to_run must be either 'adam', 'gatk', or 'both'. %s was passed." % inputs.pipeline_to_run)

        Job.Runner.startToil(Job.wrapJobFn(sample_loop, uuid_list, inputs), args)
530260
function main (processArgv, conf) {

  // CLI input
  var opts = getOpts(processArgv);
  var argv = opts.argv;

  // Update notifier
  if (!argv["no-notifier"]) {
    checkUpdate();
  }

  // Convert options "--help" and "-h" into command "help"
  if (argv.help) {
    processArgv = transformHelpArgs(processArgv);
    // Regenerate opts from newly forged process.argv
    opts = getOpts(processArgv);
    argv = opts.argv;
  }

  // "--version"
  if (argv.version) {
    showVersion();
  }

  var commandName = argv._[0];

  // Demand command name
  if (!commandName) {
    console.error("No command specified");
    opts.showHelp();
    process.exit(127);
  }

  // Load command module
  var command = commands.load(commandName);

  // Demand valid command
  if (!command) {
    console.error("Unknown command: " + commandName);
    opts.showHelp();
    process.exit(127);
  }

  process.on("exit", function () {
    ttys.stdin.end();
  });

  // Configure opts and run command (inside a domain to catch any error)
  commands.run(command, opts, conf).then(ok, fail);

  function ok () {
    process.exit(0);
  }

  function fail (e) {
    if (e.code === "EINTERRUPT") {
      process.exit(127);
    } else {
      console.error("%s", e);
      if (process.env.DEBUG) {
        throw e;
      }
      process.exit(1);
    }
  }
}
175913
def stub_main():
    """"""
    from google.apputils import run_script_module
    import butcher.main
    run_script_module.RunScriptModule(butcher.main)
680574
private boolean tryCheckEmptyRunGitCommand(File directory, long nativeGitTimeoutInMs, String gitCommand) {
    try {
      String env = System.getenv("GIT_PATH");
      String exec = env == null ? "git" : env;
      String command = String.format("%s %s", exec, gitCommand);

      return getRunner().runEmpty(directory, nativeGitTimeoutInMs, command);
    } catch (IOException ex) {
      // Error means "non-empty"
      return false;
      // do nothing...
    }
  }
499950
function Cli(argv) {
  var Cucumber = require('cucumber');
  var Command = require('commander').Command;
  var path = require('path');

  function collect(val, memo) {
    memo.push(val);
    return memo;
  }

  function getProgram() {
    var program = new Command(path.basename(argv[1]));

    program
      .usage('[options] [<DIR|FILE[:LINE]>...]')
      .version(Cucumber.VERSION, '-v, --version')
      .option('-b, --backtrace', 'show full backtrace for errors')
      .option('--compiler <EXTENSION:MODULE>', 'require files with the given EXTENSION after requiring MODULE (repeatable)', collect, [])
      .option('-d, --dry-run', 'invoke formatters without executing steps')
      .option('--fail-fast', 'abort the run on first failure')
      .option('-f, --format <TYPE[:PATH]>', 'specify the output format, optionally supply PATH to redirect formatter output (repeatable)', collect, ['pretty'])
      .option('--name <REGEXP>', 'only execute the scenarios with name matching the expression (repeatable)', collect, [])
      .option('--no-colors', 'disable colors in formatter output')
      .option('--no-snippets', 'hide step definition snippets for pending steps')
      .option('--no-source', 'hide source uris')
      .option('-p, --profile <NAME>', 'specify the profile to use (repeatable)', collect, [])
      .option('-r, --require <FILE|DIR>', 'require files before executing features (repeatable)', collect, [])
      .option('--snippet-syntax <FILE>', 'specify a custom snippet syntax')
      .option('-S, --strict', 'fail if there are any undefined or pending steps')
      .option('-t, --tags <EXPRESSION>', 'only execute the features or scenarios with tags matching the expression (repeatable)', collect, []);

    program.on('--help', function () {
      console.log('  For more details please visit https://github.com/cucumber/cucumber-js#cli\n');
    });

    return program;
  }

  function getConfiguration() {
    var program = getProgram();
    program.parse(argv);
    var profileArgs = Cucumber.Cli.ProfilesLoader.getArgs(program.profile);
    if (profileArgs.length > 0) {
      var fullArgs = argv.slice(0, 2).concat(profileArgs).concat(argv.slice(2));
      program = getProgram();
      program.parse(fullArgs);
    }
    var configuration = Cucumber.Cli.Configuration(program.opts(), program.args);
    return configuration;
  }

  var self = {
    run: function run(callback) {
      var configuration = getConfiguration();
      var runtime = Cucumber.Runtime(configuration);
      var formatters = [createIpcFormatter()].concat(configuration.getFormatters());
      formatters.forEach(function (formatter) {
        runtime.attachListener(formatter);
      });
      try {
        runtime.start(callback);
      } catch (e) {
        console.log(e.stack || e)
        callback(false)
      }
    }
  };
  return self;
}
792292
function buildSpawn (cmd, args, opts, callback) {
  var proc = spawn(cmd, args, opts)
  var buffer = new Buffer('')
  var cmdError = {}

  cmd = cmd + ' ' + args.join(' ')

  if (proc.stdout) {
    proc.stdout.on('data', function indexOnData (data) {
      buffer = Buffer.concat([buffer, data])
    })
  }

  proc
    .on('error', function spawnOnError (err) {
      cmdError = new CommandError({
        command: cmd,
        message: err.message ? err.message : undefined,
        stack: err.stack ? err.stack : undefined,
        buffer: buffer ? buffer : undefined,
        status: err.status ? err.status : 1
      })
    })
    .on('close', function spawnOnClose (code) {
      if (code === 0) {
        callback(null, buffer.toString().trim(), code, buffer)
        return
      }

      cmdError = new CommandError({
        command: cmd,
        message: cmdError.message ? cmdError.message : undefined,
        stack: cmdError.stack ? cmdError.stack : undefined,
        buffer: cmdError.buffer ? cmdError.buffer : buffer,
        status: cmdError.status ? cmdError.status : code
      })
      callback(cmdError, undefined, code, undefined)
    })

  return proc
}
443393
public static void main(String[] args) throws ClassNotFoundException, IOException {
      // When run off the command-line or a build script, this program takes in two arguments: the path containing
      // class files to scan, and the output file to generate.
      long startTime = System.nanoTime();
      String path = args[0];
      String outputFile = args[1];

      System.out.printf(" [ComponentMetadataPersister] Starting component metadata generation.  Scanning classes in %s%n", path);

      ComponentMetadataRepo repo = new ComponentMetadataRepo();

      File f = new File(path);
      process(repo, f.getAbsolutePath(), f);

      // Test that all dependencies now exist in the component metadata map.
      Map<String, String> dependencies = new HashMap<>(128);
      for (ComponentMetadata md : repo.componentMetadataMap.values()) {
         if (md.getDependencies() != null) dependencies.putAll(md.getDependencies());
      }

      if (Boolean.getBoolean("infinispan.isCoreModule")) {
         // Perform this sanity check
         boolean hasErrors = false;
         for (Map.Entry<String, String> e : dependencies.entrySet()) {
            if (!repo.componentMetadataMap.containsKey(e.getKey())) {
               if (!repo.hasFactory(e.getKey())) {
                  System.out.printf(" [ComponentMetadataPersister]     **** WARNING!!!  Missing components or factories for dependency on %s%n", e.getKey());
                  hasErrors = true;
               }
            }
         }

         if (hasErrors && Boolean.getBoolean("infinispan.isCoreModule"))
            throw new RuntimeException("Could not pass sanity check of all annotated components and their respective factories/dependencies.");
      }
      writeMetadata(repo, outputFile);

      System.out.printf(" [ComponentMetadataPersister] %s components and %s factories.%n%n",
            repo.componentMetadataMap.size(), repo.factories.size());
   }
973976
def main(raw_args=None):
    

    if raw_args is None:
        raw_args = sys.argv[1:]

    parser = build_parser()
    args = parser.parse_args(raw_args)

    if args.firmware_image is None and args.gdb is None:
        print("You must specify either a firmware image or attach a debugger with --gdb <PORT>")
        return 1

    test_args = ['qemu-system-gnuarmeclipse', '-verbose', '-verbose', '-board', 'STM32F0-Discovery',
                 '-nographic', '-monitor', 'null', '-serial', 'null', '--semihosting-config',
                 'enable=on,target=native', '-d', 'unimp,guest_errors']

    if args.firmware_image:
        test_args += ['-image', args.firmware_image]

    if args.gdb:
        test_args += ['--gdb', 'tcp::%d' % args.gdb]

    proc = subprocess.Popen(test_args, stdout=sys.stdout, stderr=sys.stderr)

    try:
        proc.communicate()
    except KeyboardInterrupt:
        proc.terminate()

    return 0
319889
def main():
    
    parser = argparse.ArgumentParser()
    parser.add_argument('--config_file', dest='config_file', help='Config file to be used in the' +
                        'run.', type=str, required=True, default=None)
    Job.Runner.addToilOptions(parser)
    params = parser.parse_args()
    START = Job.wrapJobFn(parse_config_file, params.config_file).encapsulate()
    Job.Runner.startToil(START, params)
    return None
683023
def main_locust():
    
    # monkey patch ssl at beginning to avoid RecursionError when running locust.
    from gevent import monkey; monkey.patch_ssl()

    import multiprocessing
    import sys
    from httprunner import logger

    try:
        from httprunner import locusts
    except ImportError:
        msg = "Locust is not installed, install first and try again.\n"
        msg += "install command: pip install locustio"
        print(msg)
        exit(1)

    sys.argv[0] = 'locust'
    if len(sys.argv) == 1:
        sys.argv.extend(["-h"])

    if sys.argv[1] in ["-h", "--help", "-V", "--version"]:
        locusts.start_locust_main()
        sys.exit(0)

    # set logging level
    if "-L" in sys.argv:
        loglevel_index = sys.argv.index('-L') + 1
    elif "--loglevel" in sys.argv:
        loglevel_index = sys.argv.index('--loglevel') + 1
    else:
        loglevel_index = None

    if loglevel_index and loglevel_index < len(sys.argv):
        loglevel = sys.argv[loglevel_index]
    else:
        # default
        loglevel = "WARNING"

    logger.setup_logger(loglevel)

    # get testcase file path
    try:
        if "-f" in sys.argv:
            testcase_index = sys.argv.index('-f') + 1
        elif "--locustfile" in sys.argv:
            testcase_index = sys.argv.index('--locustfile') + 1
        else:
            testcase_index = None

        assert testcase_index and testcase_index < len(sys.argv)
    except AssertionError:
        print("Testcase file is not specified, exit.")
        sys.exit(1)

    testcase_file_path = sys.argv[testcase_index]
    sys.argv[testcase_index] = locusts.parse_locustfile(testcase_file_path)

    if "--processes" in sys.argv:
        """ locusts -f locustfile.py --processes 4
        """
        if "--no-web" in sys.argv:
            logger.log_error("conflict parameter args: --processes & --no-web. \nexit.")
            sys.exit(1)

        processes_index = sys.argv.index('--processes')

        processes_count_index = processes_index + 1

        if processes_count_index >= len(sys.argv):
            """ do not specify processes count explicitly
                locusts -f locustfile.py --processes
            """
            processes_count = multiprocessing.cpu_count()
            logger.log_warning("processes count not specified, use {} by default.".format(processes_count))
        else:
            try:
                """ locusts -f locustfile.py --processes 4 """
                processes_count = int(sys.argv[processes_count_index])
                sys.argv.pop(processes_count_index)
            except ValueError:
                """ locusts -f locustfile.py --processes -P 8888 """
                processes_count = multiprocessing.cpu_count()
                logger.log_warning("processes count not specified, use {} by default.".format(processes_count))

        sys.argv.pop(processes_index)
        locusts.run_locusts_with_processes(sys.argv, processes_count)
    else:
        locusts.start_locust_main()
722494
public static void main(String[] args) throws Exception {
        setCustomErrStream();

        CommandLine cmdLine = null;
        try {
            cmdLine = new CommandLine(args != null ? Arrays.copyOf(args, args.length) : null);

        } catch (final Exception e) {
        	// Cant use the CommandLine help here as the 
        	// i18n messages wont have been loaded
            System.out.println("Failed due to invalid parameters: " + Arrays.toString(args));
            System.out.println(e.getMessage());
            System.out.println("Use '-h' for more details.");
            System.exit(1);
        }

        ZapBootstrap bootstrap = createZapBootstrap(cmdLine);
        try {
            int rc = bootstrap.start();
            if (rc != 0) {
                System.exit(rc);
            }

        } catch (final Exception e) {
            logger.fatal(e.getMessage(), e);
            System.exit(1);
        }

    }
1020090
def execute
      subcmd_name = @match[1]
      return puts(help) unless subcmd_name

      subcmd = subcommand_list.match(subcmd_name)
      raise CommandNotFound.new(subcmd_name, self.class) unless subcmd

      subcmd.new(processor, arguments).execute
    end
379714
def run(self):
        ""
        arguments = self.argument_parser.parse_args()
        argspec = inspect.getargspec(arguments.func)
        vargs = []
        for arg in argspec.args:
            vargs.append(getattr(arguments, arg))
        if argspec.varargs:
            vargs.extend(getattr(arguments, argspec.varargs))
        output = arguments.func(*vargs)
        if getattr(arguments.func, '_cli_test_command', False):
            self.exit_code = 0 if output else 1
            output = ''
        if getattr(arguments.func, '_cli_no_output', False):
            output = ''
        self.formatter.format_output(output, arguments.format)
        if charmhelpers.core.unitdata._KV:
            charmhelpers.core.unitdata._KV.flush()
1072710
def build_inside(input_method, input_args=None, substitutions=None):
    
    def process_keyvals(keyvals):
        """ ["key=val", "x=y"] -> {"key": "val", "x": "y"} """
        keyvals = keyvals or []
        processed_keyvals = {}
        for arg in keyvals:
            key, value = arg.split("=", 1)
            processed_keyvals[key] = value
        return processed_keyvals

    main = __name__.split('.', 1)[0]
    log_encoding = get_logging_encoding(main)
    logger.info("log encoding: %s", log_encoding)

    if not input_method:
        raise RuntimeError("No input method specified!")

    logger.debug("getting build json from input %s", input_method)

    cleaned_input_args = process_keyvals(input_args)
    cleaned_input_args['substitutions'] = process_keyvals(substitutions)

    input_runner = InputPluginsRunner([{'name': input_method,
                                        'args': cleaned_input_args}])
    build_json = input_runner.run()[input_method]

    if isinstance(build_json, Exception):
        raise RuntimeError("Input plugin raised exception: {}".format(build_json))
    logger.debug("build json: %s", build_json)
    if not build_json:
        raise RuntimeError("No valid build json!")
    if not isinstance(build_json, dict):
        raise RuntimeError("Input plugin did not return valid build json: {}".format(build_json))

    dbw = DockerBuildWorkflow(**build_json)
    try:
        build_result = dbw.build_docker_image()
    except Exception as e:
        logger.error('image build failed: %s', e)
        raise
    else:
        if not build_result or build_result.is_failed():
            raise RuntimeError("no image built")
        else:
            logger.info("build has finished successfully \\o/")
943229
def _local_run(self, run_conf):
        '''
        
        '''
        try:
            ret = self._get_runner(run_conf).run()
        except SystemExit:
            ret = 'Runner is not available at this moment'
            self.out.error(ret)
        except Exception as ex:
            ret = 'Unhandled exception occurred: {}'.format(ex)
            log.debug(ex, exc_info=True)

        return ret