从正在调试的python程序中控制gdb
pygdb2的Python项目详细描述
pygdb2是一个python模块,它允许您向 底层gdb进程。例如,它可以用于 以编程方式添加断点和监视点。
如何安装
确保pygdb2已安装:
$ pip install pygdb2
然后,您需要激活gdb集成,方法是将这一行放在 您的~/.gdbinit:
python import pygdb2
如何使用
您需要使用 pyrun命令:
$ gdb --args python myscript.py ... (gdb) pyrun ...
在python程序中,可以使用pygdb2.set_trace()输入gdb 提示,或pygdb2.execute()向gdb发送命令。
在(gdb)提示下,可以调用pdb命令来输入 在python级别的相应调试器中。
示例
例如,下面的代码为特定的 使用ctypes:
创建的内存区域import ctypes import pygdb2 def main(): buf = ctypes.c_int() buf.value = 42 adr = ctypes.cast(ctypes.pointer(buf), ctypes.c_void_p) # enter gdb when we write to this memory pygdb2.execute("watch *(int*)%d" % adr.value) i = 0 while i < 5: print i i += 1 if i == 2: buf.value = 43 # GDB stops here
下面是gdb/pdb会话的示例:
$ gdb --args python set_watchpoint.py ... (gdb) # lines prefixed "pygdb2:" contain the command coming from pygdb2.execute() (gdb) pyrun ... pygdb2: watch *(int*)14079984 Hardware watchpoint 1: *(int*)14079984 0 1 Hardware watchpoint 1: *(int*)14079984 Old value = 42 New value = 43 i_set (ptr=0xd6d7f0, value=<value optimized out>, size=4) at /build/buildd/python2.7-2.7.1/Modules/_ctypes/cfield.c:663 663 /build/buildd/python2.7-2.7.1/Modules/_ctypes/cfield.c: No such file or directory. in /build/buildd/python2.7-2.7.1/Modules/_ctypes/cfield.c (gdb) # now we are debugging at the C level (gdb) # in particular, we are inside function of _ctypes (gdb) # which sets the value of the buffer (gdb) # Let's jump to the Python level (gdb) pdb Signal received, entering pdb Traceback: File "set_watchpoint.py", line 20, in <module> main() File "set_watchpoint.py", line 16, in main buf.value = 43 # we should enter gdb here > /home/antocuni/env/src/pygdb2/pygdb2/test/set_watchpoint.py(12)main() -> while i < 5: (Pdb++) print i 2 (Pdb++) c 2 3 4 Program exited normally. (gdb) q
使用信号
pygdb2同时使用SIGUSR1和SIGUSR2与gdb通信, 所以如果你的程序也需要这些,你可能会有冲突。