我可以在AssertionError上强制调试python吗?

2024-05-06 01:40:33 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有一个python程序,其中assert被用来定义事情应该如何,我希望用read eval循环捕捉异常,而不是抛出AssertionError。在

当然,我本来可以的

if (reality!=expectation):
    print("assertion failed");
    import pdb; pdb.set_trace();

但这在代码中比普通的assert(reality==expectation)难看得多。在

我可以在顶层调用pdb.set_trace()块,但这样我就失去了失败的所有上下文,对吗?(我的意思是,stacktrace可以从异常对象恢复,但不能从参数值等恢复)

有没有类似于--magic命令行标志可以将python3解释器转换成我需要的东西吗?在


Tags: 程序readif定义evaltraceassert事情
2条回答

看看nose项目。您可以将它与 pdb option一起使用,以便在出现错误时将其放入调试器。在

主要取自this great snippet

import sys

def info(type, value, tb):
   if hasattr(sys, 'ps1') or not sys.stderr.isatty() or type != AssertionError:
      # we are in interactive mode or we don't have a tty-like
      # device, so we call the default hook
      sys.__excepthook__(type, value, tb)
   else:
      import traceback, pdb
      # we are NOT in interactive mode, print the exception...
      traceback.print_exception(type, value, tb)
      print
      # ...then start the debugger in post-mortem mode.
      pdb.pm()

sys.excepthook = info

当您用这个初始化代码时,所有AssertionError都应该调用pdb。在

相关问题 更多 >