Receive data from the terminal as a (``stdout``, ``stderr``) tuple. If
        any of those is ``None`` we can no longer communicate with the
        terminal's child process.
161109
def recv(self, maxsize=None):
        '''
        
        '''
        if maxsize is None:
            maxsize = 1024
        elif maxsize < 1:
            maxsize = 1
        return self._recv(maxsize)
316854
def get_cmd_output_from_stdin(stdint_content_binary: bytes,
                              *args, encoding: str = SYS_ENCODING) -> str:
    
    p = subprocess.Popen(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
    stdout, stderr = p.communicate(input=stdint_content_binary)
    return stdout.decode(encoding, errors='ignore')
508048
def send(self, data):
        
        assert isinstance(data, text_type)

        # When data is send back to the client, we should replace the line
        # endings. (We didn't allocate a real pseudo terminal, and the telnet
        # connection is raw, so we are responsible for inserting \r.)
        self.stdout.write(data.replace('\n', '\r\n'))
        self.stdout.flush()
741414
def stderr_handle(self):
        """"""
        if self.stderr_file is not None:
            # Needed to prevent any error that could appear.
            # See issue 6267
            try:
                handle = codecs.open(self.stderr_file, 'w', encoding='utf-8')
            except Exception:
                handle = None
        else:
            handle = None

        return handle
658210
def outReceived(self, data):
        

        if self.stdout:
            self.stdout.write(data.decode('ascii'))

        # minor hack: we can't try this in connectionMade because
        # that's when the process first starts up so Tor hasn't
        # opened any ports properly yet. So, we presume that after
        # its first output we're good-to-go. If this fails, we'll
        # reset and try again at the next output (see this class'
        # tor_connection_failed)
        txtorlog.msg(data)
        if not self.attempted_connect and self.connection_creator \
                and b'Opening Control listener' in data:
            self.attempted_connect = True
            # hmmm, we don't "do" anything with this Deferred?
            # (should it be connected to the when_connected
            # Deferreds?)
            d = self.connection_creator()
            d.addCallback(self._tor_connected)
            d.addErrback(self._tor_connection_failed)
354918
def handle_streams(stdout_stream, stderr_stream, &block)
        logger.debug "Monitoring stdout/stderr streams for output"
        streams = [stdout_stream, stderr_stream]
        until streams.empty?
          # Find which streams are ready for reading, timeout 0.1s
          selected, = select(streams, nil, nil, 0.1)

          # Try again if none were ready
          next if selected.nil? or selected.empty?

          selected.each do |stream|
            if stream.eof?
              logger.debug "Stream reached end-of-file"
              if @success.nil?
                logger.debug "Process hasn't finished, keeping stream"
              else
                logger.debug "Removing stream"
                streams.delete(stream)
              end
              next
            end

            while data = @reader.call(stream)
              data = ((@options[:mode] == :chars) ? data.chr : data)
              stream_name = (stream == stdout_stream) ? :stdout : :stderr
              output data, stream_name, &block unless block.nil?
              buffer data, stream_name unless @options[:no_buffer]
            end
          end
        end
      end
894151
def cmd(send, msg, _):
    
    try:
        answer = subprocess.check_output(['wtf', msg], stderr=subprocess.STDOUT)
        send(answer.decode().strip().replace('\n', ' or ').replace('fuck', 'fsck'))
    except subprocess.CalledProcessError as ex:
        send(ex.output.decode().rstrip().splitlines()[0])
782424
def subprocess_output(command, raise_on_empty_output):
    

    # Use tempfile, allowing a larger amount of memory. The subprocess.Popen
    # docs warn that the data read is buffered in memory. They suggest not to
    # use subprocess.PIPE if the data size is large or unlimited.
    with tempfile.TemporaryFile() as stdout_f, tempfile.TemporaryFile() as stderr_f:
        proc = subprocess.Popen(command, stdout=stdout_f, stderr=stderr_f)
        proc.wait()
        stderr_f.seek(0)
        err = stderr_f.read()
        stdout_f.seek(0)
        output = stdout_f.read()

    if not output and raise_on_empty_output:
        raise SubprocessOutputEmptyError("get_subprocess_output expected output but had none.")

    return output, err, proc.returncode
829639
def receive():
    
    header = _in_file.read(8)
    logging.getLogger(__name__).debug('Received command, header: [%s]' % header)
    if header is None or len(header) < 8:
        # Pipe EOF encountered
        logging.getLogger(__name__).debug('Pipe EOF encountered')
        return None, None
    length = int(header[2:])
    data = _in_file.read(length)
    command = CommandType(header[:2])
    data = data.decode('utf8')
    logging.getLogger(__name__).debug('Received command, data: [%s]' % data)
    return command, data
607963
def receive(self,arg_formats=None):
        

        # Read serial input until a command separator or empty character is
        # reached 
        msg = [[]]
        raw_msg = []
        escaped = False
        command_sep_found = False
        while True:

            tmp = self.board.read()
            raw_msg.append(tmp)

            if escaped:

                # Either drop the escape character or, if this wasn't really
                # an escape, keep previous escape character and new character
                if tmp in self._escaped_characters:
                    msg[-1].append(tmp)
                    escaped = False
                else:
                    msg[-1].append(self._byte_escape_sep)
                    msg[-1].append(tmp)
                    escaped = False
            else:

                # look for escape character
                if tmp == self._byte_escape_sep:
                    escaped = True

                # or field separator
                elif tmp == self._byte_field_sep:
                    msg.append([])

                # or command separator
                elif tmp == self._byte_command_sep:
                    command_sep_found = True
                    break

                # or any empty characater 
                elif tmp == b'':
                    break

                # okay, must be something
                else:
                    msg[-1].append(tmp)
  
        # No message received given timeouts
        if len(msg) == 1 and len(msg[0]) == 0:
            return None

        # Make sure the message terminated properly
        if not command_sep_found:
          
            # empty message (likely from line endings being included) 
            joined_raw = b''.join(raw_msg) 
            if joined_raw.strip() == b'':
                return  None
           
            err = "Incomplete message ({})".format(joined_raw.decode())
            raise EOFError(err)

        # Turn message into fields
        fields = [b''.join(m) for m in msg]

        # Get the command name.
        cmd = fields[0].strip().decode()
        try:
            cmd_name = self._int_to_cmd_name[int(cmd)]
        except (ValueError,IndexError):

            if self.give_warnings:
                cmd_name = "unknown"
                w = "Recieved unrecognized command ({}).".format(cmd)
                warnings.warn(w,Warning)
        
        # Figure out what formats to use for each argument.  
        arg_format_list = []
        if arg_formats != None:

            # The user specified formats
            arg_format_list = list(arg_formats)

        else:
            try:
                # See if class was initialized with a format for arguments to this
                # command
                arg_format_list = self._cmd_name_to_format[cmd_name]
            except KeyError:
                # if not, guess for all arguments
                arg_format_list = ["g" for i in range(len(fields[1:]))]

        # Deal with "*" format  
        arg_format_list = self._treat_star_format(arg_format_list,fields[1:])

        if len(fields[1:]) > 0:
            if len(arg_format_list) != len(fields[1:]):
                err = "Number of argument formats must match the number of recieved arguments."
                raise ValueError(err)

        received = []
        for i, f in enumerate(fields[1:]):
            received.append(self._recv_methods[arg_format_list[i]](f))
        
        # Record the time the message arrived
        message_time = time.time()

        return cmd_name, received, message_time
66294
def shell_out(cmd, stderr=STDOUT, cwd=None):
    """"""
    if cwd is None:
        from os import getcwd
        cwd = getcwd()  # TODO do I need to normalize this on Windows

    out = check_output(cmd, cwd=cwd, stderr=stderr, universal_newlines=True)
    return _clean_output(out)
148752
def err(*args):
    
    for value in args:
        sys.stderr.write(value)

    sys.stderr.write(os.linesep)
116868
def stderr():
    

    # We write all of the data to stderr with bytes, typically io.BytesIO. stderr in Python2
    # accepts bytes but Python3 does not. This is due to a type change on the attribute. To keep
    # this consistent, we leave Python2 the same and get the .buffer attribute on stderr in Python3
    byte_stderr = sys.stderr

    if sys.version_info.major > 2:
        byte_stderr = sys.stderr.buffer  # pylint: disable=no-member

    return byte_stderr
239985
def wrap_existing_process(self, pid, stdout_read_fd, stderr_read_fd, port=None):
        
        stdout_read_file = os.fdopen(stdout_read_fd, 'rb')
        stderr_read_file = os.fdopen(stderr_read_fd, 'rb')
        stdout_streams, stderr_streams = self._get_stdout_stderr_streams()
        self._stdout_tee = io_wrap.Tee(stdout_read_file, *stdout_streams)
        self._stderr_tee = io_wrap.Tee(stderr_read_file, *stderr_streams)

        self.proc = Process(pid)
        self._run.pid = pid
        logger.info("wrapping existing process %i" % pid)

        try:
            self.init_run()
        except LaunchError as e:
            logger.exception("catostrophic launch error")
            wandb.termerror(str(e))
            util.sentry_exc(e)
            self._socket.launch_error()
            return

        if io_wrap.SIGWINCH_HANDLER is not None:
            # SIGWINCH_HANDLER (maybe) gets set in self.init_run()
            io_wrap.SIGWINCH_HANDLER.add_fd(stdout_read_fd)
            io_wrap.SIGWINCH_HANDLER.add_fd(stderr_read_fd)

        # Signal the main process that we're all hooked up
        logger.info("informing user process we are ready to proceed")
        self._socket.ready()

        self._sync_etc(headless=True)
654299
def output_stderr(self, text):
        ""
        binary_stderr.write(b''.join([
            self._red,
            b't=%07d' % (time.time() - self._t0),
            self._reset,
            b' ',
            text,
        ]))
        binary_stderr.flush()
336532
def _read_stderr(self):
        ''''''
        try:
            while self._process.returncode is None:
                line = yield from self._process.stderr.readline()

                if not line:
                    break

                if self._stderr_callback:
                    yield from self._stderr_callback(line)

        except Exception:
            _logger.exception('Unhandled read stderr exception.')
            raise
1126712
def block(self):
        """"""
        if self._uses_subprocess:
            # consume stdout and stderr
            if self.blocking:
                try:
                    stdout, stderr = self.subprocess.communicate()
                    self.__out = stdout
                    self.__err = stderr
                except ValueError:
                    pass  # Don't read from finished subprocesses.
            else:
                self.subprocess.stdin.close()
                self.std_out.close()
                self.std_err.close()
                self.subprocess.wait()
        else:
            self.subprocess.sendeof()
            try:
                self.subprocess.wait()
            finally:
                if self.subprocess.proc.stdout:
                    self.subprocess.proc.stdout.close()