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

#!/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)

你可能感兴趣的:(python,开发语言)