##// END OF EJS Templates
Update docs about embedding.
Thomas Kluyver -
Show More
@@ -1,274 +1,271 b''
1 1 # encoding: utf-8
2 2 """
3 3 An embedded IPython shell.
4 4
5 5 Authors:
6 6
7 7 * Brian Granger
8 8 * Fernando Perez
9 9
10 10 Notes
11 11 -----
12 12 """
13 13
14 14 #-----------------------------------------------------------------------------
15 15 # Copyright (C) 2008-2011 The IPython Development Team
16 16 #
17 17 # Distributed under the terms of the BSD License. The full license is in
18 18 # the file COPYING, distributed as part of this software.
19 19 #-----------------------------------------------------------------------------
20 20
21 21 #-----------------------------------------------------------------------------
22 22 # Imports
23 23 #-----------------------------------------------------------------------------
24 24
25 25 from __future__ import with_statement
26 26 import __main__
27 27
28 28 import sys
29 29 try:
30 30 from contextlib import nested
31 31 except:
32 32 from IPython.utils.nested_context import nested
33 33 import warnings
34 34
35 35 from IPython.core import ultratb
36 36 from IPython.frontend.terminal.interactiveshell import TerminalInteractiveShell
37 37 from IPython.frontend.terminal.ipapp import load_default_config
38 38
39 39 from IPython.utils.traitlets import Bool, CBool, Unicode
40 40 from IPython.utils.io import ask_yes_no
41 41
42 42
43 43 #-----------------------------------------------------------------------------
44 44 # Classes and functions
45 45 #-----------------------------------------------------------------------------
46 46
47 47 # This is an additional magic that is exposed in embedded shells.
48 48 def kill_embedded(self,parameter_s=''):
49 49 """%kill_embedded : deactivate for good the current embedded IPython.
50 50
51 51 This function (after asking for confirmation) sets an internal flag so that
52 52 an embedded IPython will never activate again. This is useful to
53 53 permanently disable a shell that is being called inside a loop: once you've
54 54 figured out what you needed from it, you may then kill it and the program
55 55 will then continue to run without the interactive shell interfering again.
56 56 """
57 57
58 58 kill = ask_yes_no("Are you sure you want to kill this embedded instance "
59 59 "(y/n)? [y/N] ",'n')
60 60 if kill:
61 61 self.embedded_active = False
62 62 print "This embedded IPython will not reactivate anymore once you exit."
63 63
64 64
65 65 class InteractiveShellEmbed(TerminalInteractiveShell):
66 66
67 67 dummy_mode = Bool(False)
68 68 exit_msg = Unicode('')
69 69 embedded = CBool(True)
70 70 embedded_active = CBool(True)
71 71 # Like the base class display_banner is not configurable, but here it
72 72 # is True by default.
73 73 display_banner = CBool(True)
74 74
75 75 def __init__(self, config=None, ipython_dir=None, user_ns=None,
76 76 user_module=None, custom_exceptions=((),None),
77 77 usage=None, banner1=None, banner2=None,
78 78 display_banner=None, exit_msg=u'', user_global_ns=None):
79 79
80 80 if user_global_ns is not None:
81 81 warnings.warn("user_global_ns has been replaced by user_module. The\
82 82 parameter will be ignored.", DeprecationWarning)
83 83
84 84 super(InteractiveShellEmbed,self).__init__(
85 85 config=config, ipython_dir=ipython_dir, user_ns=user_ns,
86 86 user_module=user_module, custom_exceptions=custom_exceptions,
87 87 usage=usage, banner1=banner1, banner2=banner2,
88 88 display_banner=display_banner
89 89 )
90 90
91 91 self.exit_msg = exit_msg
92 92 self.define_magic("kill_embedded", kill_embedded)
93 93
94 94 # don't use the ipython crash handler so that user exceptions aren't
95 95 # trapped
96 96 sys.excepthook = ultratb.FormattedTB(color_scheme=self.colors,
97 97 mode=self.xmode,
98 98 call_pdb=self.pdb)
99 99
100 100 def init_sys_modules(self):
101 101 pass
102 102
103 103 def __call__(self, header='', local_ns=None, module=None, dummy=None,
104 104 stack_depth=1, global_ns=None):
105 105 """Activate the interactive interpreter.
106 106
107 __call__(self,header='',local_ns=None,global_ns,dummy=None) -> Start
107 __call__(self,header='',local_ns=None,module=None,dummy=None) -> Start
108 108 the interpreter shell with the given local and global namespaces, and
109 109 optionally print a header string at startup.
110 110
111 111 The shell can be globally activated/deactivated using the
112 set/get_dummy_mode methods. This allows you to turn off a shell used
112 dummy_mode attribute. This allows you to turn off a shell used
113 113 for debugging globally.
114 114
115 115 However, *each* time you call the shell you can override the current
116 116 state of dummy_mode with the optional keyword parameter 'dummy'. For
117 example, if you set dummy mode on with IPShell.set_dummy_mode(1), you
118 can still have a specific call work by making it as IPShell(dummy=0).
119
120 The optional keyword parameter dummy controls whether the call
121 actually does anything.
117 example, if you set dummy mode on with IPShell.dummy_mode = True, you
118 can still have a specific call work by making it as IPShell(dummy=False).
122 119 """
123 120
124 121 # If the user has turned it off, go away
125 122 if not self.embedded_active:
126 123 return
127 124
128 125 # Normal exits from interactive mode set this flag, so the shell can't
129 126 # re-enter (it checks this variable at the start of interactive mode).
130 127 self.exit_now = False
131 128
132 129 # Allow the dummy parameter to override the global __dummy_mode
133 130 if dummy or (dummy != 0 and self.dummy_mode):
134 131 return
135 132
136 133 if self.has_readline:
137 134 self.set_readline_completer()
138 135
139 136 # self.banner is auto computed
140 137 if header:
141 138 self.old_banner2 = self.banner2
142 139 self.banner2 = self.banner2 + '\n' + header + '\n'
143 140 else:
144 141 self.old_banner2 = ''
145 142
146 143 # Call the embedding code with a stack depth of 1 so it can skip over
147 144 # our call and get the original caller's namespaces.
148 145 self.mainloop(local_ns, module, stack_depth=stack_depth, global_ns=global_ns)
149 146
150 147 self.banner2 = self.old_banner2
151 148
152 149 if self.exit_msg is not None:
153 150 print self.exit_msg
154 151
155 152 def mainloop(self, local_ns=None, module=None, stack_depth=0,
156 153 display_banner=None, global_ns=None):
157 154 """Embeds IPython into a running python program.
158 155
159 156 Input:
160 157
161 158 - header: An optional header message can be specified.
162 159
163 - local_ns, global_ns: working namespaces. If given as None, the
164 IPython-initialized one is updated with __main__.__dict__, so that
165 program variables become visible but user-specific configuration
166 remains possible.
160 - local_ns, module: working local namespace (a dict) and module (a
161 module or similar object). If given as None, they are automatically
162 taken from the scope where the shell was called, so that
163 program variables become visible.
167 164
168 165 - stack_depth: specifies how many levels in the stack to go to
169 looking for namespaces (when local_ns and global_ns are None). This
166 looking for namespaces (when local_ns or module is None). This
170 167 allows an intermediate caller to make sure that this function gets
171 168 the namespace from the intended level in the stack. By default (0)
172 169 it will get its locals and globals from the immediate caller.
173 170
174 171 Warning: it's possible to use this in a program which is being run by
175 172 IPython itself (via %run), but some funny things will happen (a few
176 173 globals get overwritten). In the future this will be cleaned up, as
177 174 there is no fundamental reason why it can't work perfectly."""
178 175
179 176 if (global_ns is not None) and (module is None):
180 177 class DummyMod(object):
181 178 """A dummy module object for embedded IPython."""
182 179 pass
183 180 warnings.warn("global_ns is deprecated, use module instead.", DeprecationWarning)
184 181 module = DummyMod()
185 182 module.__dict__ = global_ns
186 183
187 184 # Get locals and globals from caller
188 185 if (local_ns is None or module is None) and self.default_user_namespaces:
189 186 call_frame = sys._getframe(stack_depth).f_back
190 187
191 188 if local_ns is None:
192 189 local_ns = call_frame.f_locals
193 190 if module is None:
194 191 global_ns = call_frame.f_globals
195 192 module = sys.modules[global_ns['__name__']]
196 193
197 194 # Save original namespace and module so we can restore them after
198 195 # embedding; otherwise the shell doesn't shut down correctly.
199 196 orig_user_module = self.user_module
200 197 orig_user_ns = self.user_ns
201 198
202 199 # Update namespaces and fire up interpreter
203 200
204 201 # The global one is easy, we can just throw it in
205 202 if module is not None:
206 203 self.user_module = module
207 204
208 205 # But the user/local one is tricky: ipython needs it to store internal
209 206 # data, but we also need the locals. We'll throw our hidden variables
210 207 # like _ih and get_ipython() into the local namespace, but delete them
211 208 # later.
212 209 if local_ns is not None:
213 210 self.user_ns = local_ns
214 211 self.init_user_ns()
215 212
216 213 # Patch for global embedding to make sure that things don't overwrite
217 214 # user globals accidentally. Thanks to Richard <rxe@renre-europe.com>
218 215 # FIXME. Test this a bit more carefully (the if.. is new)
219 216 # N.B. This can't now ever be called. Not sure what it was for.
220 217 # And now, since it wasn't called in the previous version, I'm
221 218 # commenting out these lines so they can't be called with my new changes
222 219 # --TK, 2011-12-10
223 220 #if local_ns is None and module is None:
224 221 # self.user_global_ns.update(__main__.__dict__)
225 222
226 223 # make sure the tab-completer has the correct frame information, so it
227 224 # actually completes using the frame's locals/globals
228 225 self.set_completer_frame()
229 226
230 227 with nested(self.builtin_trap, self.display_trap):
231 228 self.interact(display_banner=display_banner)
232 229
233 230 # now, purge out the local namespace of IPython's hidden variables.
234 231 if local_ns is not None:
235 232 for name in self.user_ns_hidden:
236 233 local_ns.pop(name, None)
237 234
238 235 # Restore original namespace so shell can shut down when we exit.
239 236 self.user_module = orig_user_module
240 237 self.user_ns = orig_user_ns
241 238
242 239 _embedded_shell = None
243 240
244 241
245 242 def embed(**kwargs):
246 243 """Call this to embed IPython at the current point in your program.
247 244
248 245 The first invocation of this will create an :class:`InteractiveShellEmbed`
249 246 instance and then call it. Consecutive calls just call the already
250 247 created instance.
251 248
252 249 Here is a simple example::
253 250
254 251 from IPython import embed
255 252 a = 10
256 253 b = 20
257 254 embed('First time')
258 255 c = 30
259 256 d = 40
260 257 embed
261 258
262 259 Full customization can be done by passing a :class:`Struct` in as the
263 260 config argument.
264 261 """
265 262 config = kwargs.get('config')
266 263 header = kwargs.pop('header', u'')
267 264 if config is None:
268 265 config = load_default_config()
269 266 config.InteractiveShellEmbed = config.TerminalInteractiveShell
270 267 kwargs['config'] = config
271 268 global _embedded_shell
272 269 if _embedded_shell is None:
273 270 _embedded_shell = InteractiveShellEmbed(**kwargs)
274 271 _embedded_shell(header=header, stack_depth=2)
@@ -1,154 +1,156 b''
1 1 ================================================
2 2 Development version
3 3 ================================================
4 4
5 5 The changes listed here are a brief summary of the substantial work on IPython
6 6 since the 0.11.x release series. For more details, please consult the actual
7 7 source.
8 8
9 9 Main `ipython` branch
10 10 =====================
11 11
12 12
13 13 New features
14 14 ------------
15 15
16 16 .. Expand on this:
17 17 * **HTML Notebook**: A powerful new interface puts IPython in your browser. You
18 18 can start it with the command ``ipython notebook``. See :ref:`the Notebook
19 19 docs <htmlnotebook>` for technical details.
20 20
21 21 * **Tabbed QtConsole**: The QtConsole now supports starting multiple kernels in
22 22 tabs, and has a menubar, so it looks and behaves more like a real application.
23 23 Keyboard enthusiasts can disable the menubar with ctrl-shift-M (:ghpull:`887`).
24 24
25 25 * **Python 3 compatibility**: IPython can now be installed from a single
26 26 codebase on Python 2 and Python 3. The installation process for Python 3
27 27 automatically runs 2to3. The same 'default' profile is now used for
28 28 Python 2 and 3 (the previous version had a separate 'python3' profile).
29 29
30 30 * **PyPy support**: The terminal interface to IPython now runs under
31 31 `PyPy <http://pypy.org/>`_.
32 32
33 33 * **SSH Tunnels**: In 0.11, the :mod:`IPython.parallel` Client could tunnel its
34 34 connections to the Controller via ssh. Now, the QtConsole :ref:`supports
35 35 <ssh_tunnels>` ssh tunneling, as do parallel engines.
36 36
37 37 * **relaxed command-line parsing**: 0.11 was released with overly-strict
38 38 command-line parsing, preventing the ability to specify arguments with spaces,
39 39 e.g. ``ipython --pylab qt`` or ``ipython -c "print 'hi'"``. This has
40 40 been fixed, by using argparse. The new parsing is a strict superset of 0.11, so
41 41 any commands in 0.11 should still work in 0.12.
42 42
43 43 * **HistoryAccessor**: The :class:`~IPython.core.history.HistoryManager` class for
44 44 interacting with your IPython SQLite history database has been split, adding
45 45 a parent :class:`~IPython.core.history.HistoryAccessor` class, so that users can
46 46 write code to access and search their IPython history without being in an IPython
47 47 session (:ghpull:`824`).
48 48
49 49 * **kernel %gui and %pylab**: The ``%gui`` and ``%pylab`` magics have been restored
50 50 to the IPython kernel (e.g. in the qtconsole or notebook). This allows activation
51 51 of pylab-mode, or eventloop integration after starting the kernel, which was
52 52 unavailable in 0.11. Unlike in the terminal, this can be set only once, and
53 53 cannot be changed.
54 54
55 55 * **%config**: A new ``%config`` magic has been added, giving easy access to the
56 56 IPython configuration system at runtime (:ghpull:`923`).
57 57
58 58 * **Standalone Kernel**: ``ipython kernel`` subcommand has been added, to allow
59 59 starting a standalone kernel, that can be used with various frontends.
60 60
61 61 * **Multiline History**: Multiline readline history has been restored to the
62 62 Terminal frontend by default (:ghpull:`838`).
63 63
64 64 * **%store**: The ``%store`` magic from earlier versions has been updated and
65 65 placed in an extension, :ref:`extensions_storemagic`. Add 'storemagic' to ``c.InteractiveShellApp.extensions``
66 66 in ipython_config.py to enable it (:ghpull:`1029`).
67 67
68 68
69 69
70 70 Major Bugs fixed
71 71 ----------------
72 72
73 73 * Simple configuration errors should no longer crash IPython. In 0.11, errors in
74 74 config files, as well as invalid trait values, could crash IPython. Now, such
75 75 errors are reported, and help is displayed.
76 76
77 77 * Certain SyntaxErrors no longer crash IPython (e.g. just typing keywords, such as
78 78 ``return``, ``break``, etc.). See :ghissue:`704`.
79 79
80 80 * IPython path utils, such as :func:`~IPython.utils.path.get_ipython_dir` now check
81 81 for write permissions, so IPython should function on systems where the default
82 82 path resolution might point to a read-only location, such as ``HOMESHARE`` on
83 83 Windows (:ghissue:`669`).
84 84
85 85 * :func:`raw_input` now works in the kernel when multiple frontends are in use. The
86 86 request will be sent to the frontend that made the request, and an exception is
87 87 raised if that frontend does not support stdin requests (e.g. the notebook)
88 88 (:ghissue:`673`).
89 89
90 90 * :mod:`zmq` version detection no longer uses simple lexicographical comparison to
91 91 check minimum version, which prevents 0.11 from working with pyzmq-2.1.10
92 92 (:ghpull:`758`).
93 93
94 94 * A bug in PySide < 1.0.7 caused crashes on OSX when tooltips were shown
95 95 (:ghissue:`711`). these tooltips are now disabled on old PySide (:ghpull:`963`).
96 96
97 97 * IPython no longer crashes when started on recent versions of Python 3 in
98 98 Windows (:ghissue:`737`).
99 99
100 100 * Instances of classes defined interactively can now be pickled (:ghissue:`29`;
101 101 :ghpull:`648`). Note that pickling saves a reference to the class definition,
102 102 so unpickling the instances will only work where the class has been defined.
103 103
104 104 .. * use bullet list
105 105
106 106 Backwards incompatible changes
107 107 ------------------------------
108 108
109 109 * IPython connection information is no longer specified via ip/port directly,
110 110 rather via json connection files. These files are stored in the security
111 111 directory, and enable us to turn on HMAC message authentication by default,
112 112 significantly improving the security of kernels. Various utility functions
113 113 have been added to :mod:`IPython.lib.kernel`, for easier connecting to existing
114 114 kernels.
115 115
116 116 * :class:`~IPython.zmq.kernelmanager.KernelManager` now has one ip, and several port
117 117 traits, rather than several ip/port pair ``_addr`` traits. This better matches the
118 118 rest of the code, where the ip cannot not be set separately for each channel.
119 119
120 120 * Custom prompts are now configured using a new class,
121 121 :class:`~IPython.core.prompts.PromptManager`, which has traits for :attr:`in_template`,
122 122 :attr:`in2_template` (the ``...:`` continuation prompt), :attr:`out_template`
123 123 and :attr:`rewrite_template`. This uses Python's string formatting system, so
124 124 you can use ``{time}`` and ``{cwd}``, although we have preserved the abbreviations
125 125 from previous versions, e.g. ``\#`` (prompt number) and ``\w`` (working
126 126 directory). For the list of available fields, refer to the source of
127 127 :file:`IPython/core/prompts.py`.
128 128
129 129 * The class inheritance of the Launchers in :mod:`IPython.parallel.apps.launcher`
130 130 used by ipcluster has changed, so that trait names are more consistent across
131 131 batch systems. This may require a few renames in your config files, if you
132 132 customized the command-line args for launching controllers and engines. The
133 133 configurable names have also been changed to be clearer that they point to class
134 134 names, and can now be specified by name only, rather than requiring the full
135 135 import path of each class, e.g.::
136 136
137 137 IPClusterEngines.engine_launcher = 'IPython.parallel.apps.launcher.MPIExecEngineSetLauncher'
138 138 IPClusterStart.controller_launcher = 'IPython.parallel.apps.launcher.SSHControllerLauncher'
139 139
140 140 would now be specified as::
141 141
142 142 IPClusterEngines.engine_launcher_class = 'MPIExec'
143 143 IPClusterStart.controller_launcher_class = 'SSH'
144 144
145 145 The full path will still work, and is necessary for using custom launchers not in
146 146 IPython's launcher module.
147 147
148 * For embedding a shell, note that the parameter ``user_global_ns`` has been
149 replaced by ``user_module``, and expects a module-like object, rather than
150 a namespace dict. The ``user_ns`` parameter works the same way as before, and
148 * For embedding a shell, note that the parameters ``user_global_ns`` and ``global_ns``
149 have been deprectated in favour of ``user_module`` and ``module`` respsectively.
150 The new parameters expect a module-like object, rather than a namespace dict.
151 The old parameters remain for backwards compatibility, although ``user_global_ns``
152 is now ignored. The ``user_ns`` parameter works the same way as before, and
151 153 calling :func:`~IPython.frontend.terminal.embed.embed` with no arguments still
152 works the same way.
154 works as before.
153 155
154 156 .. * use bullet list
General Comments 0
You need to be logged in to leave comments. Login now