代码终止后保持 matplotlib/pyplot 窗口打开 [英] keep matplotlib / pyplot windows open after code termination
问题描述
我希望python制作一个绘图,在不阻塞控制流的情况下显示它,并在代码退出后保持绘图打开.这可能吗?
I'd like python to make a plot, display it without blocking the control flow, and leave the plot open after the code exits. Is this possible?
这个和相关主题存在于许多其他线程中(见下文),但我无法让情节既保持开放又不阻塞.例如,如果我在 pyplot.show()
之前使用 pyplot.ion()
,或者如果我使用 pyplot.show(block=False)
>然后,代码终止时图将关闭.使用 python
或 ipython
都是如此.如果重要的话,我在 OS X 10.8.2 (Mountain Lion) 上运行,运行 python27
和 ipython27
This, and related subjects exist (see below) in numerous other threads, but I can't get the plot to both stay open, and be non-blocking. For example, if I use pyplot.ion()
before pyplot.show()
, or if I use pyplot.show(block=False)
then the plot closes when the code terminates. This is true using either python
or ipython
. If it matters, I'm running on OS X 10.8.2 (Mountain Lion), running python27
and ipython27
相关讨论:
pylab matplotlibshow"等到窗口关闭
有没有办法分离 matplotlib 图以便计算可以继续?
保持在Matplotlib中打开绘图窗口
关闭pyplot窗口
推荐答案
在 Linux 上,您可以通过以下方式分离显示:
On Linux you can detach the display this way:
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab
import numpy as np
import os
def detach_display():
mu, sigma = 0, 0.5
x = np.linspace(-3, 3, 100)
plt.plot(x, mlab.normpdf(x, mu, sigma))
plt.show()
if os.fork():
# Parent
pass
else:
# Child
detach_display()
主要过程结束了,但情节依然存在.
The main process ends, but the plot remains.
尝试#2.这在Linux上也适用;您可以尝试一下:,但不能在OS X上使用.
Attempt #2. This also works on Linux; you might give it a try: but not on OS X.
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab
import numpy as np
import os
import multiprocessing as mp
def detach_display():
mu, sigma = 0, 0.5
x = np.linspace(-3, 3, 100)
plt.plot(x, mlab.normpdf(x, mu, sigma))
plt.show()
proc = mp.Process(target=detach_display)
proc.start()
os._exit(0)
在没有 os._exit(0)
的情况下,主进程会阻塞.按 Ctrl-C 会终止主进程,但情节仍然存在.
Without the os._exit(0)
, the main process blocks. Pressing Ctrl-C kills the main process, but the plot remains.
使用 os._exit(0)
,主过程结束,但情节仍然存在.
With the os._exit(0)
, the main process ends, but the plot remains.
叹气.尝试#3.如果您将 matplotlib 调用放在另一个脚本中,那么您可以像这样使用子进程:
Sigh. Attempt #3. If you place your matplotlib calls in another script, then you could use subprocess like this:
show.py:
import matplotlib.pyplot as plt
import numpy as np
import sys
filename = sys.argv[1]
data = np.load(filename)
plt.plot(data['x'], data['y'])
plt.show()
test.py
import subprocess
import numpy as np
import matplotlib.mlab as mlab
mu, sigma = 0, 0.5
x = np.linspace(-3, 3, 100000)
y = mlab.normpdf(x, mu, sigma)
filename = '/tmp/data.npz'
np.savez(filename, x=x, y=y)
proc = subprocess.Popen(['python', '/path/to/show.py', filename])
运行 test.py
应该显示一个绘图并将控制权返回给终端,同时保持绘图显示.
Running test.py
should display a plot and return control to the terminal while leaving the plot displayed.
这篇关于代码终止后保持 matplotlib/pyplot 窗口打开的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!