Commands invoke through key actions or otherwise will be captured after running when while running doFunc and the result returned *instead* of triggering normal actions. This basically overwrites the typical ed.commands.exec handler
188622
function captureEditorCommand(ed, captureCommandFunc, captureCallFunc) {
  var origCallKeyboardHandlers = ed.keyBinding.$callKeyboardHandlers,
      commandExecHandler = ed.commands.addEventListener('exec', function(e) {
        uninstall();
        e.stopPropagation(); e.preventDefault();
        captureCommandFunc && captureCommandFunc(e.command, e);
        return true;
      });

  var orig = ed.keyBinding.$callKeyboardHandlers;
  ed.keyBinding.$callKeyboardHandlers = function(hashId, keyString, keyCode, e) {
    captureCallFunc && captureCallFunc(hashId, keyString, keyCode, e);
    return orig.call(this, hashId, keyString, keyCode, e);
  };

  return uninstall;

  // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

  function uninstall() {
    commandExecHandler && ed.commands.removeEventListener('exec', commandExecHandler);
    ed.keyBinding.$callKeyboardHandlers = orig;
  }

}
664267
def _exec_command(self, cmd):
        
        _, out, err = self._client.exec_command(cmd, timeout=self._timeout)
        return out.read().strip() if not err.read().strip() else None
35999
function checkExec (mode, callback) {
  if (!exercise.passed)
    return callback(null, true) // shortcut if we've already had a failure

  childProcess.exec(
        '"'
      + process.execPath
      + '" "'
      + copyTempDir
      + '" "'
      + expected
      + '"'
    , function (err, stdout, stderr) {
        if (err) {
          process.stderr.write(stderr)
          process.stdout.write(stdout)
          return callback(err)
        }

        var pass = stdout.toString().replace('\r', '') == expected + '\n'
          , seminl = !pass && stdout.toString() == expected

        if (!seminl && !pass) {
          process.stderr.write(stderr)
          process.stdout.write(stdout)
        }

        if (seminl)
          exercise.emit('fail', 'Addon prints out expected string (missing newline)')
        else
          exercise.emit(pass ? 'pass' : 'fail', 'Addon prints out expected string')

        callback(null, pass)
      }
  )
}
781447
def execute_command(self, generator, write_concern, session):
        
        # nModified is only reported for write commands, not legacy ops.
        full_result = {
            "writeErrors": [],
            "writeConcernErrors": [],
            "nInserted": 0,
            "nUpserted": 0,
            "nMatched": 0,
            "nModified": 0,
            "nRemoved": 0,
            "upserted": [],
        }
        op_id = _randint()

        def retryable_bulk(session, sock_info, retryable):
            self._execute_command(
                generator, write_concern, session, sock_info, op_id,
                retryable, full_result)

        client = self.collection.database.client
        with client._tmp_session(session) as s:
            client._retry_with_session(
                self.is_retryable, retryable_bulk, s, self)

        if full_result["writeErrors"] or full_result["writeConcernErrors"]:
            _raise_bulk_write_error(full_result)
        return full_result
1075462
function handler(current, argv) {
        var cmds = pargv._commands;
        var completions = [];
        if (pargv._env.EXEC === argv[0])
            argv.shift(); // remove first arg which is app/exec name.
        var tmpCmd = pargv.getCommand(utils.first(argv)); // is first is known command.
        if (tmpCmd) { // limit to single command if known.
            cmds = {}; // set the commands to just the one known command.
            cmds[tmpCmd._name] = tmpCmd;
            var sliced_1 = argv.slice(1); // remove command name.
            var curCmdIdx_1 = 0;
            var lastCmdIdx_1 = tmpCmd._arguments.length - 1; // last index for commands.
            sliced_1.forEach(function (el, i) {
                if (!constants_1.FLAG_EXP.test(el) && i <= lastCmdIdx_1) {
                    var prev_1 = sliced_1[i - 1] || null;
                    var prevKey = tmpCmd.isOption(prev_1);
                    if (!prevKey && !constants_1.FLAG_EXP.test(prev_1)) // could be val for option.
                        curCmdIdx_1 = i;
                }
            });
            var curIdx = sliced_1.length - 1;
            var prevIdx = sliced_1.length - 2;
            var prev = sliced_1[prevIdx] || null;
            var isFlagPrev = prev && constants_1.FLAG_EXP.test(prev);
            var isBool = tmpCmd.isBool(prev);
            var isOption = isFlagPrev && !isBool;
            var isCommand = (curCmdIdx_1 >= 0) &&
                (curCmdIdx_1 <= lastCmdIdx_1);
            //  !FLAG_EXP.test(sliced[curIdx])
            if (isCommand || isOption) {
                var key = isOption ? tmpCmd.aliasToKey(prev) : tmpCmd.aliasToKey(curCmdIdx_1);
                if (tmpCmd._completions[key])
                    completions = completions.concat(tmpCmd._completions[key]);
            }
            if (tmpCmd._completions['*']) // anon custom completions.
                completions = completions.concat(tmpCmd._completions['*']);
        }
        else {
            var _loop_1 = function (k) {
                var cmd = cmds[k];
                [cmd._name].concat(cmd.aliases(cmd._name) || []) // iterate commands.
                    .forEach(function (el, i) {
                    if (!~completions.indexOf(el))
                        completions.push(el);
                });
                cmd._options.forEach(function (o) {
                    if (!~completions.indexOf(o))
                        completions.push(o);
                    (cmd.aliases(o) || []).forEach(function (el) {
                        if (!~completions.indexOf(el))
                            completions.push(el);
                    });
                });
            };
            for (var k in cmds) {
                _loop_1(k);
            }
        }
        // TODO: clunky redundant need to refactor this.
        var _options = completions.filter(function (c) { return constants_1.FLAG_EXP.test(c); });
        var _cmds = completions.filter(function (c) { return !constants_1.FLAG_EXP.test(c); });
        return _cmds.sort().concat(_options.sort());
    }
