參考資料:
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