python stacktrace,e、 python中的printStackTrace等价物

e.printStackTrace equivalent in python

在Java中,这将执行以下操作(docs):public void printStackTrace()

Prints this throwable and its backtrace to the standard error stream...

它的用法如下:try

{

// code that may raise an error

}

catch (IOException e)

{

// exception handling

e.printStackTrace();

}

在Java中,标准错误流是无缓冲的,因此输出会立即到达。

Python 2中的相同语义是:import traceback

import sys

try: # code that may raise an error

pass

except IOError as e: # exception handling

# in Python 2, stderr is also unbuffered

print >> sys.stderr, traceback.format_exc()

# in Python 2, you can also from __future__ import print_function

print(traceback.format_exc(), file=sys.stderr)

# or as the top answer here demonstrates, use:

traceback.print_exc()

# which also uses stderr.

Python3

在Python 3中,我们可以直接从exception对象获得回溯(这可能对线程化代码的性能更好)。

还有,stderr is line-buffered,但是print函数得到

一个flush参数,因此这将立即打印到stderr:print(traceback.format_exception(None, #

e, e.__traceback__),

file=sys.stderr, flush=True)

结论:

因此,在Python 3中,traceback.print_exc(),尽管它使用sys.stderrby default,但是会缓冲输出,并且可能会丢失输出。因此,为了获得尽可能等效的语义,在Python 3中,将print与flush=True一起使用。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值