这个问题我想了很久,但一直没有找到合适的解决方案。如果我运行一个脚本,遇到一个IndexError, python会打印出错误的行、位置和快速描述,然后退出。是否有可能在遇到错误时自动启动pdb ?我并不反对在文件顶部添加额外的import语句,也不反对添加几行额外的代码。
当前回答
Python -m PDB script.py在python2.7中按continue start,它将运行到错误处并在那里中断以进行调试。
其他回答
使用以下模块:
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路径中的某个地方。
现在,在脚本的开头,只需添加一个导入调试。
如果您正在使用IPython环境,您可以只使用%debug, shell将带您回到ipdb环境中的违规行进行检查等。上面提到的另一个选项是使用iPython magic %pdb,它可以有效地完成同样的工作。
这不是调试器,但可能同样有用(?)
我知道我听圭多在某个地方的演讲中提到过这个。
我刚刚检查了python -?,如果您使用-i命令,您可以在脚本停止的地方进行交互。
给定这个脚本:
testlist = [1,2,3,4,5, 0]
prev_i = None
for i in testlist:
if not prev_i:
prev_i = i
else:
result = prev_i/i
您可以得到这个输出!
PS D:\> python -i debugtest.py
Traceback (most recent call last):
File "debugtest.py", line 10, in <module>
result = prev_i/i
ZeroDivisionError: integer division or modulo by zero
>>>
>>>
>>> prev_i
1
>>> i
0
>>>
说实话,我没用过这个,但我应该用,看起来很有用。
如果你正在运行一个模块:
python -m mymodule
现在你想在异常发生时输入pdb,这样做:
PYTHONPATH="." python -m pdb -c c mymodule/__main__.py
(或扩展PYTHONPATH)。由于您现在正在运行pdb模块,因此需要PYTHONPATH以便在路径中找到模块。
从3.7开始,你可以在你的代码中直接使用关键字breakpoint(不需要任何导入),就像这样:
try:
... # The line that raises an error
except:
breakpoint()
推荐文章
- 如何在Python中做指数和对数曲线拟合?我发现只有多项式拟合
- 创建独立变量字典的简单方法?
- 在Python中创建一个初始容量的列表
- Pylint在Visual Studio代码中“未解决的导入”错误
- Matplotlib错误-没有名为tkinter的模块
- 0到1之间的随机数?
- 使用Boto3将S3对象作为字符串打开
- "pip install——editable ./" vs "python setup.py develop"
- Pandas:索引数据帧时的多个条件-意外行为
- 如何更改Django应用程序的名称?
- 如何在python抽象类中创建抽象属性?
- “克隆”行或列向量
- 在python shell中按方向键时看到转义字符
- Linux有c++ gdb图形用户界面吗?
- 在pip install中方括号是什么意思?