Run configContext with command execution as a callback
344233
function runJekyll (next) {

      // Build the command string
      if (options.bundleExec) {
        command = 'bundle exec ' + command;
      }

      if (options.serve) {
        command += majorVersion > 0 ? ' serve' : ' server';
      }
      else {
        command += ' build';
      }

      // Insert temporary config path into the config option
      if (typeof rawConfigFile !== 'undefined') {
        options.config = options.config ? options.config + ',' + rawConfigFile : rawConfigFile;
      }

      // Add flags to command if running serve or build
      Object.keys(optionList).forEach(function(option) {
        if (options[option]) {
          command += ' ' + optionList[option];
          if (typeof options[option] !== 'boolean') {
            command += ' ' + options[option];
          }
          if (!options[option]) {
            grunt.warn('`' + option + '` has been deprecated. You may want to try this as a `raw` option in your Gruntfile or in `_config.yml`.');
          }
        }
      });

      // Execute command
      grunt.log.write('`' + command + '` was initiated.\n');

      if (options.serve) {
        grunt.log.write('Started web server on http://localhost:' + (options.port || 4000) + '. Press Ctrl-C to stop it.\n');
      }

      exec(command, function(err, stdout) {
        grunt.log.write('\n\nJekyll output:\n' + stdout);

        if (err) {
          grunt.fail.warn(err);
          done(false);
        }
        else {
          next();
        }
      });
    }
228748
def run(self, context=None, options=None):
        
        template = (
            "var callback = arguments[arguments.length - 1];"
            + "axe.run(%s).then(results => callback(results))"
        )
        args = ""

        # If context parameter is passed, add to args
        if context is not None:
            args += "%r" % context
        # Add comma delimiter only if both parameters are passed
        if context is not None and options is not None:
            args += ","
        # If options parameter is passed, add to args
        if options is not None:
            args += "%s" % options

        command = template % args
        response = self.selenium.execute_async_script(command)
        return response
425496
function process(){
		if (!conf.configured) that.configure();
		var args = command.args.slice(0);
		for(var i in args){
			var arg = args[i];
			if(conf.regexp.test(arg)){
				var catchWord = RegExp.$2;
				switch(RegExp.$1){
					case '-': 
						processShortKey(catchWord, i, args);
						break;
					case '--':
						processKey(catchWord, i, args);
						break;
				}
			} else {
				addArgument(arg);
			}
		}
		conf.processed = true
	}
712329
def run(self, cmd, fn=None, globals=None, locals=None):
        """"""
        if globals is None:
            import __main__
            globals = __main__.__dict__
        if locals is None:
            locals = globals
        self.reset()
        if isinstance(cmd, str):
            str_cmd = cmd
            cmd = compile(str_cmd, fn or "<wdb>", "exec")
            self.compile_cache[id(cmd)] = str_cmd
        if fn:
            from linecache import getline
            lno = 1
            while True:
                line = getline(fn, lno, globals)
                if line is None:
                    lno = None
                    break
                if executable_line(line):
                    break
                lno += 1

        self.start_trace()
        if lno is not None:
            self.breakpoints.add(LineBreakpoint(fn, lno, temporary=True))
        try:
            execute(cmd, globals, locals)
        finally:
            self.stop_trace()
498964
def run(self):
        ''''''
        while not self.wait(self.delay()):
            try:
                logger.info('Invoking callback %s', self.callback)
                self.callback()
            except StandardError:
                logger.exception('Callback failed')
1359017
def run(self, cmd):
        """"""
        import __main__
        dikt = __main__.__dict__
        return self.runctx(cmd, dikt, dikt)
245232
def _execute_config_show(self, show_command, delay_factor=.1):
        
        rpc_command = '<CLI><Configuration>{show_command}</Configuration></CLI>'.format(
            show_command=escape_xml(show_command)
        )
        response = self._execute_rpc(rpc_command, delay_factor=delay_factor)
        raw_response = response.xpath('.//CLI/Configuration')[0].text
        return raw_response.strip() if raw_response else ''
