import time


def exec_remote_cmd(client, cmd, t_sleep=5, verbose=False):
    """A wrapper function around paramiko.client.exec_command that helps with
    error handling and returns only once the command has been completed.

    Parameters
    ----------
    client : paramiko ssh client
        the client to use
    cmd : str
        the command to execute
    t_sleep : float, optional
        the amount of time to wait between querying if a job is complete
    verbose : str, optional
        print information about the command
    """
    if verbose:
        print("Remotely executing '{0}'".format(cmd))
    stdin, stdout, stderr = client.exec_command(cmd)
    while not stdout.channel.exit_status_ready():
        if verbose:
            print('Command not complete, checking again in {0} seconds.'.format(
                    t_sleep))
        time.sleep(t_sleep)
    if stdout.channel.recv_exit_status() != 0:
        raise IOError('Error with command {0}: {1}'.format(
                cmd, " ".join(stderr)))
    return stdin, stdout, stderr