Wrapper around :func:`run_cmd` for the testing using a record-replay
    model
15523
def _wrap_run_cmd(jsonfile, mode='replay'):
    
    logger = logging.getLogger(__name__)
    records = []
    counter = 0
    json_opts = {'indent': 2, 'separators':(',',': '), 'sort_keys': True}
    def run_cmd_record(*args, **kwargs):
        response = run_cmd(*args, **kwargs)
        records.append({'args': args, 'kwargs': kwargs, 'response': response})
        with open(jsonfile, 'w') as out_fh:
            json.dump(records, out_fh, **json_opts)
        return response
    def run_cmd_replay(*args, **kwargs):
        record = records.pop(0)
        logger.debug("cached run_cmd, args=%s, kwargs=%s"
                     % (str(args), str(kwargs)) )
        assert list(record['args']) == list(args), \
            "run_cmd call #%d: Obtained args: '%s'; Expected args: '%s'" \
            % (counter+1, str(args), str(record['args']))
        assert record['kwargs'] == kwargs, \
            "run_cmd call #%d: Obtained kwargs: '%s'; Expected kwargs: '%s'" \
            % (counter+1, str(kwargs), str(record['kwargs']))
        response = record['response']
        if "\n" in response:
            if len(response.splitlines()) == 1:
                logger.debug("cached response: %s", response)
            else:
                logger.debug("cached response: ---\n%s\n---", response)
        else:
            logger.debug("cached response: '%s'", response)
        return response
    if mode == 'replay':
        with open(jsonfile) as in_fh:
            records = json.load(in_fh)
        return run_cmd_replay
    elif mode == 'record':
        return run_cmd_record
    else:
        raise ValueError("Invalid mode")
590543
def run_command(*cmd, **kwargs):
    ''
    logging.debug('Running: {0} with {1}'.format(cmd, kwargs))
    kwargs['stdout'] = sys.stderr
    subprocess.check_call(cmd, **kwargs)
1171448
def run_step(*args, prompt=None):
    
    global DRY_RUN

    cmd = args
    print(' '.join(cmd))
    if skip_step():
        print('--- Skipping...')
    elif DRY_RUN:
        print('--- Pretending to run...')
    else:
        if prompt:
            print(prompt)
        subprocess.check_output(cmd)
411930
def run_track(track,
              result_hosts=None,
              crate_root=None,
              output_fmt=None,
              logfile_info=None,
              logfile_result=None,
              failfast=False,
              sample_mode='reservoir'):
    """"""
    with Logger(output_fmt=output_fmt,
                logfile_info=logfile_info,
                logfile_result=logfile_result) as log:
        executor = Executor(
            track_dir=os.path.dirname(track),
            log=log,
            result_hosts=result_hosts,
            crate_root=crate_root,
            fail_fast=failfast,
            sample_mode=sample_mode
        )
        error = executor.execute(toml.load(track))
        if error:
            sys.exit(1)
315514
def monkey_patch_behave(django_test_runner):
    
    behave_run_hook = ModelRunner.run_hook

    def run_hook(self, name, context, *args):
        if name == 'before_all':
            django_test_runner.patch_context(context)

        behave_run_hook(self, name, context, *args)

        if name == 'before_scenario':
            django_test_runner.setup_testclass(context)
            django_test_runner.setup_fixtures(context)
            django_test_runner.setup_test(context)
            behave_run_hook(self, 'django_ready', context)

        if name == 'after_scenario':
            django_test_runner.teardown_test(context)

    ModelRunner.run_hook = run_hook
882575
def record(session_file, shell, prompt, alias, envvar):
    
    if os.path.exists(session_file):
        click.confirm(
            'File "{0}" already exists. Overwrite?'.format(session_file),
            abort=True,
            default=False,
        )

    secho("We'll do it live!", fg="red", bold=True)
    filename = click.format_filename(session_file)
    secho("RECORDING SESSION: {}".format(filename), fg="yellow", bold=True)

    print_recorder_instructions()

    click.pause()
    click.clear()
    cwd = os.getcwd()  # Save cwd

    # Run the recorder
    commands = run_recorder(shell, prompt, aliases=alias, envvars=envvar)

    os.chdir(cwd)  # Reset cwd

    secho("FINISHED RECORDING SESSION", fg="yellow", bold=True)
    secho("Writing to {0}...".format(filename), fg="cyan")
    with open(session_file, "w", encoding="utf-8") as fp:
        fp.write(HEADER_TEMPLATE.format(shell=shell, prompt=prompt))
        write_directives(fp, "alias", alias)
        write_directives(fp, "env", envvar)
        fp.write("\n")
        fp.write("".join(commands))
        fp.write("\n")

    play_cmd = style("doitlive play {}".format(filename), bold=True)
    echo("Done. Run {} to play back your session.".format(play_cmd))
