您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

一定时间后中断功能

一定时间后中断功能

我认为创建一个新的流程可能是过大的。如果您使用的是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块,您的程序可以继续执行。

编辑:哎呀,TimeoutException一个类,而不是一个函数。谢谢,阿巴纳特!

其他 2022/1/1 18:33:36 有420人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