Write Python2 and Python3 compatible byte stream.
774713
def write_bytes(out_data, encoding="ascii"):
    """"""
    if sys.version_info[0] >= 3:
        if isinstance(out_data, type("")):
            if encoding == "utf-8":
                return out_data.encode("utf-8")
            else:
                return out_data.encode("ascii", "ignore")
        elif isinstance(out_data, type(b"")):
            return out_data
    else:
        if isinstance(out_data, type("")):
            if encoding == "utf-8":
                return out_data.encode("utf-8")
            else:
                return out_data.encode("ascii", "ignore")
        elif isinstance(out_data, type(str(""))):
            return out_data
    msg = "Invalid value for out_data neither unicode nor byte string: {}".format(
        out_data
    )
    raise ValueError(msg)
52111
def _write_with_fallback(s, write, fileobj):
    

    if IPythonIOStream is not None and isinstance(fileobj, IPythonIOStream):
        # If the output stream is an IPython.utils.io.IOStream object that's
        # not going to be very helpful to us since it doesn't raise any
        # exceptions when an error occurs writing to its underlying stream.
        # There's no advantage to us using IOStream.write directly though;
        # instead just write directly to its underlying stream:
        write = fileobj.stream.write

    try:
        write(s)
        return write
    except UnicodeEncodeError:
        # Let's try the next approach...
        pass

    enc = locale.getpreferredencoding()
    try:
        Writer = codecs.getwriter(enc)
    except LookupError:
        Writer = codecs.getwriter(_DEFAULT_ENCODING)

    f = Writer(fileobj)
    write = f.write

    try:
        write(s)
        return write
    except UnicodeEncodeError:
        Writer = codecs.getwriter('latin-1')
        f = Writer(fileobj)
        write = f.write

    # If this doesn't work let the exception bubble up; I'm out of ideas
    write(s)
    return write
900552
def dump(self, msg, fn_):
        '''
        
        '''
        if six.PY2:
            fn_.write(self.dumps(msg))
        else:
            # When using Python 3, write files in such a way
            # that the 'bytes' and 'str' types are distinguishable
            # by using "use_bin_type=True".
            fn_.write(self.dumps(msg, use_bin_type=True))
        fn_.close()
850415
def _py2_and_3_joiner(sep, joinable):
    
    if ISPY3:
        sep = bytes(sep, DEFAULT_ENCODING)
    joined = sep.join(joinable)
    return joined.decode(DEFAULT_ENCODING) if ISPY3 else joined
89247
def _write_bin(self, data, stream, byte_order):
        '''
        

        '''
        (len_t, val_t) = self.list_dtype(byte_order)

        data = _np.asarray(data, dtype=val_t).ravel()

        _write_array(stream, _np.array(data.size, dtype=len_t))
        _write_array(stream, data)
998784
def write (self, s):
        
        if isinstance(s, bytes):
            s = self._decode(s)
        for c in s:
            self.process(c)
25216
def _winpath2bytes_py3(text, codec):
    """"""

    # merge surrogate codepoints
    if _normalize_codec(codec).startswith("utf-16"):
        # fast path, utf-16 merges anyway
        return text.encode(codec, _surrogatepass)
    return _decode_surrogatepass(
        text.encode("utf-16-le", _surrogatepass),
        "utf-16-le").encode(codec, _surrogatepass)
353261
def write(u, path):
    
    print("writing to: %s" % path)
    # This function implementation was chosen to be compatible across Python 2/3.
    f = open(path, "wb")
    try:
        b = u.encode(FILE_ENCODING)
        f.write(b)
    finally:
        f.close()
1241328
def write(self, s):
        
        should_write_s = os.getenv('PROGRESSIVE_NOWRITE') != "True"
        if should_write_s:
            self._stream.write(s)
241805
def write(self, buf):
        """"""
        if not isinstance(buf, six.binary_type):
            raise TypeError('buf: must be a bytes instance')
        # Be careful not to write zero-length chunks as they indicate the end of a body.
        if len(buf) == 0:
            return
        if self._content_length and self._bytes_written > self._content_length:
            raise RuntimeError('wrote too many bytes ({} > {})'
                                    .format(self._bytes_written, self._content_length))
        self._bytes_written += len(buf)
        if self._chunked:
            buf = create_chunk(buf)
        self._protocol.writer.write(buf)
256551
def write_byte(self, value):
        
        if isinstance(value, bytes):
            self.stream.write(value)
        elif isinstance(value, str):
            self.stream.write(value.encode('utf-8'))
        elif isinstance(value, int):
            self.stream.write(bytes([value]))
1107240
def binary_stream(stream):
    
    try:
        import os
        if os.name == 'nt':
            fileno = getattr(stream, 'fileno', None)
            if fileno:
                no = fileno()
                if no >= 0:     # -1 means we're working as subprocess
                    import msvcrt
                    msvcrt.setmode(no, os.O_BINARY)
    except ImportError:
        pass
    return stream
973564
def _to_bytes(self, data):
        
        # TODO: On Python 3, move this `if` line to the `except` branch
        # as the common case will indeed no longer be bytes.
        if not isinstance(data, bytes):
            try:
                return data.encode('utf-8')
            except Exception:
                return None

        return data
869742
def _wrap_stream(stream):
        
        if hasattr(stream, "buffer"):
            return io.TextIOWrapper(stream.buffer, encoding="utf-8")
        elif hasattr(stream, "readable"):
            return io.TextIOWrapper(stream, encoding="utf-8")
        # Python 2.x stdin and stdout are just files
        else:
            return io.open(stream.fileno(), mode=stream.mode, encoding="utf-8")
108000
def write_bytes(self, data):
        
        if not isinstance(data, six.binary_type):
            raise TypeError(
                'data must be %s, not %s' %
                (six.binary_type.__class__.__name__, data.__class__.__name__))
        with self.open(mode='wb') as f:
            return f.write(data)
707270
def write(self, chunk):
        """"""
        if self.chunked_write and chunk:
            buf = [hex(len(chunk))[2:], CRLF, chunk, CRLF]
            self.conn.wfile.sendall("".join(buf))
        else:
            self.conn.wfile.sendall(chunk)
906808
def write(self, s):
        
        if not self.isalive():
            raise EOFError('Pty is closed')
        if PY2:
            s = _unicode(s)

        success, nbytes = self.pty.write(s)
        if not success:
            raise IOError('Write failed')
        return nbytes