<p>I have python 2.7 code that for each 1 min run command on running pods with the following:</p>

<pre><code>file_exist = subprocess. \
    check_output("kubectl exec -it  " + pod_name + " -- ls " +
                 path + " &gt;&gt; /dev/null 2&gt;&amp;1 &amp;&amp; echo yes || echo no", shell=True).rstrip()
return file_exist == "yes"
</code></pre>

<p>The problem I face with is <code>kubectl exec</code> command sometimes hang, How can I add timeout to  kubectl command to prevent my code to hang on  <code>kubectl exec</code> command?</p>

<p>Use timeout parameter In <code>check_output()</code></p>

<pre><code>file_exist = subprocess. \
    check_output("kubectl exec -it  " + pod_name + " -- ls " +
                 path + " &gt;&gt; /dev/null 2&gt;&amp;1 &amp;&amp; echo yes || echo no", shell=True,timeout=300).rstrip()
return file_exist == "yes"
</code></pre>

<p><a href="https://docs.python.org/3/library/subprocess.html#subprocess.check_output" rel="nofollow noreferrer">https://docs.python.org/3/library/subprocess.html#subprocess.check_output</a></p>

<p>for <code>kubectl exec</code> timeout you can use <code>--request-timeout=30s</code> </p>
