Reads and blocks until the socket closes

        Used for the "shell" command, where STDOUT and STDERR
        are just redirected to the terminal with no length
324790
def receive_until_end(self, timeout=None):
        
        if self.receive_fixed_length(4) != "OKAY":
            raise SocketError("Socket communication failed: "
                              "the server did not return a valid response")

        # The time at which the receive starts
        start_time = time.clock()

        output = ""

        while True:
            if timeout is not None:
                self.socket.settimeout(timeout - (time.clock() - start_time))
            
            chunk = ''
            try:
                chunk = self.socket.recv(4096).decode("ascii")
            except socket.timeout:
                return output            

            if not chunk:
                return output

            output += chunk
723127
def wait(self) -> None:
        """"""
        if self._out_thread.is_alive():
            self._out_thread.join()
        if self._err_thread.is_alive():
            self._err_thread.join()

        # Handle case where the process ended before the last read could be done.
        # This will return None for the streams that weren't pipes.
        out, err = self._proc.communicate()

        if out:
            self._write_bytes(self._stdout, out)
        if err:
            self._write_bytes(self._stderr, err)
258895
def channel(self):
        
        # start shell, non-blocking channel
        chan = self.cli.invoke_shell(width=360, height=80)
        chan.setblocking(0)
        # set channel timeout
        chan.settimeout(10)
        # now waiting for shell prompt ('username@')
        result = ""
        count = 0
        while count < 10:
            try:
                recv_part = chan.recv(16384).decode()
                result += recv_part
            except socket.timeout:
                # socket.timeout here means 'no more data'
                pass

            if result.find('%s@' % self.username) != -1:
                return chan
            time.sleep(1)
            count += 1
        # failed to get shell prompt on channel :-(
        raise StitchesConnectionException("Failed to get shell prompt")
491020
def exec_command(self, cmd, tmp_path, sudo_user, sudoable=False, executable='/bin/sh'):
        '''  '''

        bufsize = 4096
        try:
            chan = self.ssh.get_transport().open_session()
        except Exception, e:
            msg = "Failed to open session"
            if len(str(e)) > 0:
                msg += ": %s" % str(e)
            raise errors.AnsibleConnectionFailed(msg)
        chan.get_pty()

        if not self.runner.sudo or not sudoable:
            if executable:
                quoted_command = executable + ' -c ' + pipes.quote(cmd)
            else:
                quoted_command = cmd
            vvv("EXEC %s" % quoted_command, host=self.host)
            chan.exec_command(quoted_command)
        else:
            shcmd, prompt = utils.make_sudo_cmd(sudo_user, executable, cmd)
            vvv("EXEC %s" % shcmd, host=self.host)
            sudo_output = ''
            try:
                chan.exec_command(shcmd)
                if self.runner.sudo_pass:
                    while not sudo_output.endswith(prompt):
                        chunk = chan.recv(bufsize)
                        if not chunk:
                            if 'unknown user' in sudo_output:
                                raise errors.AnsibleError(
                                    'user %s does not exist' % sudo_user)
                            else:
                                raise errors.AnsibleError('ssh connection ' +
                                    'closed waiting for password prompt')
                        sudo_output += chunk
                    chan.sendall(self.runner.sudo_pass + '\n')
            except socket.timeout:
                raise errors.AnsibleError('ssh timed out waiting for sudo.\n' + sudo_output)

        stdout = ''.join(chan.makefile('rb', bufsize))
        stderr = ''.join(chan.makefile_stderr('rb', bufsize))
        return (chan.recv_exit_status(), '', stdout, stderr)
308082
def read_line
      begin
        with_timeout { @socket.gets.to_s.strip }
      rescue Errno::ETIMEDOUT, Errno::ECONNREFUSED, Errno::ECONNRESET, EOFError => ex
        raise Munin::ConnectionError, ex.message
      rescue Timeout::Error
        raise Munin::ConnectionError, "Timed out reading from #{@host}."
      end
    end
68228
def silence(self):
        

        sys.stdout = open(os.devnull, 'w')
        sys.stderr = open(os.devnull, 'w')
458383
def launch(program, sock, stderr=True, cwd=None, env=None):
        
        if stderr is True:
            err = sock # redirect to socket
        elif stderr is False:
            err = open(os.devnull, 'wb') # hide
        elif stderr is None:
            err = None # redirect to console

        p = subprocess.Popen(program,
                shell=type(program) not in (list, tuple),
                stdin=sock, stdout=sock, stderr=err,
                cwd=cwd, env=env,
                close_fds=True)

        sock.close()
        return p
263119
def _read(self, n):
        
        while len(self._read_buffer) < n:
            s = self.sock.recv(65536)
            if not s:
                raise IOError('Socket closed')
            self._read_buffer += s

        result = self._read_buffer[:n]
        self._read_buffer = self._read_buffer[n:]

        return result
111113
def popenCatch(command, stdinString=None):
    
    logger.debug("Running the command: %s" % command)
    if stdinString != None:
        process = subprocess.Popen(command, shell=True,
                                   stdin=subprocess.PIPE, stdout=subprocess.PIPE, bufsize=-1)
        output, nothing = process.communicate(stdinString)
    else:
        process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=sys.stderr, bufsize=-1)
        output, nothing = process.communicate() #process.stdout.read().strip()
    sts = process.wait()
    if sts != 0:
        raise RuntimeError("Command: %s with stdin string '%s' exited with non-zero status %i" % (command, stdinString, sts))
    return output
203984
def _close_socket(self):
        
        try:
            self.socket.shutdown(socket.SHUT_RDWR)
        except (OSError, socket.error):
            pass
        self.socket.close()
