Run the command inside a thread so that we can catch output for each
        line as it comes in and display it.
435185
def _persist(self):
        
        # run the block/command
        for command in self.commands:
            try:
                process = Popen(
                    [command],
                    stdout=PIPE,
                    stderr=PIPE,
                    universal_newlines=True,
                    env=self.env,
                    shell=True,
                )
            except Exception as e:
                retcode = process.poll()
                msg = "Command '{cmd}' {error} retcode {retcode}"
                self.py3.log(msg.format(cmd=command, error=e, retcode=retcode))

            # persistent blocklet output can be of two forms.  Either each row
            # of the output is on a new line this is much easier to deal with)
            # or else the output can be continuous and just flushed when ready.
            # The second form is more tricky, if we find newlines then we
            # switch to easy parsing of the output.

            # When we have output we store in self.persistent_output and then
            # trigger the module to update.

            fd = process.stdout.fileno()
            fl = fcntl.fcntl(fd, fcntl.F_GETFL)
            has_newlines = False
            while True:
                line = process.stdout.read(1)
                # switch to a non-blocking read as we do not know the output
                # length
                fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NONBLOCK)
                line += process.stdout.read(1024)
                # switch back to blocking so we can wait for the next output
                fcntl.fcntl(fd, fcntl.F_SETFL, fl)
                if process.poll():
                    break
                if self.py3.is_python_2():
                    line = line.decode("utf-8")
                self.persistent_output = line
                self.py3.update()
                if line[-1] == "\n":
                    has_newlines = True
                    break
                if line == "":
                    break
            if has_newlines:
                msg = "Switch to newline persist method {cmd}"
                self.py3.log(msg.format(cmd=command))
                # just read the output in a sane manner
                for line in iter(process.stdout.readline, b""):
                    if process.poll():
                        break
                    if self.py3.is_python_2():
                        line = line.decode("utf-8")
                    self.persistent_output = line
                    self.py3.update()
        self.py3.log("command exited {cmd}".format(cmd=command))
        self.persistent_output = "Error\nError\n{}".format(
            self.py3.COLOR_ERROR or self.py3.COLOR_BAD
        )
        self.py3.update()
1142700
def run_command(args, asynchronous=False):
    """"""
    logging.info("Executing %s command %s.",
                 asynchronous and 'asynchronous' or 'synchronous', args)

    process = subprocess.Popen(args,
                               shell=True,
                               stdout=subprocess.PIPE,
                               stderr=subprocess.STDOUT)

    try:
        timeout = asynchronous and 1 or None
        output = process.communicate(timeout=timeout)[0].decode('utf8')
    except subprocess.TimeoutExpired:
        pass

    if asynchronous:
        return PopenOutput(None, 'Asynchronous call.')
    else:
        return PopenOutput(process.returncode, output)
1108822
def run(cmd, filename=None, threads=True, verbose=False):
    """"""
    _run(threads, verbose, 'run', filename, cmd)
447019
def run(cmd, shell=False, debug=False):
    ''
    proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=shell)
    (out, _) = proc.communicate()  # no need for stderr
    if debug:
        print(cmd)
        print(out)
    return out
770016
def run(self):
        """"""
        self.logger.debug(f'Running command: {self.cmd}')

        def execute(cmd):
            output = ""
            popen = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
                                     universal_newlines=True, shell=True)
            for stdout_line in iter(popen.stdout.readline, ""):
                stdout_line = stdout_line.strip('\n')
                output += stdout_line
                yield stdout_line
            popen.stdout.close()
            return_code = popen.wait()
            if return_code:
                raise subprocess.CalledProcessError(return_code, cmd, output)

        try:
            for out in execute(self.cmd):
                self.logger.info(out)
            return "", 0
        except subprocess.CalledProcessError as e:
            return e.output, e.returncode
165845
public synchronized void execute(Runnable command) {
        if (active.get()) {
            stop();
            this.command = command;
            start();
        } else {
            this.command = command;
        }
    }
1247558
def run(self, command, options, pipe=False, get_stdout=False, memscale=None):
        
        cl = self.cl_picard(command, options, memscale=memscale)
        if pipe:
            subprocess.Popen(cl)
        elif get_stdout:
            p = subprocess.Popen(cl, stdout=subprocess.PIPE)
            stdout = p.stdout.read()
            p.wait()
            p.stdout.close()
            return stdout
        else:
            do.run(cl, "Picard {0}".format(command), None)
