matplotlib, Preview, and AppleScript -- Oh, My!


nathanieltroutman - Posted on 13 March 2010

 I use matplotlib fairly frequently in my research, it rocks. However, the fact that the MacOSX backed doesn't let me use 'Cmd-Q' to close things down is annoying. So my solution is a combination of pycario and preview with a little AppleScript through in for fun. I program in Eclipse with PyDev, however I run my python programs exclusively from iTerm. Hence, I'm used to cmd-tabbing back and forth between iterm and eclipse. However, when I run a program that opens up a gui, such doing "pylab.show()" things get annoying. When using other gui elements that allow 'Cmd-Q' to close things down it doesn't interupt my work flow:

  1. cmd-tab to iterm from eclipse
  2. run python program
  3. look at resulting gui which is now the forground window
  4. cmd-q to close the gui
  5. cmd-tab to eclipse from iterm

And I never touched the mouse. With pylab.show() it looks like this:

  1. cmd-tab to iterm from eclipse
  2. run python program
  3. look at gui
  4. cmd-q which does nothing
  5. move the mouse over to the x-button to close the window 
  6. cmd-tab to eclipse from iterm

Which is annoying to me. My solution? Don't bother with the MacOSC backend for matplotlib since I don't need any of its features, i just want to see the graph for about 5 seconds. So my code would look something like:

import os
import matplotlib as mpl
mpl.use('cairo')
import pylab as plt
import numpy as np
 
plt.plot(np.random.random(10))
 
plt.savefig('/tmp/tmp.png')
os.system('osascript -e "tell application \\"Eclipse\\" to activate"')
os.system('open /tmp/tmp.png')

So the first few lines should make since, import stuff, pick the "cairo" backend, plot some random numbers. Then it gets interesting. Instead of "plt.show()" I save the figure to a png, then using AppleScript I call Eclipse to the foreground, and last I open the saved figure which uses Preview. Now the window order is Preview > Eclipse > iTerm. 

 

  1. cmd-tab to iterm from eclipse
  2. run python program
  3. look at gui
  4. cmd-q and I'm back at eclipse

Which cuts a step off of my non-gui workflow and two steps off the clumsy plt.show() workflow. And there you go. 

 

Post new comment

The content of this field is kept private and will not be shown publicly.
By submitting this form, you accept the Mollom privacy policy.