Emacs pdb与多线程Python代码中的断点问题
我正在使用 Emacs 23.2 和 python.el
来调试一些 Python 代码,使用的是 pdb
工具。
我的代码使用 threading
模块创建了一个兄弟线程,我在 run()
方法的开头设置了一个断点,但即使代码确实运行并且效果很好,pdb
也从来没有处理过这个断点。
我原以为可以在 任何 线程中使用 pdb
来设置断点,尽管实际上并不支持完整的多线程调试。
我是不是错了,认为在 M-x pdb
调用中可以在任何线程中断?如果你不相信我,可以自己试试这个简单的例子。
import threading
class ThreadTest(threading.Thread):
def __init__(self,):
threading.Thread.__init__(self)
def run(self):
print "Type M-x pdb, set a breakpoint here then type c <RET>..."
print "As you can see it does not break!"
if __name__ == '__main__':
tt = ThreadTest()
tt.start()
多亏了 Pierre 和他提到的书籍,我尝试了将 pdb.set_trace()
加入代码,像这样:
def run(self):
import pdb; pdb.set_trace()
print "Set a breakpoint here then M-x pdb and type c..."
但是,这只有在从控制台直接运行 Python 解释器时才会中断并提供 pdb
控制选项,比如 step, next, continue 等等,而关键是 不能 通过 M-x pdb
来实现——至少在我的 Emacs 和 pdb
配置下是这样的。
所以我最初的问题可以重新表述一下:
有没有办法从 Emacs 内部调用一个 Python 程序,而这个程序使用内联调用的 pdb(从而支持多线程应用中的断点),并且能够自动建立一个 pdb 控制缓冲区?
或者
如果我使用 M-x pdb 运行我的 Python 应用程序,而它包含一个内联调用的 pdb,最好的处理方式是什么,因为这会导致一个 pdb 会话嵌套在另一个 pdb 会话中,从而失去控制?
2 个回答
请查看这个链接:http://heather.cs.ucdavis.edu/~matloff/158/PLN/ParProcBook.pdf,里面有一部分讲的是多线程调试的内容。
3.6.1 Using PDB to Debug Threaded Programs Using PDB is a bit more complex when threads are involved. One cannot, for instance, simply do something like this: pdb.py buggyprog.py because the child threads will not inherit the PDB process from the main thread. You can still run PDB in the latter, but will not be able to set breakpoints in threads. What you can do, though, is invoke PDB from within the function which is run by the thread, by calling pdb.set trace() at one or more points within the code: import pdb pdb.set_trace() In essence, those become breakpoints. For example, in our program srvr.py in Section 3.1.1, we could add a PDB call at the beginning of the loop in serveclient(): while 1: import pdb pdb.set_trace() # receive letter from client, if it is still connected k = c.recv(1) if k == ’’: break You then run the program directly through the Python interpreter as usual, NOT through PDB, but then the program suddenly moves into debugging mode on its own. At that point, one can then step through the code using the n or s commands, query the values of variables, etc. PDB’s c (“continue”) command still works. Can one still use the b command to set additional breakpoints? Yes, but it might be only on a one-time basis, depending on the context. A breakpoint might work only once, due to a scope problem. Leaving the scope where we invoked PDB causes removal of the trace object. Thus I suggested setting up the trace inside the loop above.
你在用默认的 python.el 吗?我已经放弃那个了,改用 python-mode.el。然后输入 M-x shell
,在提示符下输入 python myproblem.py
(当然要把程序名换成你自己的),这样它就会在 set_trace
这一行停下来。这个方法开箱即用,还能和 pdb(Python 调试工具)集成。(而且它可以在你的程序上正常工作)。