import time


def wait_for_operation(api, job_name):
  """Waiting for a long running operation by polling it."""
  while True:
    result = api.projects().regions().operations().get(name=job_name).execute()
    if result.get('done'):
      if result['metadata']['status']['state'] == 'DONE':
        return result
      else:
        raise Exception(result)
    time.sleep(5)