【问题标题】:Define with statement that automatically includes try and except定义自动包含 try 和 except 的语句
【发布时间】:2021-08-05 00:43:21
【问题描述】:

是否可以定义一个自己的 with 语句,它自动包含 try...except 错误处理? 例如,最好有一个简写形式:

with Do_Something():
    try:
        ...
    except Exception as e:
        print(str(e))

...看起来像这样:

with Try_Something():
    ...
    

我们如何将 try...except 行为包含到以下 MWE 类中?

class Do_Something():
    def __init__(self):
        pass

    def __enter__(self):
        print('Starting...')
        # invoke "try" somewhere here?
        return(self)

    def __exit__(self, except_type, except_value, tb):
        # invoke "except" somewhere here?

【问题讨论】:

  • __exit__() 方法允许异常处理。详情请参阅docs
  • 这能回答你的问题吗? Handling exceptions inside context managers
  • @Corralien:该链接很有帮助,但它处理了一个更具体的问题。它没有完全回答这里所说的问题,因为我不想以某种方式处理错误,我想重现 try...except 的默认输出。即,问题归结为如何以与str(e) 使用except 提供的参数类似的方式输出__exit__ 提供的回溯信息。

标签: python exception try-catch with-statement


【解决方案1】:

看起来with 本身带有try,并将异常作为参数传递给__exit__(...)。所以这可能是一个合适的解决方案:

import traceback
class Try_Something():
    def __init__(self):
        pass

    def __enter__(self):
        print('Starting...')
        # invoke "try" somewhere here? -- No, "with" automatically invokes "try"
        return(self)

    def __exit__(self, except_type, except_value, tb):
        if not except_type:
            print('finished.')
        else:
            print('failed.')
            traceback.print_exc() # prints error similar to str(e) from the question
        return(True)

我没有找到没有import traceback 的解决方案。请评论是否有一种方法可以使用提供的参数直接打印回溯信息而无需额外的模块。

【讨论】:

    【解决方案2】:

    根据the docs,如果你想抑制异常,__exit__应该返回True

    传递给__exit__ 的参数将描述异常,以防您想做出有条件的决定。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-04-01
      • 2011-09-29
      • 2020-06-08
      • 2013-04-10
      • 1970-01-01
      • 1970-01-01
      • 2018-02-24
      • 1970-01-01
      相关资源
      最近更新 更多