函数执行超时捕获-并主动响应异常

该代码定义了一个Python装饰器`timeout`,用于监控函数执行是否超时。如果函数在指定秒数内未完成,将抛出`TimeoutError`异常。示例中,`long_running_function`是一个模拟长时间运行的函数,它会被`timeout`装饰器包装,若超过3秒未执行完,则引发超时错误。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#!/usr/bin/env python3
# -*- coding:utf-8 -*-

"""
@Author : LingXiaoShuai
@File   : 超时监测
@Time   : 2023-05-08 09:44
@Desc   : 
"""
import time
import threading

class TimeoutError(Exception):
    pass

def timeout(seconds=10, error_message="Function execution timed out"):
    def decorator(func):
        def wrapper(*args, **kwargs):
            result = [None]
            error = [None]
            def target():
                try:
                    result[0] = func(*args, **kwargs)
                except Exception as e:
                    error[0] = e
            thread = threading.Thread(target=target)
            thread.start()
            thread.join(seconds)
            if thread.is_alive():
                error[0] = TimeoutError(error_message)
                thread.join()
            if error[0] is not None:
                raise error[0]
            return result[0]
        return wrapper
    return decorator



@timeout(seconds=3, error_message="Function execution timed out")
def long_running_function(arg1, arg2):
    # some long-running operation here
    print(arg1, arg2)
    time.sleep(5)




if __name__ == '__main__':
    try:
        result = long_running_function('xx', 'xxx')
    except TimeoutError as e:
        print(str(e))
    # else:
    #     print(result)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值