l0b0 l0b0 - 1 month ago 19
Python Question

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

Answer

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.

Comments