<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>

Joe J
<p>May be you can try this way and handle exceptions based your requirement</p>
<pre><code>    def delete_deployment():
        &quot;&quot;&quot; Delete deployment &quot;&quot;&quot;
        while True:
            try:
                deployment = api_client.delete_namespaced_deployment(
                    name=&quot;deployment_name&quot;,
                    namespace=&quot;deployment_namespace&quot;,
                  body=client.V1DeleteOptions(propagation_policy=&quot;Foreground&quot;, grace_period_seconds=5),
                    )
            except ApiException:
                break
        print(&quot;Deployment 'deployment_name' has been deleted.&quot;)
</code></pre>
