一定时间后中断功能

用户名

在python中,一个玩具示例:

for x in range(0, 3):
    # call function A(x)

如果函数A通过跳过它花费了5秒以上的时间,我想继续for循环,这样我就不会卡住或浪费时间。

通过进行一些搜索,我意识到子进程或线程可能会有所帮助,但是我不知道如何在此处实现。任何帮助都会很棒。谢谢

声音防御

我认为创建一个新的流程可能是过大的。如果您使用的是Mac或基于Unix的系统,则应该能够使用signal.SIGALRM来强制使时间过长的功能超时。这将适用于闲置的网络功能或修改功能绝对无法解决的其他问题。我有一个在此答案中使用它的示例:

https://stackoverflow.com/a/24921763/3803152

在这里编辑我的答案,尽管我不确定是否应该这样做:

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是一个类,而不是一个函数。谢谢,阿巴纳特!

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章