56755
function runCommand(output, cache, cmdIndex) {
				var cmd = batch.commands[cmdIndex];
				if (cmd) {
					if (cacheContent.length !== 0 && isCachedCommand(cmd)) {
						logger.warning
							.data({ cmd: cmd.cmdName })
							.log('Re-sending cached command response');

						output += (output ? ',' : '[') + cacheContent.shift();
						return setImmediate(runCommand, output, cache, cmdIndex + 1);
					}

					return that.executeCommand(cmd, session, metaData, function (error, response) {
						if (error) {
							// should never happen
							return cb(error);
						}

						if (headerEvents && headerEvents.length) {
							response.myEvents = response.myEvents || [];
							response.myEvents = headerEvents.concat(response.myEvents);
							headerEvents = null;
						}

						const serializedResponse = serializeCommandResult(response);
						output += (output ? ',' : '[') + serializedResponse;

						if (isCachedCommand(cmd)) {
							cache += (cache ? ',' : '[') + JSON.stringify(serializedResponse);
						}

						setImmediate(runCommand, output, cache, cmdIndex + 1);
					});
				}

				// close the output JSON array

				output += ']';

				if (cache === '') {
					cache = '[]';
				} else {
					cache += ']';
				}

				// turn results array into a reportable response (possibly gzipped)

				var options = {
					mimetype: CONTENT_TYPE_JSON
				};

				if (!shouldCompress(output, acceptedEncodings)) {
					return respond(options, output, cache);
				}

				return compress(output, function (error, compressed) {
					if (error) {
						// error during compression, send the original
						respond(options, output, cache);
					} else {
						options.encoding = 'gzip';

						respond(options, compressed, cache);
					}
				});
			}