1050623
def execute_flow(self, custom_command="", is_config=False):
        

        responses = []
        if isinstance(custom_command, str):
            commands = [custom_command]
        elif isinstance(custom_command, tuple):
            commands = list(custom_command)
        else:
            commands = custom_command

        if is_config:
            mode = self._cli_handler.config_mode
            if not mode:
                raise Exception(self.__class__.__name__,
                                "CliHandler configuration is missing. Config Mode has to be defined")
        else:
            mode = self._cli_handler.enable_mode
            if not mode:
                raise Exception(self.__class__.__name__,
                                "CliHandler configuration is missing. Enable Mode has to be defined")

        with self._cli_handler.get_cli_service(mode) as session:
            for cmd in commands:
                responses.append(session.send_command(command=cmd))
        return '\n'.join(responses)
285949
protected void handleProcessTimeout(String[] cmd) throws IOException {
        StringBuilder bld   = new StringBuilder();
        boolean       first = true;
        for (String c : cmd) {
            if (first) {
                first = false;
            } else {
                bld.append(" ");
            }

            String esc = Strings.escape(c);

            // Quote where escaping is needed, OR the argument
            // contains a literal space.
            if (!c.equals(esc) || c.contains(" ")) {
                bld.append('\"')
                   .append(esc)
                   .append('\"');
            } else {
                bld.append(c);
            }
        }

        throw new IOException("Process took too long: " + bld.toString());
    }
1283826
function doExec(callback, command) {
    let args = Array.prototype.slice.call(arguments);
    args.splice(0, 2);  //remove the first cb and command
    if (!this.isConnected()) {
      return callback(thorin.error('REDIS.NOT_CONNECTED', 'The connection is not active yet.'));
    }
    command = command.toLowerCase();
    if (typeof this[connections].default.connection[command] !== 'function') {
      return callback(thorin.error('REDIS.COMMAND_NOT_FOUND', 'Invalid command issued: ' + command, 500));
    }
    args.push((err, res) => {
      if (err) {
        return callback(thorin.error('REDIS.EXEC', 'Redis command failed to execute.', err));
      }
      if (command === 'hgetall' && typeof res === 'object' && res) {
        // backward compatibility
        if (Object.keys(res).length === 0) {
          res = null;
        }
      }
      callback(null, res);
    });
    this[connections].default.emit('command', command, args);
    this[connections].default.connection[command].apply(this[connections].default.connection, args);
  }
756277
def handle_command(command):
  
  try:
    cmds = command.split(None, 1)
    cmd = cmds[0]
    if cmd == 'new':
      add_task(get_arg(cmds))
    elif cmd == 'done':
      mark_done(int(get_arg(cmds)))
    elif cmd == 'list':
      for task in format_tasks(list_tasks()):
        print task
    elif cmd == 'delete':
      delete_task(int(get_arg(cmds)))
    else:
      print_usage()
  except Exception, e:  # pylint: disable=broad-except
    print e
    print_usage()
1060488
def capture(command, input=None, cwd=None, shell=False, raiseOnError=False):
		
		
		# Attempt to execute the child process
		proc = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=cwd, shell=shell, universal_newlines=True)
		(stdout, stderr) = proc.communicate(input)
		
		# If the child process failed and we were asked to raise an exception, do so
		if raiseOnError == True and proc.returncode != 0:
			raise Exception(
				'child process ' + str(command) +
				' failed with exit code ' + str(proc.returncode) +
				'\nstdout: "' + stdout + '"' +
				'\nstderr: "' + stderr + '"'
			)
		
		return CommandOutput(proc.returncode, stdout, stderr)