722421
def _replay_info(replay_path):
  """"""
  if not replay_path.lower().endswith("sc2replay"):
    print("Must be a replay.")
    return

  run_config = run_configs.get()
  with run_config.start(want_rgb=False) as controller:
    info = controller.replay_info(run_config.replay_data(replay_path))
  print("-" * 60)
  print(info)
177058
def iprompt(self, out=sys.stdout):
        """"""

        cmds = """
        Commands:
          i -- index: print current iteration index
          p -- pause: interrupt sampling and return to the main console.
                      Sampling can be resumed later with icontinue().
          h -- halt:  stop sampling and truncate trace. Sampling cannot be
                      resumed for this chain.
          b -- bg:    return to the main console. The sampling will still
                      run in a background thread. There is a possibility of
                      malfunction if you interfere with the Sampler's
                      state or the database during sampling. Use this at your
                      own risk.
        """

        print_("""==============
 PyMC console
==============

        PyMC is now sampling. Use the following commands to query or pause the sampler.
        """, file=out)
        print_(cmds, file=out)

        prompt = True
        try:
            while self.status in ['running', 'paused']:
                    # sys.stdout.write('pymc> ')
                if prompt:
                    out.write('pymc > ')
                    out.flush()

                if self._exc_info is not None:
                    a, b, c = self._exc_info
                    reraise(a, b, c)

                cmd = utils.getInput().strip()
                if cmd == 'i':
                    print_(
                        'Current iteration: %i of %i' %
                        (self._current_iter, self._iter), file=out)
                    prompt = True
                elif cmd == 'p':
                    self.status = 'paused'
                    break
                elif cmd == 'h':
                    self.status = 'halt'
                    self._halt()
                    break
                elif cmd == 'b':
                    return
                elif cmd == '\n':
                    prompt = True
                    pass
                elif cmd == '':
                    prompt = False
                else:
                    print_('Unknown command: ', cmd, file=out)
                    print_(cmds, file=out)
                    prompt = True

        except KeyboardInterrupt:
            if not self.status == 'ready':
                self.status = 'halt'
                self._halt()

        if self.status == 'ready':
            print_("Sampling terminated successfully.", file=out)
        else:
            print_('Waiting for current iteration to finish...', file=out)
            while self._sampling_thread.isAlive():
                sleep(.1)
            print_('Exiting interactive prompt...', file=out)
            if self.status == 'paused':
                print_(
                    'Call icontinue method to continue, or call halt method to truncate traces and stop.',
                    file=out)
223182
def _verify_run(out, cmd=None):
    '''
    
    '''
    if out.get('retcode', 0) and out['stderr']:
        if cmd:
            log.debug('Command: \'%s\'', cmd)

        log.debug('Return code: %s', out.get('retcode'))
        log.debug('Error output:\n%s', out.get('stderr', 'N/A'))

        raise CommandExecutionError(out['stderr'])
536916
def run(commandline, echo = false, stdin = nil)
      log.debug "running `#{commandline}`"

      out_recorder = echo ? RecordingIO.new(STDOUT) : RecordingIO.new
      err_recorder = echo ? RecordingIO.new(STDERR) : RecordingIO.new

      status = Open4.spawn(commandline, stdin: stdin, stdout: out_recorder,
                                        stderr: err_recorder, quiet: true).exitstatus

      log.debug "`#{commandline}` exited with status #{status}"

      if status != 0
        log.warn("`#{commandline}` failed with status #{status}")
        out = out_recorder.record
        err = err_recorder.record
        if out != "" || err != ""
          log.warn("Output follows:")
          log.warn(out) unless out == ""
          log.warn(err) unless err == ""
        end
        fail ExecutionFailed.new(commandline, status, out, err)
      end

      out_recorder.record
    end
