Detach matplotlib window from subprocess

I have a script that creates a graph, but the script continues to run in the background until the window is closed, I would like it to leave as soon as the window was created, so that Ctrl-C in the shell will not kill the window, and so that the user can leave the window open and continue working in the shell without bg - manually. I saw some solutions with demons, but I would like this to not split into two scenarios. Is multiprocessing the easiest solution, or is there something shorter?

The corresponding show() command is the last thing the script runs, so I don't need to refer to the window in any way.

Edit: I do not want to save the shape as a file, I want to be able to use the interactive window. Essentially, this is the same as starting mian ... & in bash

+4
source share
3 answers

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 the terminal), a pylab graph will be displayed. Pressing Ctrl-C kills the main script, but the graph remains.

+2
source

I would suggest using os.fork () as the simplest solution. This is a trick used by demons, but it does not require two scenarios, and it is quite simple. For instance:

 import os proc_num = os.fork() if proc_num != 0: #This is the parent process, that should quit immediately to return to the #shell. print "You can kill the graph with the command \"kill %d\"." % proc_num import sys sys.exit() #If we've made it to here, we're the child process, that doesn't have to quit. import matplotlib.pyplot as plt plt.plot([1,2,3],[4,5,6]) plt.show() 
+3
source

Just opened this argument in plt.show (). set block = False a window will appear with a picture, continue the following code and save you in the interpreter when the script ends (if you are working in -i interactive mode).

 plt.show(block=False) 
+1
source

All Articles