擅长:python、mysql、java
<p>我一直用2.7来做超时的一个简单方法是利用<code>subprocess.poll()</code>和<code>time.sleep()</code>一起延迟。下面是一个非常基本的例子:</p>
<pre><code>import subprocess
import time
x = #some amount of seconds
delay = 1.0
timeout = int(x / delay)
args = #a string or array of arguments
task = subprocess.Popen(args)
#while the process is still executing and we haven't timed-out yet
while task.poll() is None and timeout > 0:
#do other things too if necessary e.g. print, check resources, etc.
time.sleep(delay)
timeout -= delay
</code></pre>
<p>如果设置了<code>x = 600</code>,则超时时间将为10分钟。而<code>task.poll()</code>将查询进程是否已终止。<code>time.sleep(delay)</code>在这种情况下将睡眠1秒,然后将超时时间减少1秒。你可以随心所欲地玩这个角色,但基本概念始终是一样的。</p>
<p>希望这有帮助!</p>
<p><code>subprocess.poll()</code><a href="https://docs.python.org/2/library/subprocess.html#popen-objects" rel="noreferrer">https://docs.python.org/2/library/subprocess.html#popen-objects</a></p>