一定时间后中断功能 [英] Break the function after certain time

查看:64
本文介绍了一定时间后中断功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Python 中,以玩具为例:

In Python, for a toy example:

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

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

I want to continue the for loop if function A takes more than five seconds by skipping it so I won't get stuck or waste time.

通过一些搜索,我意识到子进程或线程可能会有所帮助,但我不知道如何在这里实现它.

By doing some search, I realized a subprocess or thread may help, but I have no idea how to implement it here.

推荐答案

我认为创建一个新进程可能有点矫枉过正.如果您使用的是 Mac 或基于 Unix 的系统,您应该能够使用 signal.SIGALRM 来强制超时耗时过长的函数.这将适用于因网络或其他问题而空闲的函数,而这些问题您绝对无法通过修改函数来处理.我有一个在这个答案中使用它的例子:

I think creating a new process may be overkill. If you're on Mac or a Unix-based system, you should be able to use signal.SIGALRM to forcibly time out functions that take too long. This will work on functions that are idling for network or other issues that you absolutely can't handle by modifying your function. I have an example of using it in this answer:

SSH 在短时间内超时的选项?ClientAlive &ConnectTimeout 似乎没有做我需要他们做的

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

Editing my answer in here, though I'm not sure I'm supposed to do that:

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 块,在那里您的程序可以继续.

This basically sets a timer for 5 seconds, then tries to execute your code. If it fails to complete before time runs out, a SIGALRM is sent, which we catch and turn into a TimeoutException. That forces you to the except block, where your program can continue.

这篇关于一定时间后中断功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