如何使用try / catch包装Python函数

时间:2018-03-14 16:36:44

标签: python try-catch decorator wrapper

我有大约20个使用try / catch语句开始/结束的函数但是如何创建装饰器或包装器来执行它而不是复制和粘贴try catch 20x?

def func1():
        TIMER = time.time()
        try:
            print("function1 logic goes here")
        except Exception as e:
            logging.error(str(e))
            return str(e)

def func2():
        TIMER = time.time()
        try:
            print("function2 logic goes here")
        except Exception as e:
            logging.error(str(e))
            return str(e)

我需要用这个包装所有函数:

    TIMER = time.time()
    try:

    except Exception as e:
        logging.error(str(e))
        return str(e)

1 个答案:

答案 0 :(得分:0)

实现此目的的一种方法是创建一个类并将您的函数用作属性。实施例

def func1():
    print("function1 logic goes here")


class CustomFunction(object):

    def __init__(self, my_func):
        self.my_func

    def exec_func(self):
        TIMER = time.time()
        try:
            self.my_func()
        except Exception as e:
            logging.error(str(e))
            return str(e)

所以,你可以将你的函数包装成:

c_func1 = CustomFunction(func1)

然后打电话给:

c_func1.exec_func()