如何调试多线程python脚本

e27*_*314 5 python debugging

我有一个运行几个线程的python脚本。通常,当我想调试python脚本时,请使用“ -m pdb”运行它,然后使用“ b”设置一个断点。但是,由于某种原因,即使它通过了那条线,它也不会在断点处停止,甚至我看到实际上已经添加了断点。知道我在做什么错吗?我从这里使用了一个简单的python线程模块示例

import threading

class SummingThread(threading.Thread):
     def __init__(self,low,high):
         threading.Thread.__init__(self)
         self.low=low
         self.high=high
         self.total=0

     def run(self):
         print 'self.low = ' + str(self.low) + ', self.high = ' + str(self.high)
         for i in range(self.low,self.high):
             self.total+=i

thread1 = SummingThread(0,500000)
thread2 = SummingThread(500000,1000000)
thread1.start() # This actually causes the thread to run
thread2.start()
thread1.join()  # This waits until the thread has completed
thread2.join()
# At this point, both threads have completed
result = thread1.total + thread2.total
print result
Run Code Online (Sandbox Code Playgroud)

然后run,使用print命令在该行中的方法内部添加一个断点并运行脚本。脚本运行,通过print命令,但不会停止。

~$ python -m pdb test.py
> /home/user/test.py(1)<module>()
-> import threading
(Pdb) b 11
Breakpoint 1 at /home/user/test.py:11
(Pdb) r
self.low = 0, self.high = 500000
 self.low = 500000, self.high = 1000000
499999500000
--Return--
> /home/user/test.py(24)<module>()->None
-> print result
(Pdb) q
Run Code Online (Sandbox Code Playgroud)

alt*_*urt 1

正如评论中提到的,pdb 不支持线程。但您可以在线程中使用 pdb。

import pdb
import threading

class SummingThread(threading.Thread):
     ...

     def run(self):
         # TODO: do for only one thread.
         pdb.set_trace()
         print 'self.low = ' + str(self.low) + ', self.high = ' + str(self.high)
         ...         

Run Code Online (Sandbox Code Playgroud)