我只是想使用matplotlib来可视化一些调试数据。遵循这个页面:Analyzing C/C++ matrix in the gdb debugger with Python and Numpy - CodeProject,它可以正常工作,除非matplotlib GUI阻塞了GDB的命令行。这意味着如果我保持GUI窗口打开,GDB的命令行将被冻结,我无法在GDB命令中输入任何内容,直到关闭pyplot窗口。
为了解决这个问题,我尝试在另一个线程中运行绘图代码。为简化测试用例,我创建了一个名为“test-pyplot.py”的简单python源代码文件,其内容如下:
import numpy as np
from matplotlib import pyplot as plt
from threading import Thread
class MyThread (Thread):
def __init__(self, thread_id):
Thread.__init__(self)
self.thread_id = thread_id
def run(self):
x = np.arange(0, 5, 0.1);
y = np.sin(x)
plt.plot(x, y)
plt.show(block = True) #this cause the mainloop
thread1 = MyThread(1)
thread1.start()
现在,在GDB命令行下,我只需键入:
source test-pyplot.py
,一个非阻塞的GUI将会打开并且看起来不错,GDB的命令行仍然可以接收命令,目前为止一切都很好。但是问题出现了,当我关闭绘图窗口后,再次运行source test-pyplot.py
时,这时,GDB就卡住了。我使用的是Windows下的Python2.7.6,并且我看到matplotlib默认使用tkAgg
作为绘图后端,因此我想看看是否会对普通的tk GUI窗口产生影响。这里有另一个名为“test-tk.py”的测试Python文件,其内容如下:from Tkinter import *
from threading import Thread
class App():
def __init__(self):
self.g=Tk()
self.th=Thread(target=self.g.mainloop)
self.th.start()
def destroy(self):
self.g.destroy()
a1 = App()
如果我在GDB提示符下运行命令
source test-tk.py
,将会出现一个tk窗口,GDB仍然活动(未冻结),我可以关闭tk窗口,然后再次输入命令source test-tk.py
,一切都正常工作,GDB不会挂起。我甚至可以在没有关闭第一个tk窗口的情况下两次运行命令source test-tk.py
,那么就会出现两个tk窗口。问题:如何以非阻塞模式正确显示matplotlib pyplot图形,而不会挂起GDB?谢谢。 通常,
plt.show
会在内部调用Tkinter包的mainloop
函数,这是一个事件循环。
matplotlib确实有一个名为交互模式的选项,可以通过调用`plt.ion()`来启用,但它无法解决我的问题。