【问题标题】:How can I quickly disable a try statement in python for testing?如何快速禁用 python 中的 try 语句进行测试?
【发布时间】:2012-11-23 22:45:00
【问题描述】:

假设我有以下代码:

尝试: 打印“富” # 更多代码... 打印“酒吧” 除了: 经过

出于测试目的,我如何临时禁用 try-statement?

您不能只注释掉 tryexcept 行,因为缩进仍会关闭。

没有比这更简单的方法了吗?

#尝试: 打印“富” # 更多代码... 打印“酒吧” #除了: # 经过

【问题讨论】:

  • 您通常应该首先避免在 try: 块中包含“更多代码”。通常你只需要一行。
  • 这个问题毫无意义。您不会禁用 try 语句进行测试,而是测试它是否被正确执行。如果您的意思是像某种形式的“原型设计”一样进行测试,只需将 try 语句中的代码移动到函数中并直接调用该函数即可。

标签: python debugging testing exception-handling


【解决方案1】:

背靠 velotron 的回答,我喜欢做这样的事情:

try:
    print 'foo'
    # A lot more code...
    print 'bar'
except:
    if settings.DEBUG:  # Use some boolean to represent dev state, such as DEBUG in Django
        raise           # Raise the error
    # Otherwise, handle and move on. 
    # Typically I want to log it rather than just pass.
    logger.exception("Something went wrong")

【讨论】:

    【解决方案2】:

    您可以将异常重新引发为 except 块的第一行,它的行为就像没有 try/except 一样。

    try:
        print 'foo'
        # A lot more code...
        print 'bar'
    except:
        raise # was: pass
    

    【讨论】:

      【解决方案3】:

      让你的except 只捕获try 块不会抛出的东西:

      class FakeError:
          pass
      
      try:
          # code
      except FakeError: # OldError:
          # catch
      

      实际上不确定这是否是一个好主意,但它确实有效!

      【讨论】:

        【解决方案4】:

        将其转换为if True 语句,except 子句被else 分支“注释掉”(永远不会被执行):

        if True: # try:
            # try suite statements
        else: # except:
            # except suite statements
        

        else: 是可选的,您也可以只注释掉整个 except: 套件,但使用 else: 您可以将整个 except: 套件缩进并取消注释。

        所以:

        try:
            print 'foo'
            # A lot more code...
            print 'bar'
        except SomeException as se:
            print 'Uhoh, got SomeException:', se.args[0]
        

        变成:

        if True: # try:
            print 'foo'
            # A lot more code...
            print 'bar'
        else: # except SomeException as se:
            print 'Uhoh, got SomeException:', se.args[0]
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-08-24
          • 1970-01-01
          • 1970-01-01
          • 2019-02-28
          • 2021-06-10
          • 2018-02-16
          相关资源
          最近更新 更多