首页 文章

如何在Python中打印错误?

提问于
浏览
386
try:
    something here
except:
    print 'the whatever error occurred.'

如何在 except: 块中打印错误?

6 回答

  • 41

    对于Python 2.6及更高版本和Python 3.x:

    except Exception as e: print(e)
    

    对于Python 2.5及更早版本,请使用:

    except Exception,e: print str(e)
    
  • 561

    traceback模块为formatting and printing exceptions及其回溯提供方法,例如:这会像默认处理程序那样打印异常:

    import traceback
    
    try:
        1/0
    except Exception:
        traceback.print_exc()
    

    输出:

    Traceback (most recent call last):
      File "C:\scripts\divide_by_zero.py", line 4, in <module>
        1/0
    ZeroDivisionError: division by zero
    
  • 270

    Python 2.6 or greater 它有点清洁:

    except Exception as e: print(e)
    

    在旧版本中,它仍然具有可读性:

    except Exception, e: print e
    
  • 4

    如果你想传递错误字符串,这是一个来自Errors and Exceptions的例子(Python 2.6)

    >>> try:
    ...    raise Exception('spam', 'eggs')
    ... except Exception as inst:
    ...    print type(inst)     # the exception instance
    ...    print inst.args      # arguments stored in .args
    ...    print inst           # __str__ allows args to printed directly
    ...    x, y = inst          # __getitem__ allows args to be unpacked directly
    ...    print 'x =', x
    ...    print 'y =', y
    ...
    <type 'exceptions.Exception'>
    ('spam', 'eggs')
    ('spam', 'eggs')
    x = spam
    y = eggs
    
  • 10

    (我打算将此作为对@ jldupont答案的评论,但我没有足够的声誉 . )

    我在其他地方也见过像@ jldupont这样的答案 . FWIW,我认为重要的是要注意这一点:

    except Exception as e:
        print(e)
    

    默认情况下会将错误输出打印到 sys.stdout . 一般来说,更合适的错误处理方法是:

    except Exception as e:
        print(e, file=sys.stderr)
    

    (请注意,为此必须使用 import sys . )这样,错误将打印到 STDERR 而不是 STDOUT ,这允许正确的输出解析/重定向/等 . 我理解这个问题严格来说是关于'printing an error',但是在这里指出最佳实践似乎很重要,而不是忽略这些细节,这可能导致任何最终没有学到更好的人的非标准代码 .

    我没有像最好的方式那样使用 traceback 模块,但我想我会把它扔出去 .

  • 157

    如果这是您想要做的事情,可以使用断言语句完成一个线程错误提升 . 这将帮助您编写静态可修复代码并尽早检查错误 .

    assert type(A) is type(""), "requires a string"
    

相关问题