在多线程Python代码中遇到Emacs pdb和断点问题

时间:2010-10-05 21:29:12

标签: python multithreading emacs pdb

我正在使用python.el运行Emacs 23.2并使用pdb调试一些Python代码。

我的代码使用threading模块生成一个兄弟线程,我在run()方法的开头设置了一个断点,但是pdb永远不会处理该断点,即使代码绝对运行并适用于所有意图和目的。

我的印象是我可以使用pdb任何线程中建立断点,即使实际上不支持完整的多线程调试。

我错误地认为 M-x pdb调用中的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()

感谢皮埃尔和他所提到的书籍文本,我尝试了将pdb.set_trace()包含在内的选项如下:

def run(self):
    import pdb; pdb.set_trace()
    print "Set a breakpoint here then M-x pdb and type c..."

但是这只会中断并为步骤提供pdb控件,接下来,继续等,如果它是从控制台执行并直接在Python解释器中运行,并且至关重要通过 Mx pdb - 至少使用我的Emacs和pdb配置。

所以我原来的问题可以改写:

有没有办法从Emacs中调用Python程序,该程序使用内联调用pdb(从而支持多线程应用程序中断),以及是否有自动神奇地建立的pdb comint控制缓冲区?

如果我使用Mx pdb运行我的Python应用程序并且它包含pdb的内联调用,那么如何最好地处理这导致pdb-session-in-a-pdb-session与相关的控制权失去这一事实?

2 个答案:

答案 0 :(得分:1)

请参阅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.

答案 1 :(得分:1)

您使用的是默认的python.el吗?我已经放弃了并开始使用python-mode.el。然后在提示符类型M-x shell中输入python myproblem.py(当然替换为您的程序名称),它将停在set_trace行。它与pdb集成开箱即用。 (它适用于你的程序)。