294016
def run(self):
        
        # TODO is a separate thread necessary?  Wouldn't a threadPool.execute
        #      suffice?
        self.running = True
        self.recordCond.acquire()
        while self.running or self.recordQueue:
            # Check for new entries.  If none: wait.
            if self.running and not self.recordQueue:
                self.recordCond.wait()
                continue
            entries = list(reversed(self.recordQueue))
            self.recordQueue = []
            self.recordCond.release()
            with self.lock:
                # Record the entries
                for now, updates, source in entries:
                    for pc, occupation in updates.iteritems():
                        self.c.execute(""" INSERT INTO occupationUpdates
                                            ( pc, datetime, occupation, source )
                                           VALUES ( ?, ?, ?, ? ) """, (
                                   self._id_for_pc(pc), now, occupation,
                                   self._id_for_source(source)))
                self.conn.commit()
            self.recordCond.acquire()
        self.recordCond.release()
1278570
def run(
    commands,
    shell=None,
    prompt_template="default",
    speed=1,
    quiet=False,
    test_mode=False,
    commentecho=False,
):
    """"""
    if not quiet:
        secho("We'll do it live!", fg="red", bold=True)
        secho(
            "STARTING SESSION: Press Ctrl-C at any time to exit.",
            fg="yellow",
            bold=True,
        )
        click.pause()

    click.clear()
    state = SessionState(
        shell=shell,
        prompt_template=prompt_template,
        speed=speed,
        test_mode=test_mode,
        commentecho=commentecho,
    )

    i = 0
    while i < len(commands):
        command = commands[i].strip()
        i += 1
        if not command:
            continue
        is_comment = command.startswith("#")
        if not is_comment:
            command_as_list = shlex.split(ensure_utf8(command))
        else:
            command_as_list = None
        shell_match = SHELL_RE.match(command)
        if is_comment:
            # Parse comment magic
            match = OPTION_RE.match(command)
            if match:
                option, arg = match.group("option"), match.group("arg")
                func = OPTION_MAP[option]
                func(state, arg)
            elif state.commentecho():
                comment = command.lstrip("#")
                secho(comment, fg="yellow", bold=True)
            continue
        # Handle 'export' and 'alias' commands by storing them in SessionState
        elif command_as_list and command_as_list[0] in ["alias", "export"]:
            magictype(
                command, prompt_template=state["prompt_template"], speed=state["speed"]
            )
            # Store the raw commands instead of using add_envvar and add_alias
            # to avoid having to parse the command ourselves
            state.add_command(command)
        # Handle ```python and ```ipython by running "player" consoles
        elif shell_match:
            shell_name = shell_match.groups()[0].strip()
            py_commands = []
            more = True
            while more:  # slurp up all the python code
                try:
                    py_command = commands[i].rstrip()
                except IndexError:
                    raise SessionError(
                        "Unmatched {0} code block in "
                        "session file.".format(shell_name)
                    )
                i += 1
                if py_command.startswith("```"):
                    i += 1
                    more = False
                else:
                    py_commands.append(py_command)
            # Run the player console
            magictype(
                shell_name,
                prompt_template=state["prompt_template"],
                speed=state["speed"],
            )

            if shell_name == "ipython":
                try:
                    from doitlive.ipython_consoles import start_ipython_player
                except ImportError:
                    raise RuntimeError(
                        "```ipython blocks require IPython to be installed"
                    )
                # dedent all the commands to account for IPython's autoindentation
                ipy_commands = [textwrap.dedent(cmd) for cmd in py_commands]
                start_ipython_player(ipy_commands, speed=state["speed"])
            else:
                start_python_player(py_commands, speed=state["speed"])
        else:
            # goto_stealthmode determines when to switch to stealthmode
            goto_stealthmode = magicrun(command, **state)
            # stealthmode allows user to type live commands outside of automated script
            i -= stealthmode(state, goto_stealthmode)
    echo_prompt(state["prompt_template"])
    wait_for(RETURNS)
    if not quiet:
        secho("FINISHED SESSION", fg="yellow", bold=True)
