##// END OF EJS Templates
Initial support for %pylab magic to load pylab at runtime....
Fernando Perez -
Show More
@@ -264,7 +264,7 b' class Application(object):'
264 # our shipped copies of builtin profiles even if they don't have them
264 # our shipped copies of builtin profiles even if they don't have them
265 # in their local ipython directory.
265 # in their local ipython directory.
266 prof_dir = os.path.join(get_ipython_package_dir(), 'config', 'profile')
266 prof_dir = os.path.join(get_ipython_package_dir(), 'config', 'profile')
267 self.config_file_paths = (os.getcwd(), self.ipython_dir,prof_dir)
267 self.config_file_paths = (os.getcwd(), self.ipython_dir, prof_dir)
268
268
269 def pre_load_file_config(self):
269 def pre_load_file_config(self):
270 """Do actions before the config file is loaded."""
270 """Do actions before the config file is loaded."""
@@ -80,10 +80,97 b' def compress_dhist(dh):'
80 done.add(h)
80 done.add(h)
81
81
82 return newhead + tail
82 return newhead + tail
83
83
84
85 def pylab_activate(user_ns, gui=None, import_all=True):
86 """...."""
87
88 # Initialize matplotlib to interactive mode always
89 import matplotlib
90
91 # If user specifies a GUI, that dictates the backend, otherwise we read the
92 # user's mpl default from the mpl rc structure
93 g2b = {'tk': 'TkAgg',
94 'gtk': 'GTKAgg',
95 'wx': 'WXAgg',
96 'qt': 'Qt4Agg', # qt3 not supported
97 'qt4': 'Qt4Agg' }
98
99 if gui:
100 # select backend based on requested gui
101 backend = g2b[gui]
102 else:
103 backend = matplotlib.rcParams['backend']
104 # In this case, we need to find what the appropriate gui selection call
105 # should be for IPython, so we can activate inputhook accordingly
106 b2g = dict(zip(g2b.values(),g2b.keys()))
107 gui = b2g[backend]
108
109 matplotlib.use(backend)
110
111 # This must be imported last in the matplotlib series, after
112 # backend/interactivity choices have been made
113 import matplotlib.pylab as pylab
114
115 pylab.show._needmain = False
116 # We need to detect at runtime whether show() is called by the user.
117 # For this, we wrap it into a decorator which adds a 'called' flag.
118 pylab.draw_if_interactive = flag_calls(pylab.draw_if_interactive)
119
120 # Import numpy as np/pyplot as plt are conventions we're trying to
121 # somewhat standardize on. Making them available to users by default
122 # will greatly help this.
123 exec ("import numpy\n"
124 "import numpy as np\n"
125 "import matplotlib\n"
126 "from matplotlib import pylab, mlab, pyplot as plt\n"
127 ) in user_ns
128
129 if import_all:
130 exec("from matplotlib.pylab import *\n"
131 "from numpy import *\n") in user_ns
132
133 matplotlib.interactive(True)
134
135 # matplotlib info banner
136 print """
137 Welcome to pylab, a matplotlib-based Python environment.
138 Backend in use: %s
139 For more information, type 'help(pylab)'.\n""" % backend
140 return gui
141
142 def mpl_runner(safe_execfile):
143 def mplot_exec(fname,*where,**kw):
144 """Execute a matplotlib script.
145
146 This is a call to execfile(), but wrapped in safeties to properly
147 handle interactive rendering and backend switching."""
148
149 import matplotlib
150 import matplotlib.pylab as pylab
151
152 #print '*** Matplotlib runner ***' # dbg
153 # turn off rendering until end of script
154 isInteractive = matplotlib.rcParams['interactive']
155 matplotlib.interactive(False)
156 safe_execfile(fname,*where,**kw)
157 matplotlib.interactive(isInteractive)
158 # make rendering call now, if the user tried to do it
159 if pylab.draw_if_interactive.called:
160 pylab.draw()
161 pylab.draw_if_interactive.called = False
162
163 return mplot_exec
164
84
165
85 #***************************************************************************
166 #***************************************************************************
86 # Main class implementing Magic functionality
167 # Main class implementing Magic functionality
168
169 # XXX - for some odd reason, if Magic is made a new-style class, we get errors
170 # on construction of the main InteractiveShell object. Something odd is going
171 # on with super() calls, Component and the MRO... For now leave it as-is, but
172 # eventually this needs to be clarified.
173
87 class Magic:
174 class Magic:
88 """Magic functions for InteractiveShell.
175 """Magic functions for InteractiveShell.
89
176
@@ -1571,7 +1658,7 b' Currently the magic system has the following functions:\\n"""'
1571 return
1658 return
1572
1659
1573 if filename.lower().endswith('.ipy'):
1660 if filename.lower().endswith('.ipy'):
1574 self.safe_execfile_ipy(filename)
1661 self.shell.safe_execfile_ipy(filename)
1575 return
1662 return
1576
1663
1577 # Control the response to exit() calls made by the script being run
1664 # Control the response to exit() calls made by the script being run
@@ -3495,20 +3582,25 b' Defaulting color scheme to \'NoColor\'"""'
3495 This is highly recommended for most users.
3582 This is highly recommended for most users.
3496 """
3583 """
3497 from IPython.lib import inputhook
3584 from IPython.lib import inputhook
3498 if "-a" in parameter_s:
3585
3499 app = True
3586 opts, arg = self.parse_options(parameter_s,'a')
3500 else:
3587 if not arg:
3501 app = False
3502 if not parameter_s:
3503 inputhook.clear_inputhook()
3588 inputhook.clear_inputhook()
3504 elif 'wx' in parameter_s:
3589 return
3505 return inputhook.enable_wx(app)
3590
3506 elif ('qt4' in parameter_s) or ('qt' in parameter_s):
3591 guis = {'tk': inputhook.enable_tk,
3507 return inputhook.enable_qt4(app)
3592 'gtk':inputhook.enable_gtk,
3508 elif 'gtk' in parameter_s:
3593 'wx': inputhook.enable_wx,
3509 return inputhook.enable_gtk(app)
3594 'qt': inputhook.enable_qt4, # qt3 not supported
3510 elif 'tk' in parameter_s:
3595 'qt4': inputhook.enable_qt4 }
3511 return inputhook.enable_tk(app)
3596 try:
3597 gui = guis[arg]
3598 except KeyError:
3599 e="Invalid GUI request %r, valid ones are:%s" % (arg, guis.keys())
3600 raise UsageError(e)
3601
3602 #print 'Switching IPython gui support to:', arg, 'a' in opts # dbg
3603 return gui('a' in opts)
3512
3604
3513 def magic_load_ext(self, module_str):
3605 def magic_load_ext(self, module_str):
3514 """Load an IPython extension by its module name."""
3606 """Load an IPython extension by its module name."""
@@ -3576,5 +3668,21 b' Defaulting color scheme to \'NoColor\'"""'
3576 shutil.copy(src, dst)
3668 shutil.copy(src, dst)
3577 print "Installing default config file: %s" % dst
3669 print "Installing default config file: %s" % dst
3578
3670
3671 # Pylab support: simple wrappers that activate pylab, load gui input
3672 # handling and modify slightly %run
3673
3674 @testdec.skip_doctest
3675 def _pylab_magic_run(self, parameter_s=''):
3676 Magic.magic_run(self, parameter_s,
3677 runner=mpl_runner(self.shell.safe_execfile))
3678
3679 _pylab_magic_run.__doc__ = magic_run.__doc__
3680
3681 def magic_pylab(self, s):
3682 """Load pylab, optionally with gui of choice"""
3683
3684 gui = pylab_activate(self.shell.user_ns, s)
3685 self.shell.magic_gui('-a %s' % gui)
3686 self.shell.magic_run = self._pylab_magic_run
3579
3687
3580 # end Magic
3688 # end Magic
General Comments 0
You need to be logged in to leave comments. Login now