Python clean way to wrap individual statements in a try except block

前端 未结 4 1409
情话喂你
情话喂你 2021-01-17 21:14

I\'m currently doing some Python automation of Excel with com. It\'s fully functional, and does what I want, but I\'ve discovered something surprising. Sometimes, some of th

4条回答
  •  迷失自我
    2021-01-17 21:43

    This just wraps functions calls, but you can extend it to handle attribute access as well, and to proxy the results of nested attribute accesses, finally just wrapping the __setattr__ in your try:except block.

    It might be sensible to swallow only some specific exception types in your case (as @vsekhar says).

    def onErrorResumeNext(wrapped):
        class Proxy(object):
            def __init__(self, fn):
                self.__fn = fn
    
            def __call__(self, *args, **kwargs):
                try:
                    return self.__fn(*args, **kwargs)
                except:
                    print "swallowed exception"
    
        class VBWrapper(object):
            def __init__(self, wrapped):
                self.wrapped = wrapped
    
            def __getattr__(self, name):
                return Proxy(eval('self.wrapped.'+name))
    
        return VBWrapper(wrapped)
    

    Example:

    exceptionProofBorders = onErrorResumeNext(excel.Selection.Borders)
    exceptionProofBorders(xlDiagonalDown).LineStyle = xlNone
    exceptionProofBorders(xlDiagonalup).LineStyle = xlNone
    

提交回复
热议问题