这个问题我想了很久,但一直没有找到合适的解决方案。如果我运行一个脚本,遇到一个IndexError, python会打印出错误的行、位置和快速描述,然后退出。是否有可能在遇到错误时自动启动pdb ?我并不反对在文件顶部添加额外的import语句,也不反对添加几行额外的代码。
当前回答
要让它运行而不需要在开始时输入c,请使用:
python -m pdb -c c <script name>
Pdb有自己的命令行参数:-c c将在执行开始时执行c(continue)命令,程序将不间断地运行,直到出现错误。
其他回答
python -m pdb -c continue myscript.py
如果你没有提供-c continue标志,那么你需要在执行开始时输入'c'(代表continue)。然后它会运行到错误点并在那里给你控制权。正如eqzx所提到的,该标志是python 3.2中的新添加,因此在早期的python版本中需要输入'c'(请参阅https://docs.python.org/3/library/pdb.html)。
使用以下模块:
import sys
def info(type, value, tb):
if hasattr(sys, 'ps1') or not sys.stderr.isatty():
# 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() # deprecated
pdb.post_mortem(tb) # more "modern"
sys.excepthook = info
将其命名为debug(或任何你喜欢的名字),并将其放在python路径中的某个地方。
现在,在脚本的开头,只需添加一个导入调试。
在层次结构中最顶层异常类的构造函数中放置断点,大多数情况下您将看到哪里引发了错误。
设置断点意味着任何您想要的含义:您可以使用IDE或pdb。Set_trace之类的
要让它运行而不需要在开始时输入c,请使用:
python -m pdb -c c <script name>
Pdb有自己的命令行参数:-c c将在执行开始时执行c(continue)命令,程序将不间断地运行,直到出现错误。
你可以使用回溯。Print_exc输出异常回溯。然后使用sys。Exc_info来提取回溯信息,最后调用pdb。带有那个回溯的Post_mortem
import pdb, traceback, sys
def bombs():
a = []
print a[0]
if __name__ == '__main__':
try:
bombs()
except:
extype, value, tb = sys.exc_info()
traceback.print_exc()
pdb.post_mortem(tb)
如果你想用code. interactive启动一个交互式命令行,使用异常产生的帧的局部变量,你可以这样做
import traceback, sys, code
def bombs():
a = []
print a[0]
if __name__ == '__main__':
try:
bombs()
except:
type, value, tb = sys.exc_info()
traceback.print_exc()
last_frame = lambda tb=tb: last_frame(tb.tb_next) if tb.tb_next else tb
frame = last_frame().tb_frame
ns = dict(frame.f_globals)
ns.update(frame.f_locals)
code.interact(local=ns)
推荐文章
- ValueError: numpy。Ndarray大小改变,可能表示二进制不兼容。期望从C头得到88,从PyObject得到80
- Anaconda /conda -安装特定的软件包版本
- 我在哪里调用Keras的BatchNormalization函数?
- 打印测试执行时间并使用py.test锁定缓慢的测试
- 插入一行到熊猫数据框架
- 要列出Pandas DataFrame列
- 在Django模型中存储电话号码的最佳方法是什么?
- 从导入的模块中模拟函数
- 当有命令行参数时,如何使用GDB分析程序的核心转储文件?
- 滚动或滑动窗口迭代器?
- python的方法找到最大值和它的索引在一个列表?
- 如何读取文件的前N行?
- 如何删除matplotlib中的顶部和右侧轴?
- 解析.py文件,读取AST,修改它,然后写回修改后的源代码
- Visual Studio Code:如何调试Python脚本的参数