1316316
def run_command(self, command):
        
        self.display = DISPLAYS["stdout"]
        self.conf["pagesize"] = 0
        self.onecmd(command)
164384
async def runCmdLine(self, line):
        '''
        

        '''
        opts = self.getCmdOpts(line)
        return await self.runCmdOpts(opts)
1012599
def run(cls, command, cwd=".", **kwargs):
        
        assert isinstance(command, six.string_types)
        command_result = CommandResult()
        command_result.command = command
        use_shell = cls.USE_SHELL
        if "shell" in kwargs:
            use_shell = kwargs.pop("shell")

        # -- BUILD COMMAND ARGS:
        if six.PY2 and isinstance(command, six.text_type):
            # -- PREPARE-FOR: shlex.split()
            # In PY2, shlex.split() requires bytes string (non-unicode).
            # In PY3, shlex.split() accepts unicode string.
            command = codecs.encode(command, "utf-8")
        cmdargs = shlex.split(command)

        # -- TRANSFORM COMMAND (optional)
        command0 = cmdargs[0]
        real_command = cls.COMMAND_MAP.get(command0, None)
        if real_command:
            cmdargs0 = real_command.split()
            cmdargs = cmdargs0 + cmdargs[1:]
        preprocessors = cls.PREPROCESSOR_MAP.get(command0)
        if preprocessors:
            cmdargs = cls.preprocess_command(preprocessors, cmdargs, command, cwd)


        # -- RUN COMMAND:
        try:
            process = subprocess.Popen(cmdargs,
                            stdout=subprocess.PIPE,
                            stderr=subprocess.PIPE,
                            universal_newlines=True,
                            shell=use_shell,
                            cwd=cwd, **kwargs)
            out, err = process.communicate()
            if six.PY2: # py3: we get unicode strings, py2 not
                default_encoding = 'UTF-8'
                out = six.text_type(out, process.stdout.encoding or default_encoding)
                err = six.text_type(err, process.stderr.encoding or default_encoding)
            process.poll()
            assert process.returncode is not None
            command_result.stdout = out
            command_result.stderr = err
            command_result.returncode = process.returncode
            if cls.DEBUG:
                print("shell.cwd={0}".format(kwargs.get("cwd", None)))
                print("shell.command: {0}".format(" ".join(cmdargs)))
                print("shell.command.output:\n{0};".format(command_result.output))
        except OSError as e:
            command_result.stderr = u"OSError: %s" % e
            command_result.returncode = e.errno
            assert e.errno != 0

        postprocessors = cls.POSTPROCESSOR_MAP.get(command0)
        if postprocessors:
            command_result = cls.postprocess_command(postprocessors, command_result)
        return command_result
1065408
def run(self, cmd):
        """"""
        print datetime.datetime.now()
        output = subprocess.Popen(cmd, shell=True)
        output = output.communicate()[0]
        print output
576593
def runCommand(cmd, timeout=None, window=None):
    
    p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    output = ''
    for line in p.stdout:
        line = line.decode(errors='replace' if (sys.version_info) < (3, 5) else 'backslashreplace').rstrip()
        output += line
        print(line)
        window.Refresh() if window else None        # yes, a 1-line if, so shoot me

    retval = p.wait(timeout)
    return (retval, output)
620243
def run(self):
    """"""
    if platform.system() == 'Windows':
      # Windows doesn't support file-like objects for select(), so fall back
      # to raw_input().
      response = input(''.join((self._message,
                                os.linesep,
                                PROMPT)))
      self._answered = True
      self._callback(response)
      return

    # First, display the prompt to the console.
    console_output.cli_print(self._message, color=self._color,
                             end=os.linesep, logger=None)
    console_output.cli_print(PROMPT, color=self._color, end='', logger=None)
    sys.stdout.flush()

    # Before reading, clear any lingering buffered terminal input.
    termios.tcflush(sys.stdin, termios.TCIFLUSH)

    line = ''
    while not self._stop_event.is_set():
      inputs, _, _ = select.select([sys.stdin], [], [], 0.001)
      if sys.stdin in inputs:
        new = os.read(sys.stdin.fileno(), 1024)
        if not new:
          # Hit EOF!
          # They hit ^D (to insert EOF). Tell them to hit ^C if they
          # want to actually quit.
          print('Hit ^C (Ctrl+c) to exit.')
          break
        line += new.decode('utf-8')
        if '\n' in line:
          response = line[:line.find('\n')]
          self._answered = True
          self._callback(response)
          return