111772
function run(options, callback) {
  var settings = {}
  var stdin = new PassThrough()
  var tree
  var detectConfig
  var hasConfig
  var detectIgnore
  var hasIgnore

  try {
    stdin = process.stdin
  } catch (error) {
    /* Obscure bug in Node (seen on windows):
     * - https://github.com/nodejs/node/blob/f856234/lib/internal/
     *   process/stdio.js#L82;
     * - https://github.com/AtomLinter/linter-markdown/pull/85.
     */
  }

  if (!callback) {
    throw new Error('Missing `callback`')
  }

  if (!options || !options.processor) {
    return next(new Error('Missing `processor`'))
  }

  /* Processor. */
  settings.processor = options.processor

  /* Path to run as. */
  settings.cwd = options.cwd || process.cwd()

  /* Input. */
  settings.files = options.files || []
  settings.extensions = (options.extensions || []).map(extension)

  settings.filePath = options.filePath || null
  settings.streamIn = options.streamIn || stdin

  /* Output. */
  settings.streamOut = options.streamOut || process.stdout
  settings.streamError = options.streamError || process.stderr
  settings.alwaysStringify = options.alwaysStringify
  settings.output = options.output
  settings.out = options.out

  /* Null overwrites config settings, `undefined` doesn’t. */
  if (settings.output === null || settings.output === undefined) {
    settings.output = undefined
  }

  if (settings.output && settings.out) {
    return next(new Error('Cannot accept both `output` and `out`'))
  }

  /* Process phase management. */
  tree = options.tree || false

  settings.treeIn = options.treeIn
  settings.treeOut = options.treeOut
  settings.inspect = options.inspect

  if (settings.treeIn === null || settings.treeIn === undefined) {
    settings.treeIn = tree
  }

  if (settings.treeOut === null || settings.treeOut === undefined) {
    settings.treeOut = tree
  }

  /* Configuration. */
  detectConfig = options.detectConfig
  hasConfig = Boolean(options.rcName || options.packageField)

  if (detectConfig && !hasConfig) {
    return next(
      new Error('Missing `rcName` or `packageField` with `detectConfig`')
    )
  }

  settings.detectConfig =
    detectConfig === null || detectConfig === undefined
      ? hasConfig
      : detectConfig
  settings.rcName = options.rcName || null
  settings.rcPath = options.rcPath || null
  settings.packageField = options.packageField || null
  settings.settings = options.settings || {}
  settings.configTransform = options.configTransform
  settings.defaultConfig = options.defaultConfig

  /* Ignore. */
  detectIgnore = options.detectIgnore
  hasIgnore = Boolean(options.ignoreName)

  settings.detectIgnore =
    detectIgnore === null || detectIgnore === undefined
      ? hasIgnore
      : detectIgnore
  settings.ignoreName = options.ignoreName || null
  settings.ignorePath = options.ignorePath || null
  settings.silentlyIgnore = Boolean(options.silentlyIgnore)

  if (detectIgnore && !hasIgnore) {
    return next(new Error('Missing `ignoreName` with `detectIgnore`'))
  }

  /* Plug-ins. */
  settings.pluginPrefix = options.pluginPrefix || null
  settings.plugins = options.plugins || {}

  /* Reporting. */
  settings.reporter = options.reporter || null
  settings.reporterOptions = options.reporterOptions || null
  settings.color = options.color || false
  settings.silent = options.silent || false
  settings.quiet = options.quiet || false
  settings.frail = options.frail || false

  /* Process. */
  fileSetPipeline.run({files: options.files || []}, settings, next)

  function next(error, context) {
    var stats = statistics((context || {}).files)
    var failed = Boolean(
      settings.frail ? stats.fatal || stats.warn : stats.fatal
    )

    if (error) {
      callback(error)
    } else {
      callback(null, failed ? 1 : 0, context)
    }
  }
}
678024
function handleEvent(cmd, context, filename, callback) {
  var event = JSON.parse(cmd)
  eventline.route(event)
}
699680
def execute(self, args):
        """"""
        _run_atstart()
        hook_name = os.path.basename(args[0])
        if hook_name in self._hooks:
            try:
                self._hooks[hook_name]()
            except SystemExit as x:
                if x.code is None or x.code == 0:
                    _run_atexit()
                raise
            _run_atexit()
        else:
            raise UnregisteredHookError(hook_name)
