matplotlib, Preview, and AppleScript -- Oh, My!
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:
- cmd-tab to iterm from eclipse
- run python program
- look at resulting gui which is now the forground window
- cmd-q to close the gui
- cmd-tab to eclipse from iterm
And I never touched the mouse. With pylab.show() it looks like this:
- cmd-tab to iterm from eclipse
- run python program
- look at gui
- cmd-q which does nothing
- move the mouse over to the x-button to close the window
- 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.
- cmd-tab to iterm from eclipse
- run python program
- look at gui
- 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