Take a Python 2.x binary file and return an IO Stream.
510571
def make_stream(
    name,  # type: Text
    bin_file,  # type: RawIOBase
    mode="r",  # type: Text
    buffering=-1,  # type: int
    encoding=None,  # type: Optional[Text]
    errors=None,  # type: Optional[Text]
    newline="",  # type: Optional[Text]
    line_buffering=False,  # type: bool
    **kwargs  # type: Any
):
    # type: (...) -> IO
    
    reading = "r" in mode
    writing = "w" in mode
    appending = "a" in mode
    binary = "b" in mode
    if "+" in mode:
        reading = True
        writing = True

    encoding = None if binary else (encoding or "utf-8")

    io_object = RawWrapper(bin_file, mode=mode, name=name)  # type: io.IOBase
    if buffering >= 0:
        if reading and writing:
            io_object = io.BufferedRandom(
                typing.cast(io.RawIOBase, io_object),
                buffering or io.DEFAULT_BUFFER_SIZE,
            )
        elif reading:
            io_object = io.BufferedReader(
                typing.cast(io.RawIOBase, io_object),
                buffering or io.DEFAULT_BUFFER_SIZE,
            )
        elif writing or appending:
            io_object = io.BufferedWriter(
                typing.cast(io.RawIOBase, io_object),
                buffering or io.DEFAULT_BUFFER_SIZE,
            )

    if not binary:
        io_object = io.TextIOWrapper(
            io_object,
            encoding=encoding,
            errors=errors,
            newline=newline,
            line_buffering=line_buffering,
        )

    return io_object
870940
def read_blob(arg):
    """"""
    result = None
    if arg == '@-':
        result = sys.stdin.read()
    elif any(arg.startswith('@{}://'.format(x)) for x in {'http', 'https', 'ftp', 'file'}):
        if not requests:
            raise error.UserError("You must 'pip install requests' to support @URL arguments.")
        try:
            response = requests.get(arg[1:])
            response.raise_for_status()
            result = response.content
        except requests.RequestException as exc:
            raise error.UserError(str(exc))
    else:
        with open(os.path.expanduser(arg[1:]), 'rb') as handle:
            result = handle.read()

    return result
263486
def get_file_contents(path, binary=False):
    
    # if this isn't a text file, we should raise an IOError
    f = open(path, 'r')
    file_contents = f.read()
    f.close()
    if not binary and file_contents.find('\000') >= 0:
        raise IOError('Expected text file, got binary file')
    return file_contents
1006053
def get_file(self, job_binary_id):
        """"""
        resp = self.api.get('/job-binaries/%s/data' % job_binary_id)

        if resp.status_code != 200:
            self._raise_api_exception(resp)
        return resp.content
1355680
def as_binary(self, content, encoding='utf8'):
        ''''''
        if hasattr(content, 'read'):
            return content.read()
        elif isinstance(content, six.text_type):
            return content.encode(encoding)
        else:
            return content
491604
def _handle_io(self, args, file, result, passphrase=False, binary=False):
        """"""
        p = self._open_subprocess(args, passphrase)
        if not binary:
            stdin = codecs.getwriter(self._encoding)(p.stdin)
        else:
            stdin = p.stdin
        if passphrase:
            _util._write_passphrase(stdin, passphrase, self._encoding)
        writer = _util._threaded_copy_data(file, stdin)
        self._collect_output(p, result, writer, stdin)
        return result
89292
def as_bin(self, as_spendable=False):
        """"""
        f = io.BytesIO()
        self.stream(f, as_spendable=as_spendable)
        return f.getvalue()
335960
def i2m(self, pkt, x):
        """"""
        if x is None:
            x = 0
        elif isinstance(x, str):
            return bytes_encode(x)
        return x
424434
def binary(self, length=(1 * 1024 * 1024)):
        
        blob = [self.generator.random.randrange(256) for _ in range(length)]
        return bytes(blob) if sys.version_info[0] >= 3 else bytearray(blob)
1038368
def extract(binary):
    '''
    
    '''
    if len(binary) <= 8:
        raise Exception("Binary pyc must be greater than 8 bytes (got %i)" % len(binary))
    
    magic = binary[:4]
    MAGIC = get_magic()
    
    if magic != MAGIC:
        raise Exception("Python version mismatch (%r != %r) Is this a pyc file?" % (magic, MAGIC))
    
    modtime = time.asctime(time.localtime(struct.unpack('i', binary[4:8])[0]))

    code = marshal.loads(binary[8:])
    
    return modtime, code
761263
def download
      return io if io.is_a?(Tempfile)

      Tempfile.new(id, binmode: true).tap do |tempfile|
        IO.copy_stream(io, tempfile)
        tempfile.rewind
        tempfile.fsync
      end
    end
253060
def to_bytes(s, encoding="utf8"):
    """"""
    if PY_VERSION == 2:
        b = bytes(s)
    elif PY_VERSION == 3:
        b = bytes(s, encoding)
    else:
        raise ValueError("Is Python 4 out already?")

    return b
827530
def to_file(file, key = nil, jwe = nil)
      return File.binwrite(file, to_binary(key, jwe))
    end
1245359
def binary_stdout():
    

    # First there is a Python3 issue.
    try:
        stdout = sys.stdout.buffer
    except AttributeError:
        # Probably Python 2, where bytes are strings.
        stdout = sys.stdout

    # On Windows the C runtime file orientation needs changing.
    if sys.platform == "win32":
        import msvcrt
        import os
        msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)

    return stdout
1339190
def openStream(self, source):
        
        # Already a file object
        if hasattr(source, 'read'):
            stream = source
        else:
            stream = BytesIO(source)

        try:
            stream.seek(stream.tell())
        except:  # pylint:disable=bare-except
            stream = BufferedStream(stream)

        return stream
1351447
def xread(file, length):
    ""
    data = file.read(length)
    if len(data) != length:
        raise EOFError
    return data
508302
def from_bytes(cls, bitstream):
        '''
        
        '''
        from pylisp.packet.lisp.control import type_registry

        # Convert to ConstBitStream (if not already provided)
        if not isinstance(bitstream, ConstBitStream):
            if isinstance(bitstream, Bits):
                bitstream = ConstBitStream(auto=bitstream)
            else:
                bitstream = ConstBitStream(bytes=bitstream)

        # Peek at the bitstream to see which type it is
        type_nr = bitstream.peek('uint:4')

        # Look for the right class
        type_class = type_registry.get_type_class(type_nr)
        if not type_class:
            raise ValueError("Can't handle message type {0}".format(type_nr))

        # Let the specific class handle it from now on
        return type_class.from_bytes(bitstream)