839632
def run(self):
        '''
        
        '''
        self.status_callback('starting')
        stdout_filename = os.path.join(self.config.artifact_dir, 'stdout')
        command_filename = os.path.join(self.config.artifact_dir, 'command')

        try:
            os.makedirs(self.config.artifact_dir, mode=0o700)
        except OSError as exc:
            if exc.errno == errno.EEXIST and os.path.isdir(self.config.artifact_dir):
                pass
            else:
                raise
        os.close(os.open(stdout_filename, os.O_CREAT, stat.S_IRUSR | stat.S_IWUSR))

        command = [a.decode('utf-8') if six.PY2 else a for a in self.config.command]
        with codecs.open(command_filename, 'w', encoding='utf-8') as f:
            os.chmod(command_filename, stat.S_IRUSR | stat.S_IWUSR)
            json.dump(
                {'command': command,
                 'cwd': self.config.cwd,
                 'env': self.config.env}, f, ensure_ascii=False
            )

        if self.config.ident is not None:
            cleanup_artifact_dir(os.path.join(self.config.artifact_dir, ".."), self.config.rotate_artifacts)

        stdout_handle = codecs.open(stdout_filename, 'w', encoding='utf-8')
        stdout_handle = OutputEventFilter(stdout_handle, self.event_callback, self.config.suppress_ansible_output, output_json=self.config.json_mode)

        if not isinstance(self.config.expect_passwords, collections.OrderedDict):
            # We iterate over `expect_passwords.keys()` and
            # `expect_passwords.values()` separately to map matched inputs to
            # patterns and choose the proper string to send to the subprocess;
            # enforce usage of an OrderedDict so that the ordering of elements in
            # `keys()` matches `values()`.
            expect_passwords = collections.OrderedDict(self.config.expect_passwords)
        password_patterns = list(expect_passwords.keys())
        password_values = list(expect_passwords.values())

        # pexpect needs all env vars to be utf-8 encoded bytes
        # https://github.com/pexpect/pexpect/issues/512

        # Use a copy so as not to cause problems when serializing the job_env.
        env = {
            ensure_str(k): ensure_str(v) if k != 'PATH' and isinstance(v, six.text_type) else v
            for k, v in self.config.env.items()
        }

        self.status_callback('running')
        self.last_stdout_update = time.time()
        try:
            child = pexpect.spawn(
                command[0],
                command[1:],
                cwd=self.config.cwd,
                env=env,
                ignore_sighup=True,
                encoding='utf-8',
                echo=False,
                use_poll=self.config.pexpect_use_poll,
            )
            child.logfile_read = stdout_handle
        except pexpect.exceptions.ExceptionPexpect as e:
            child = collections.namedtuple(
                'MissingProcess', 'exitstatus isalive'
            )(
                exitstatus=127,
                isalive=lambda: False
            )

            def _decode(x):
                return x.decode('utf-8') if six.PY2 else x

            # create the events directory (the callback plugin won't run, so it
            # won't get created)
            events_directory = os.path.join(self.config.artifact_dir, 'job_events')
            if not os.path.exists(events_directory):
                os.mkdir(events_directory, 0o700)
            stdout_handle.write(_decode(str(e)))
            stdout_handle.write(_decode('\n'))

        job_start = time.time()
        while child.isalive():
            result_id = child.expect(password_patterns,
                                     timeout=self.config.pexpect_timeout,
                                     searchwindowsize=100)
            password = password_values[result_id]
            if password is not None:
                child.sendline(password)
                self.last_stdout_update = time.time()
            if self.cancel_callback:
                try:
                    self.canceled = self.cancel_callback()
                except Exception as e:
                    # TODO: logger.exception('Could not check cancel callback - cancelling immediately')
                    #if isinstance(extra_update_fields, dict):
                    #    extra_update_fields['job_explanation'] = "System error during job execution, check system logs"
                    raise CallbackError("Exception in Cancel Callback: {}".format(e))
            if self.config.job_timeout and not self.canceled and (time.time() - job_start) > self.config.job_timeout:
                self.timed_out = True
                # if isinstance(extra_update_fields, dict):
                #     extra_update_fields['job_explanation'] = "Job terminated due to timeout"
            if self.canceled or self.timed_out or self.errored:
                Runner.handle_termination(child.pid, is_cancel=self.canceled)
            if self.config.idle_timeout and (time.time() - self.last_stdout_update) > self.config.idle_timeout:
                Runner.handle_termination(child.pid, is_cancel=False)
                self.timed_out = True

        stdout_handle.flush()
        stdout_handle.close()

        if self.canceled:
            self.status_callback('canceled')
        elif child.exitstatus == 0 and not self.timed_out:
            self.status_callback('successful')
        elif self.timed_out:
            self.status_callback('timeout')
        else:
            self.status_callback('failed')
        self.rc = child.exitstatus if not (self.timed_out or self.canceled) else 254
        for filename, data in [
            ('status', self.status),
            ('rc', self.rc),
        ]:
            artifact_path = os.path.join(self.config.artifact_dir, filename)
            if not os.path.exists(artifact_path):
                os.close(os.open(artifact_path, os.O_CREAT, stat.S_IRUSR | stat.S_IWUSR))
            with open(artifact_path, 'w') as f:
                f.write(str(data))
        if self.config.directory_isolation_path and self.config.directory_isolation_cleanup:
            shutil.rmtree(self.config.directory_isolation_path)
        if self.finished_callback is not None:
            try:
                self.finished_callback(self)
            except Exception as e:
                raise CallbackError("Exception in Finished Callback: {}".format(e))
        return self.status, self.rc