28958
def get_simple_output(self, stderr=STDOUT):
        
        args = shlex.split(self.cmd)
        proc = Popen(args, stdout=PIPE, stderr=stderr)
        return proc.communicate()[0].decode("utf8")
1136258
def run_command(cmd, env=None, max_timeout=None):
    
    arglist = cmd.split()

    output = os.tmpfile()
    try:
        pipe = Popen(arglist, stdout=output, stderr=STDOUT, env=env)
    except Exception as errmsg:
        return 1, errmsg

    # Wait only max_timeout seconds.
    if max_timeout:
        start = time.time()
        while pipe.poll() is None:
            time.sleep(0.1)
            if time.time() - start > max_timeout:
                os.kill(pipe.pid, signal.SIGINT)
                pipe.wait()
                return 1, "Time exceeded"

    pipe.wait()
    output.seek(0)
    return pipe.returncode, output.read()
1318416
def _read_until(infile=sys.stdin, maxchars=20, end=RS):
    '''   '''
    chars = []
    read = infile.read
    if not isinstance(end, tuple):
        end = (end,)

    # count down, stopping at 0
    while maxchars:
        char = read(1)
        if char in end:
            break
        chars.append(char)
        maxchars -= 1

    return ''.join(chars)
363354
def run_process(cmd, stdin=None, iterate_stdin=True, output_chunk_size=1024, shell=True, to_close=None, cwd=None):
    
    try:
        p = subprocess.Popen(cmd, shell=shell, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=cwd)

        if stdin:
            if iterate_stdin:
                stdin_iter = iter(stdin)
                stdin_buffer = ''
                stdin_available = True
            else:
                stdin_buffer = stdin
                stdin_available = False

        write_set = []
        read_set = []
        output_buffer = ''

        if p.stdin and stdin:
            write_set.append(p.stdin)
        if p.stdout:
            read_set.append(p.stdout)
        if p.stderr:
            read_set.append(p.stderr)

        while read_set or write_set:
            try:
                rlist, wlist, xlist = select.select(read_set, write_set, [])
            except select.error as e:
                if e.args[0] == errno.EINTR:
                    continue
                raise

            if p.stdin in wlist:
                while len(stdin_buffer) < _PIPE_BUF and stdin_available:
                    try:
                        stdin_buffer += stdin_iter.next()
                    except StopIteration:
                        stdin_available = False
                chunk = stdin_buffer[:_PIPE_BUF]
                bytes_written = os.write(p.stdin.fileno(), chunk)
                stdin_buffer = stdin_buffer[bytes_written:]

                if not (stdin_buffer or stdin_available):
                    p.stdin.close()
                    write_set.remove(p.stdin)

            if p.stdout in rlist:
                data = os.read(p.stdout.fileno(), output_chunk_size)
                if data == '':
                    p.stdout.close()
                    read_set.remove(p.stdout)
                if data:
                    output_buffer += data
                    yield data

            if p.stderr in rlist:
                data = os.read(p.stderr.fileno(), output_chunk_size)
                if data == '':
                    p.stderr.close()
                    read_set.remove(p.stderr)
                if data:
                    output_buffer += data

            if len(output_buffer) > output_chunk_size:
                output_buffer = output_buffer[-output_chunk_size:]

        return_code = p.poll()
        if return_code:
            e = subprocess.CalledProcessError(return_code, cmd)
            e.output = output_buffer
            raise e
    finally:
        if to_close:
            to_close.close()
502976
def stderr(self):
        
        streams = self._payload.get('streams', None)
        return streams[1] if streams is not None and len(streams) >= 2 else ''
277538
def handle_stderr(stderr_pipe):
    
    stderr_output = stderr_pipe.read()

    if len(stderr_output) > 0:
        click.secho("\n__ Error Output {0}".format('_'*62), fg='white',
                    bold=True)
        click.echo(stderr_output)

    return True
854686
def run
      Open3.popen3(@cmd) do |stdin, stdout, stderr, wait_thr|
        stdin.close # leaving stdin open when we don't use it can cause some commands to hang
        stdout_buffer=""
        stderr_buffer=""

        streams = [stdout, stderr]
        while streams.length > 0
          IO.select(streams).flatten.compact.each do |io|
            if io.eof?
              streams.delete io
              next
            end

            stdout_buffer += io.readpartial(1) if io.fileno == stdout.fileno
            stderr_buffer += io.readpartial(1) if io.fileno == stderr.fileno
          end

          # Remove and process all the finished lines from the output buffer
          stdout_buffer.sub!(/.*\n/m) do
            @out += $&
            if @show_out
              $&.strip.split("\n").each do |line|
                line = @tag.style("cmd") + " " + line if @tag
                log(@out_level, line)
              end
            end

            ''
          end

          # Remove and process all the finished lines from the error buffer
          stderr_buffer.sub!(/.*\n/m) do
            @err += $&
            if @show_err
              $&.strip.split("\n").each do |line|
                line = @tag.style("cmd") + " " + line if @tag
                log(:err, line)
              end
            end

            ''
          end
        end

        @status = wait_thr.value
      end

      if (@expect.is_a?(Array) && !@expect.include?(@status.exitstatus)) ||
         (@expect.is_a?(Integer) && @status.exitstatus != @expect)
        unless @show_err
          err_lines = @err.split "\n"
          err_lines.each do |l|
            l = @tag.style("cmd") + " " + l if @tag
            log(:err, l.chomp)
          end
        end
        raise "'#{@cmd}' failed!" if @raise
      end
    end