debugging 如何调试多线程Python脚本

nkhmeac6  于 2023-01-31  发布在  Python
关注(0)|答案(1)|浏览(154)

我有一个Python脚本,它运行的线程很少。通常,当我想调试一个Python脚本时,我用“-M PDB”运行它,然后用“B“在里面设置一个断点。然而,由于某种原因它没有停在断点处,即使它穿过了那条线,甚至我看到断点实际上是加上去的,知道我做错了什么吗?我使用了here中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方法中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
lyfkaqu1

lyfkaqu11#

正如在注解中提到的,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)
         ...

相关问题