我认为创建一个新的流程可能是过大的。如果您使用的是Mac或基于Unix的系统,则应该能够使用signal.SIGALRM来强制使时间过长的功能超时。这将适用于闲置的网络功能或修改功能绝对无法解决的其他问题。
在这里编辑我的答案,尽管我不确定是否应该这样做:
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)
这基本上将计时器设置为5秒钟,然后尝试执行您的代码。如果在时间用完之前未能完成,则会发送SIGALRM,我们将其捕获并变成TimeoutException。这将迫使您进入except块,您的程序可以继续执行。