993173
function run(cmd) {
        return function (callback, options) {
            grunt.verbose.or.ok("Executing " + cmd);
            exec(cmd, options || {}, function (error, stdout, stderr) {
                if (error) {
                    grunt.fatal("'" + cmd + "' failed with :" + stderr);
                } else {
                    grunt.verbose.writeln("Result of " + cmd + ':\n' + stdout);
                    callback();
                }
            });
        };
    }
288846
def get_context_from_cmdln(args, desc="Run scriptworker"):
    
    context = Context()
    parser = argparse.ArgumentParser(description=desc)
    parser.add_argument(
        "config_path", type=str, nargs="?", default="scriptworker.yaml",
        help="the path to the config file"
    )
    parsed_args = parser.parse_args(args)
    context.config, credentials = create_config(config_path=parsed_args.config_path)
    update_logging_config(context)
    return context, credentials
1265679
function load(opts, cb) {
  if(typeof opts === 'function') {
    cb = opts;
    opts = null;
  }

  var args = opts && opts.args ? opts.args : null
    , defaults = path.normalize(path.join(__dirname, 'command'));
  opts = opts || argv(args);

  if(opts.commands === undefined) {
    opts.commands = [defaults];
  }else if(Array.isArray(opts.commands) && opts.defaults) {
    opts.commands.unshift(defaults);
  }

  function onConfigError(err) {
    //console.dir(err);
    console.error(err.message);
    if(process.env.NODE_ENV !== Constants.TEST) {
      process.exit(1);
    }
  }

  this.conf.once('error', onConfigError.bind(this));

  function onConfigLoad() {
    // if we loaded ok we are done with fatal config errors
    // config set/rewrite need to catch errors now
    this.conf.removeAllListeners('error');

    this.emit('config', this.conf);

    opts.conf = this.conf;

    // spawning the daemon process
    if(this.conf.get(ConfigKey.DAEMONIZE) && !this._daemonized) {
      var pid = daemon(
        path.join(__dirname, 'daemonize.js'), this.conf, opts.args);
      if(cb) cb(pid);
      return;
    }

    this.log.notice('cwd: %s', process.cwd());

    // pass configured timeout to script manager
    ScriptManager.timeout = this.conf.get(ConfigKey.LUA_TIME_LIMIT);

    // spawn now, makes first script executions faster
    // later this should be configurable - allow disabling all
    // scripting
    ScriptManager.spawn();

    // load commands
    return loader(opts, onCommandLoad);
  }

  function onCommandLoad(err, commands) {
    if(err) return cb(err);
    this.execs = commands;
    this.emit('ready', this.execs);

    // inject command list so the script manager
    // can detect write commands
    ScriptManager.commands = commands;

    // loading from rdb files breaks the tests
    if(process.env.NODE_ENV === Constants.TEST) {
      return cb();
    }
    Persistence.load(this.state.store, this.state.conf, onDatabaseLoad);
  }

  function onDatabaseLoad(err, time, diff, version) {
    // load errors are thrown, will cause
    // the process to exit
    if(err) throw err;
    if(err !== false) {
      this.log.notice('db loaded from disk: %s seconds (v%s)', time, version);
      this.emit('database', time, diff, version);
    }
    cb();
  }

  onConfigLoad = onConfigLoad.bind(this);
  onCommandLoad = onCommandLoad.bind(this);
  onDatabaseLoad = onDatabaseLoad.bind(this);

  // load config
  this.conf.load(opts, onConfigLoad);
}
370460
def execute(self, handler, arg):
        
        return lib.zconfig_execute(self._as_parameter_, handler, arg)
215826
def _run_code(code, run_globals, init_globals=None,
              mod_name=None, mod_fname=None,
              mod_loader=None, pkg_name=None):
    """"""
    if init_globals is not None:
        run_globals.update(init_globals)
    run_globals.update(__name__ = mod_name,
                       __file__ = mod_fname,
                       __loader__ = mod_loader,
                       __package__ = pkg_name)
    exec code in run_globals
    return run_globals