1263101
def command(self, details):
        
        log = self._params.get('log', self._discard)
        if '_config_running' not in dir(self._parent) or 'commands' not in self._parent._config_running:
            log.error("Event parent '%s' has no 'commands' config section", self._name)
            return
        commands = self._parent._config_running['commands']
        if self._handler_arg not in commands:
            #  For now, at least, we implement a predefined command 'stop' if there is no
            #  explicit stop.  This probably needs more work because it needs to handle
            #  async commands where 'stop' would translate to a SIGTERM of the pid file.
            #
            if self._handler_arg == 'stop':
                self._parent.stop()
            else:
                log.error("Event parent '%s' has no '%s' command configured", self._name, self._handler_arg)
            return
        pid = _exec_process(commands[self._handler_arg], self._parent._context, log=log)
        log.info("Forked pid %d for %s(%s)", pid, self._name, self._handler_arg)
        self._parent._legion.proc_add(event_target(self._parent, 'command_exit', key=pid, arg=self._handler_arg, log=log))
724941
def do_execute(self):
        
        result = None
        f = None
        try:
            if bool(self.resolve_option("append")):
                f = open(str(self.resolve_option("output")), "a")
            else:
                f = open(str(self.resolve_option("output")), "w")
            f.write(str(self.input.payload))
            f.write("\n")
        except Exception as e:
            result = self.full_name + "\n" + traceback.format_exc()
        finally:
            if f is not None:
                f.close()
        return result
468654
def exec_cmd(self, command, **kwargs):
        

        if command == 'load':
            if kwargs:
                kwargs = dict(options=[kwargs])
        return self._exec_cmd(command, **kwargs)
812752
def run_command_on_event(self, command, phase=phases.ASAP):
        
        self._set('exec-%s' % phase, command, multi=True)

        return self._section
768278
function _handleCommandRegistered(event, command) {
        var commandId   = command.getID(),
            defaults    = KeyboardPrefs[commandId];

        if (defaults) {
            addBinding(commandId, defaults);
        }
    }
987673
function process(parent, index, commands) {
    var cmd = commands[index],
        ret;

    switch (cmd.value[0].type) {
        case ConkittyTypes.TEMPLATE_NAME:
            ret = processCall(parent, false, cmd);
            break;

        case ConkittyTypes.COMMAND_NAME:
            switch (cmd.value[0].value) {
                case 'ATTR':
                    ret = processAttr(parent, true, cmd);
                    break;

                case 'CALL':
                    ret = processCall(parent, true, cmd, commands[index + 1]);
                    break;

                case 'CHOOSE':
                    ret = processChoose(parent, cmd);
                    break;

                case 'EACH':
                    ret = processEach(parent, cmd, commands[index + 1]);
                    break;

                case 'EXPOSE':
                    ret = processExpose(parent, cmd);
                    break;

                case 'JS':
                    ret = processJS(parent, cmd);
                    break;

                case 'MEM':
                    ret = processMem(parent, cmd);
                    break;

                case 'PAYLOAD':
                    ret = processPayload(parent, cmd);
                    break;

                case 'SET':
                    ret = processSet(parent, cmd);
                    break;

                case 'TEST':
                    ret = processTest(parent, cmd);
                    break;

                case 'TRIGGER':
                    ret = processTrigger(parent, cmd);
                    break;

                case 'WITH':
                    ret = processWith(parent, cmd, commands[index + 1]);
                    break;

                default:
                    throw new ConkittyErrors.InconsistentCommand(cmd.value[0]);
            }

            break;

        case ConkittyTypes.VARIABLE:
            ret = processVariable(parent, cmd);
            break;

        case ConkittyTypes.JAVASCRIPT:
            ret = processJavascript(parent, cmd);
            break;

        case ConkittyTypes.STRING:
            ret = processString(parent, cmd);
            break;

        case ConkittyTypes.CSS:
            ret = processElement(parent, cmd);
            break;

        case ConkittyTypes.ATTR:
            ret = processAttr(parent, false, cmd);
            break;

        case ConkittyTypes.INCLUDE:
            ret = processInclude(parent, cmd);
            break;

        case ConkittyTypes.NODE_APPENDER:
            ret = processAppender(parent, cmd);
            break;

        default:
            throw new ConkittyErrors.InconsistentCommand(cmd.value[0]);
    }

    return index + ret;
}
592064
function exec() {

  var actions = {
    commands: {
      init: { action: _init },
      run : { action: _run }
    }
  };

  cli.command(__dirname, actions);
}