菜单 学习猿地 - LMONKEY

VIP

开通学习猿地VIP

尊享10项VIP特权 持续新增

知识通关挑战

打卡带练!告别无效练习

接私单赚外块

VIP优先接,累计金额超百万

学习猿地私房课免费学

大厂实战课仅对VIP开放

你的一对一导师

每月可免费咨询大牛30次

领取更多软件工程师实用特权

入驻
20
0

python gdb

原创
05/13 14:22
阅读数 29366

参考资料:

https://wiki.python.org/moin/DebuggingWithGdb

https://blog.csdn.net/Gamish/article/details/81632862

1 安装:sudo apt-get install gdb python2.7-dbg

2 调试:若脚本在A目录,则要在A目录执行 

gdb python <pid of running process>

3 从Ubuntu10.10开始,系统为安全考虑,默认阻止一个进程检查和修改另一个进程,除非前者是后者的父进程

阻止操作由 ptrace_scope 实现,当 ptrace_scope = 1 时,gdb 在调试运行中的进程时,会产生如下报错:

Attaching to process xxx
Could not attach to process.  If your uid matches the uid of the target process,
check the setting of /proc/sys/kernel/yama/ptrace_scope, or try again as the root user.  
For more details, see /etc/sysctl.d/10-ptrace.conf
ptrace: Operation not permitted.

在配置文件 /etc/sysctl.d/10-ptrace.conf里有这么一句话
The PTRACE scope is ignored when a user has CAP_SYS_PTRACE, so “sudo strace -fp $PID” will work as before.

所以为了使ptrace_scope不起作用,需要拥有CAP_SYS_PTRACE
如何使 docker 容器具有 CAP_SYS_PTRACE ? 

docker 使用 –privileged 和 –cap-add 、–cap-drop 来控制容器的权限, 如果是–privileged启动,容器将获得最大的cap,如果不是,就需要用 –cap-add 、–cap-drop 来增加或删除。

获得 CAP_SYS_PTRACE 的命令:docker run -it --cap-add SYS_PTRACE imagesname /bin/bash

至此,gdb -p PID 可正常调试。

 ============
起进程
1 python3 -m compileall sdf.py
2 cd __pycache__
3 python3 sdf.cpython-35.pyc
开始gdb
1 ps afx | grep sdf
2 gdb python3 -p 30031
3 py-bt

============ 原来py-list没成功,报找不到文件,是以为环境有两个版本的python,gdb时没有指定python版本
起进程
1 python3 -m sdf.py
开始gdb
1 ps afx | grep sdf
2 gdb python3 -p 30031
3 py-bt

============
起进程
1 python2.7 -m sdf.py
开始gdb
1 ps afx | grep sdf
2 gdb python2.7 -p 30031
3 py-bt
=========
如果安装的是GNU的gdb,就需要打开gdb后手动载入libpython.py脚本【可以在真正gdb前,手动载入一些模块
(gdb) python
> import sys
>sys.path.insert(0, '/path/to/libpython.py' )
> import libpython
>end
(gdb)
============
  • py-list        查看当前python应用程序上下文
  • py-bt          查看当前python应用程序调用堆栈
  • py-bt-full   查看当前python应用程序调用堆栈,并且显示每个frame的详细情况
  • py-print     查看python变量
  • py-locals   查看当前的scope的变量
  • py-up         查看上一个frame
  • py-down    查看下一个frame
  • info threads
  • thread 37
  • thread apply all py-list

py-list START

py-down

py-up

py-print x

py-locals

(gdb) python
>aa=1
>bb=2
>cc=aa+bb
>print(cc)
>end
3
(gdb)

使用generate-core-file命令生成一个coredump文件,之后可以用gdb-core来打开coredump
封装了gdb,让python调试更方便的一个git

发表评论

0/200
20 点赞
0 评论
收藏