import select


def sock_recv_raw(sock, count, timeout=None):
    """Tries to receive an exact number of bytes from a socket.

    Args:
        sock: socket object
        count (int): number of bytes to be received
        timeout (float): maximum time to wait, in s (None for infinite timeout)
    Returns:
        bytes: Received raw data
    """
    assert count
    buf = b""
    while len(buf) < count:
        if timeout:
            ready = select.select([sock], [], [], timeout)
        else:
            ready = select.select([sock], [], [])
        assert ready[0], "select operation ran into timeout"
        r = sock.recv(count - len(buf))
        assert len(r), "received 0 bytes (e.g. because the socket was closed)"
        buf += r
    return buf