要在多个函数中共用一个xlwings异常捕获函数,并且在异常捕获中输出xlwings操作的文件名,可以使用Python的装饰器来实现。

首先,创建一个装饰器函数,用于捕获异常并输出文件名:

import xlwings as xw

def catch_exceptions(func):
    def wrapper(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except Exception as e:
            wb = xw.Book.caller()
            print(f"Error occurred in file: {wb.name}")
            print(f"Error message: {str(e)}")
    return wrapper

然后,在需要捕获异常的函数上添加@catch_exceptions装饰器,如下所示:

@catch_exceptions
def function1():
    # 此函数中的xlwings操作可能会抛出异常
    ...

@catch_exceptions
def function2():
    # 此函数中的xlwings操作可能会抛出异常
    ...

现在,当function1function2中的xlwings操作抛出异常时,异常将被catch_exceptions装饰器捕获,并输出相关信息,包括文件名。

注意,使用xw.Book.caller()可以获取当前xlwings操作所在的工作簿对象,然后通过.name属性获取文件名

python 多个函数共用一个xlwings异常捕获函数异常捕获中可以输出xlwings操作的文件名

原文地址: https://www.cveoy.top/t/topic/iEcH 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录