Pyp*_*ros 10 python assert python-3.x pdb
假设我有一个python程序,其中assert用于定义事物应该是什么,并且我想用read-eval-loop捕获异常而不是AssertionError抛出.
当然,我可以
if (reality!=expectation):
print("assertion failed");
import pdb; pdb.set_trace();
Run Code Online (Sandbox Code Playgroud)
但是在代码中这比普通的更难看assert(reality==expectation).
我本可以在顶层pdb.set_trace()打电话except:,但后来我失去了失败的所有背景,对吧?(我的意思是,堆栈跟踪可以从异常对象中恢复,但不能从参数值中恢复,等等)
有没有像--magic命令行标志可以将python3解释器变成我需要的东西?
Con*_*ius 11
主要取自这个伟大的片段:
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
Run Code Online (Sandbox Code Playgroud)
用这个初始化你的代码时,所有的AssertionErrors都应该调用pdb.
| 归档时间: |
|
| 查看次数: |
2412 次 |
| 最近记录: |