Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detach matplotlib window from sub-process

I've got a script which creates a graph, but the script keeps running in the background until the window is closed. I'd like it to quit as soon as the window is created, so that Ctrl-C in the shell won't kill the window, and so that the user can leave the window open and continue working in the shell without bg-ing it manually. I've seen some solutions with daemons, but I'd like to avoid splitting this into two scripts. Is multiprocessing the easiest solution, or is there something shorter?

The relevant show() command is the last thing that is executed by the script, so I don't need to keep a reference to the window in any way.

Edit: I don't want to save the figure as a file, I want to be able to use the interactive window. Essentially the same as running mian ... & in bash

like image 366
l0b0 Avatar asked Oct 30 '10 12:10

l0b0


People also ask

Why is %Matplotlib inline?

The line magic command %matplotlib inline enables the drawing of matplotlib figures in the IPython environment. Once this command is executed in any cell, then for the rest of the session, the matplotlib plots will appear directly below the cell in which the plot function was called.

How do I not show plot in matplotlib?

Don't show the plot show()” also written as “plt. show()” is the command responsible for showing the plot. If you want the figure to NOT show, then simply skip this step. By this way, the plot is generated, saved and closed.

What is PLT show block false?

plt.show(block=False) #this creates an empty frozen window. _ = raw_input("Press [enter] to continue.") if __name__ == '__main__': main()


2 Answers

Just discovered this argument in plt.show(). setting block=False will pop up the figure window, continue following code, and keep you in the interpreter when the script has finished (if you are running in interactive mode -i).

plt.show(block=False)
like image 63
blaylockbk Avatar answered Oct 15 '22 10:10

blaylockbk


This works for Unix:

import pylab
import numpy as np
import multiprocessing as mp
import os

def display():
    os.setsid()
    pylab.show()

mu, sigma = 2, 0.5
v = np.random.normal(mu,sigma,10000)
(n, bins) = np.histogram(v, bins=50, normed=True)
pylab.plot(bins[:-1], n)
p=mp.Process(target=display)
p.start()

When you run this script (from a terminal) the pylab plot is displayed. Pressing Ctrl-C kills the main script, but the plot remains.

like image 39
unutbu Avatar answered Oct 15 '22 10:10

unutbu