import time


def wait_for_job(api, project, region, job_id):
  """Waiting for a job by polling it."""
  while True:
    result = api.projects().regions().jobs().get(
        projectId=project,
        region=region,
        jobId=job_id).execute()

    if result['status']['state'] == 'ERROR':
      raise Exception(result['status']['details'])
    elif result['status']['state'] == 'DONE':
      return result
    time.sleep(5)