1033030
def run(self, in_batches):
        
        if len(in_batches) != len(self._batcmd.batch_to_file_s):
            BaseShellOperator._rm_process_input_tmpfiles(self._batcmd.batch_to_file_s)  # [todo] - Removing tmpfiles can be easily forgot. Less lifetime for tmpfile.
            raise AttributeError('len(in_batches) == %d, while %d IN_BATCH* are specified in command below:%s$ %s' %
                                 (len(in_batches), len(self._batcmd.batch_to_file_s), os.linesep, self._batcmd.sh_cmd))

        # prepare & start process
        BaseShellOperator._batches_to_tmpfile(self._in_record_sep, self._in_column_sep, in_batches, self._batcmd.batch_to_file_s)
        process = BaseShellOperator._start_process(self._batcmd, self._cwd, self._env)
        BaseShellOperator._batch_to_stdin(process, self._in_record_sep, self._in_column_sep, in_batches, self._batcmd.batch_to_file_s)

        # wait process & get its output
        BaseShellOperator._close_process_input_stdin(self._batcmd.batch_to_file_s)
        BaseShellOperator._wait_process(process, self._batcmd.sh_cmd, self._success_exitcodes)
        BaseShellOperator._rm_process_input_tmpfiles(self._batcmd.batch_to_file_s)

        if self._batcmd.batch_from_file.is_stdout():
            out_str = self._batcmd.batch_from_file.read_stdout(process.stdout)
        elif self._batcmd.batch_from_file.is_tmpfile():
            out_str = self._batcmd.batch_from_file.read_tmpfile()
        else:  # pragma: no cover
            assert(False)

        out_batch = BaseShellOperator._out_str_to_batch(out_str, self._out_recdef, self._out_col_patterns)
        self._batcmd.batch_from_file.finish()
        return out_batch
359102
function runRecordRoute(callback) {
  var argv = parseArgs(process.argv, {
    string: 'db_path'
  });
  fs.readFile(path.resolve(argv.db_path), function(err, data) {
    if (err) {
      callback(err);
      return;
    }
    // Transform the loaded features to Feature objects
    var feature_list = _.map(JSON.parse(data), function(value) {
      var feature = new messages.Feature();
      feature.setName(value.name);
      var location = new messages.Point();
      location.setLatitude(value.location.latitude);
      location.setLongitude(value.location.longitude);
      feature.setLocation(location);
      return feature;
    });

    var num_points = 10;
    var call = client.recordRoute(function(error, stats) {
      if (error) {
        callback(error);
        return;
      }
      console.log('Finished trip with', stats.getPointCount(), 'points');
      console.log('Passed', stats.getFeatureCount(), 'features');
      console.log('Travelled', stats.getDistance(), 'meters');
      console.log('It took', stats.getElapsedTime(), 'seconds');
      callback();
    });
    /**
     * Constructs a function that asynchronously sends the given point and then
     * delays sending its callback
     * @param {messages.Point} location The point to send
     * @return {function(function)} The function that sends the point
     */
    function pointSender(location) {
      /**
       * Sends the point, then calls the callback after a delay
       * @param {function} callback Called when complete
       */
      return function(callback) {
        console.log('Visiting point ' + location.getLatitude()/COORD_FACTOR +
            ', ' + location.getLongitude()/COORD_FACTOR);
        call.write(location);
        _.delay(callback, _.random(500, 1500));
      };
    }
    var point_senders = [];
    for (var i = 0; i < num_points; i++) {
      var rand_point = feature_list[_.random(0, feature_list.length - 1)];
      point_senders[i] = pointSender(rand_point.getLocation());
    }
    async.series(point_senders, function() {
      call.end();
    });
  });
}
1190573
def replayOne(self, r):
        ''
        CommandLog.currentReplayRow = r

        longname = getattr(r, 'longname', None)
        if longname == 'set-option':
            try:
                options.set(r.row, r.input, options._opts.getobj(r.col))
                escaped = False
            except Exception as e:
                exceptionCaught(e)
                escaped = True
        else:
            vs = self.moveToReplayContext(r)

            vd().keystrokes = r.keystrokes
            # <=v1.2 used keystrokes in longname column; getCommand fetches both
            escaped = vs.exec_command(vs.getCommand(longname if longname else r.keystrokes), keystrokes=r.keystrokes)

        CommandLog.currentReplayRow = None

        if escaped:  # escape during replay aborts replay
            warning('replay aborted')
        return escaped
496003
def _run_and_log(cmd, ostree_repo_path, error_msg, wd=None):
        
        logger.debug("running command %s", cmd)
        kwargs = {
            "stderr": subprocess.STDOUT,
            "env": os.environ.copy(),
        }
        if ostree_repo_path:
            # must not exist, ostree will create it
            kwargs["env"]["ATOMIC_OSTREE_REPO"] = ostree_repo_path
        if wd:
            kwargs["cwd"] = wd
        try:
            out = subprocess.check_output(cmd, **kwargs)
        except subprocess.CalledProcessError as ex:
            logger.error(ex.output)
            logger.error(error_msg)
            raise
        logger.debug("%s", out)
952833
def start_record():
    
    global record, playback, current
    if record:
        raise StateError("Already recording.")
    if playback:
        raise StateError("Currently playing back.")
    record = True
    current = ReplayData()
    install(RecordingHTTPConnection, RecordingHTTPSConnection)