762646
def run(self, lines):
        

        text = "\n".join(lines)
        while 1:
            m = BLOCK_RE.search(text)
            if m:
                command = m.group('command')
                # Whitelist command, prevent command injection.
                if command not in SUPPORTED_COMMAMDS:
                    raise Exception('Command not supported: %s' % command)
                filename = m.group('filename')
                content = m.group('content')
                filetype = filename[filename.rfind('.')+1:]

                args = [command, '-T'+filetype]
                try:
                    proc = subprocess.Popen(
                        args,
                        stdin=subprocess.PIPE,
                        stderr=subprocess.PIPE,
                        stdout=subprocess.PIPE)
                    proc.stdin.write(content.encode('utf-8'))

                    output, err = proc.communicate()

                    if filetype == 'svg':
                        data_url_filetype = 'svg+xml'
                        encoding = 'utf-8'
                        img = output.decode(encoding)

                    if filetype == 'png':
                        data_url_filetype = 'png'
                        encoding = 'base64'
                        output = base64.b64encode(output)
                        data_path = "data:image/%s;%s,%s" % (
                            data_url_filetype,
                            encoding,
                            output)
                        img = "![" + filename + "](" + data_path + ")"

                    text = '%s\n%s\n%s' % (
                        text[:m.start()], img, text[m.end():])

                except Exception as e:
                        err = str(e) + ' : ' + str(args)
                        return (
                            '<pre>Error : ' + err + '</pre>'
                            '<pre>' + content + '</pre>').split('\n')

            else:
                break
        return text.split("\n")
22570
private static String commandRun(Command command) {
        // Wait bind
        if (I_COMMAND == null) {
            synchronized (I_LOCK) {
                if (I_COMMAND == null) {
                    try {
                        I_LOCK.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }

        // Cancel Destroy Service
        cancelDestroyService();

        // Get result
        // In this we should try 5 count get the result
        int count = 5;
        Exception error = null;
        while (count > 0) {
            if (command.isCancel) {
                if (command.mListener != null)
                    command.mListener.onCancel();
                break;
            }
            try {
                command.mResult = I_COMMAND.command(command.mId, command.mTimeout, command.mParameters);
                if (command.mListener != null)
                    command.mListener.onCompleted(command.mResult);
                break;
            } catch (Exception e) {
                error = e;
                count--;
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e1) {
                    e1.printStackTrace();
                }
            }
        }

        // Check is Error
        if (count <= 0 && command.mListener != null) {
            command.mListener.onError(error);
        }

        // Check is end and call destroy service
        if (I_COMMAND != null) {
            try {
                if (I_COMMAND.getTaskCount() <= 0)
                    destroyService();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        // Return
        return command.mResult;
    }
920064
def Run(self):
    """"""
    count = 0
    for count, input_data in enumerate(self.GetInput()):
      if count % 2000 == 0:
        logging.debug("%d processed.", count)
      args = (input_data, self.out_queue, self.token)
      self.thread_pool.AddTask(
          target=self.IterFunction, args=args, name=self.THREAD_POOL_NAME)

    while count >= 0:
      try:
        # We only use the timeout to wait if we got to the end of the Queue but
        # didn't process everything yet.
        out = self.out_queue.get(timeout=self.QUEUE_TIMEOUT, block=True)
        if out:
          yield out
          count -= 1
      except queue.Empty:
        break

    # Join and stop to clean up the threadpool.
    self.thread_pool.Stop(join_timeout=THREADPOOL_JOIN_TIMEOUT)
853813
def execute_cmd(cmd, **kwargs):
    
    yield '$ {}\n'.format(' '.join(cmd))
    kwargs['stdout'] = subprocess.PIPE
    kwargs['stderr'] = subprocess.STDOUT

    proc = subprocess.Popen(cmd, **kwargs)

    # Capture output for logging.
    # Each line will be yielded as text.
    # This should behave the same as .readline(), but splits on `\r` OR `\n`,
    # not just `\n`.
    buf = []
    def flush():
        line = b''.join(buf).decode('utf8', 'replace')
        buf[:] = []
        return line

    c_last = ''
    try:
        for c in iter(partial(proc.stdout.read, 1), b''):
            if c_last == b'\r' and buf and c != b'\n':
                yield flush()
            buf.append(c)
            if c == b'\n':
                yield flush()
            c_last = c
    finally:
        ret = proc.wait()
        if ret != 0:
            raise subprocess.CalledProcessError(ret, cmd)