Python 线程 - 将控制权返回给终端,同时保持框架打开
总结一下:我想在 Python 中打开一个框架,能够使用该框架,并且还能够继续使用该终端。
基本上,我想在 Python 中模仿一些 Matlab 行为。在 Matlab 中,您可以执行以下操作:
x=0:10;
y=0:10;
plot(x,y)
将会出现一个交互图,并且您还可以访问终端来更改内容并执行其他工作。
我想在 Python 中,如果我正确地进行线程处理,我也可以做同样的事情。但是,下面的代码保持对终端的控制。
from threading import Thread
from matplotlib import pyplot as plt
class ThreadFrame(Thread):
def __init__(self):
Thread.__init__(self)
def setup(self):
my_plot = plt.plot(range(0,10), range(0,10))
fig = plt.gcf()
ax = plt.gca()
my_thread = ThreadFrame()
my_thread.start()
my_thread.setup()
plt.show()
我应该对线程做一些不同的事情吗?或者还有其他方法可以实现此目的吗?
To sum up: I want to open a frame in Python, be able to work with that frame, and also be able to continue using that terminal.
Basically, I'd like to mimic some Matlab behavior in Python. In Matlab, you can do:
x=0:10;
y=0:10;
plot(x,y)
and a plot will come up, be interactive, and you also have access to the terminal to change things and do other work.
I figured that in Python, if I threaded properly, I could do the same thing. However, the code below keeps control of the terminal.
from threading import Thread
from matplotlib import pyplot as plt
class ThreadFrame(Thread):
def __init__(self):
Thread.__init__(self)
def setup(self):
my_plot = plt.plot(range(0,10), range(0,10))
fig = plt.gcf()
ax = plt.gca()
my_thread = ThreadFrame()
my_thread.start()
my_thread.setup()
plt.show()
Is there something I should be doing differently with the threading? Or is there another way to accomplish this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
matplotlib 使用 plt.show() 变得很有趣。要获得您想要的行为,请查看交互式使用 matplotlib 的文档。好处是,不需要线程。
(在您的解决方案中,绘图在后台准备,后台线程终止,并且您的前台线程保留在 plt.show 中)
matplotlib gets funny about using plt.show(). To get the behaviour you want, look at the docs on using matplotlib interactively. The nice thing is, no threading necessary.
(In your solution, the plot is prepared in the background, the background thread terminates, and your foreground threads stays in the plt.show)
jtniehof的回答很好。作为替代方案,您可以查看 Python 源代码中的 pysvr分配。它允许您连接到正在运行的 Python 进程并以这种方式获取 REPL。
jtniehof's answer is good. For an alternative, you could have a look at pysvr inside the Python source distribution. It allows you to connect to a running Python process and get a REPL this way.