<p>我认为创建一个新的流程可能有些过分。如果您使用的是Mac或基于Unix的系统,则应该能够使用signal.SIGALRM强制超时耗时过长的函数。这将适用于因网络或其他问题而处于空闲状态的函数,这些问题您完全无法通过修改函数来处理。我有一个在这个答案中使用它的例子:</p>
<p><em><a href="https://stackoverflow.com/questions/24921527/option-for-ssh-to-timeout-after-a-short-time-clientalive-connecttimeout-dont/24921763#24921763">Option for SSH to timeout after a short time? ClientAlive & ConnectTimeout don't seem to do what I need them to do</a></em></p>
<p>在这里编辑我的答案,虽然我不确定我应该这样做:</p>
<pre><code>import signal
class TimeoutException(Exception): # Custom exception class
pass
def timeout_handler(signum, frame): # Custom signal handler
raise TimeoutException
# Change the behavior of SIGALRM
signal.signal(signal.SIGALRM, timeout_handler)
for i in range(3):
# Start the timer. Once 5 seconds are over, a SIGALRM signal is sent.
signal.alarm(5)
# This try/except loop ensures that
# you'll catch TimeoutException when it's sent.
try:
A(i) # Whatever your function that might hang
except TimeoutException:
continue # continue the for loop if function A takes more than 5 second
else:
# Reset the alarm
signal.alarm(0)
</code></pre>
<p>这基本上会设置一个5秒的计时器,然后尝试执行代码。如果未能在时间结束前完成,将发送一个SIGALRM,我们将捕获它并将其转换为TimeoutException。这将迫使您转到except块,在该块中您的程序可以继续</p>