<p>I'm looking to use the Kubernetes python client to delete a deployment, but then block and wait until all of the associated pods are deleted as well. A lot of the examples I'm finding recommend using the watch function something like follows.</p>
<pre><code>try:
    # try to delete if exists
    AppsV1Api(api_client).delete_namespaced_deployment(namespace=&quot;default&quot;, name=&quot;mypod&quot;)
except Exception:
    # handle exception

# wait for all pods associated with deployment to be deleted. 
for e in w.stream(
    v1.list_namespaced_pod, namespace=&quot;default&quot;,
    label_selector='mylabel=my-value&quot;,
    timeout_seconds=300):

    pod_name = e['object'].metadata.name
    print(&quot;pod_name&quot;, pod_name)
    if e['type'] == 'DELETED':
        w.stop()
        break
</code></pre>
<p>However, I see two problems with this.</p>
<ol>
<li>If the pod is already gone (or if some other process deletes all pods before execution reaches the watch stream), then the watch will find no events and the for loop will get stuck until the timeout expires. Watch does not seem to generate activity if there are no events.</li>
<li>Upon seeing events in the event stream for the pod activity, how do know all the pods got deleted? Seems fragile to count them.</li>
</ol>
<p>I'm basically looking to replace the <code>kubectl delete --wait</code> functionality with a python script.</p>
<p>Thanks for any insights into this.</p>

<pre class="lang-py prettyprint-override"><code>import json

def delete_pod(pod_name):
    return v1.delete_namespaced_pod(name=pod_name, namespace=&quot;default&quot;)


def delete_pod_if_exists(pod_name):
    def run():
        delete_pod(pod_name)

    while True:
        try:
            run()
        except ApiException as e:
            has_deleted = json.loads(e.body)['code'] == 404
            if has_deleted:
                return

</code></pre>
