如何在Python中结合Cmd和Matplotlib
我想将 Matplotlib 中的交互式绘图与 python 中的命令行界面 Cmd 结合起来。我该怎么做? 我可以使用线程吗?我尝试了以下操作:
from cmd import Cmd
import matplotlib.pylab as plt
from threading import Thread
class MyCmd(Cmd):
def __init__(self):
Cmd.__init__(self)
self.fig = plt.figure()
self.ax = self.fig.add_subplot(1,1,1)
def do_foo(self, arg):
self.ax.plot(range(10))
self.fig.canvas.draw()
if __name__=='__main__':
c = MyCmd()
Thread(target=c.cmdloop).start()
plt.show()
它打开一个图形窗口,我可以在控制台中键入实际执行的命令。当执行“foo”命令时,它会在图形窗口中绘制。到目前为止一切都还好。然而,当我重新进入控制台时,控制台似乎被卡住了,现在出现了新的命令窗口。但是,当我单击图形窗口时,控制台会输出一个新的命令提示符,我可以输入一个新命令。 看来这两个循环并没有真正交错或什么的。有没有更好、更通用的方法?
I'd like to combine interactive plotting in Matplotlib and the Command line interface Cmd in python. How can I do this?
Can I use threading? I tried the following:
from cmd import Cmd
import matplotlib.pylab as plt
from threading import Thread
class MyCmd(Cmd):
def __init__(self):
Cmd.__init__(self)
self.fig = plt.figure()
self.ax = self.fig.add_subplot(1,1,1)
def do_foo(self, arg):
self.ax.plot(range(10))
self.fig.canvas.draw()
if __name__=='__main__':
c = MyCmd()
Thread(target=c.cmdloop).start()
plt.show()
It opens a figure window and I can type commands in the console that are actually executed. When the "foo" command is executed it draws in the figure window. So far everything is ok. When I reenter the console, however, the console seems to be stuck and there is now new command window. But when I click into the figure window the console outputs a new command prompt and I can enter a new command.
It seems the two loops are not really interleaved or something. Is there a better, more common way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我发现了一些有用的东西,但相当丑陋
这只是定期调用图形的绘制方法。如果我不这样做,当图形被遮挡并再次来到前面时,就不会重新绘制图形。
但这看起来很难看。有更好的办法吗?
I found something that works, but is rather ugly
This simply calls the draw method of the figure periodically. If I don't do this, the figure is not redrawn, when it was occluded and comes to the front again.
But this seems ugly. Is there a better way?
iPython 非常流行。查看在 python shell 中使用 matplotlib。
iPython is an pretty popular. Take a look at Using matplotlib in a python shell.