##// END OF EJS Templates
Update docs and error message
Matthias Bussonnier -
Show More
@@ -1,299 +1,298 b''
1 1 # encoding: utf-8
2 2 """
3 3 An embedded IPython shell.
4 4 """
5 5 # Copyright (c) IPython Development Team.
6 6 # Distributed under the terms of the Modified BSD License.
7 7
8 8 from __future__ import with_statement
9 9 from __future__ import print_function
10 10
11 11 import sys
12 12 import warnings
13 13
14 14 from IPython.core import ultratb, compilerop
15 15 from IPython.core.magic import Magics, magics_class, line_magic
16 16 from IPython.core.interactiveshell import DummyMod
17 17 from IPython.core.interactiveshell import InteractiveShell
18 18 from IPython.terminal.interactiveshell import TerminalInteractiveShell
19 19 from IPython.terminal.ipapp import load_default_config
20 20
21 21 from traitlets import Bool, CBool, Unicode
22 22 from IPython.utils.io import ask_yes_no
23 23
24 24 class KillEmbeded(Exception):pass
25 25
26 26 # This is an additional magic that is exposed in embedded shells.
27 27 @magics_class
28 28 class EmbeddedMagics(Magics):
29 29
30 30 @line_magic
31 31 def kill_embedded(self, parameter_s=''):
32 32 """%kill_embedded : deactivate for good the current embedded IPython.
33 33
34 34 This function (after asking for confirmation) sets an internal flag so
35 35 that an embedded IPython will never activate again. This is useful to
36 36 permanently disable a shell that is being called inside a loop: once
37 37 you've figured out what you needed from it, you may then kill it and
38 38 the program will then continue to run without the interactive shell
39 39 interfering again.
40 40 """
41 41
42 42 kill = ask_yes_no("Are you sure you want to kill this embedded instance "
43 43 "(y/n)? [y/N] ",'n')
44 44 if kill:
45 45 self.shell.embedded_active = False
46 46 print ("This embedded IPython will not reactivate anymore "
47 47 "once you exit.")
48 48
49 49
50 50 @line_magic
51 51 def exit_raise(self, parameter_s=''):
52 52 """%exit_raise Make the current embedded kernel exit and raise and exception.
53 53
54 This function (after asking for confirmation) sets an internal flag so
55 that an embedded IPython will raise a `KillEmbeded` Exception on exit.
56 This is useful to permanently exit a loop that create IPython embed
57 instance.
54 This function sets an internal flag so that an embedded IPython will
55 raise a `IPython.terminal.embed.KillEmbeded` Exception on exit, and then exit the current I. This is
56 useful to permanently exit a loop that create IPython embed instance.
58 57 """
59 58
60 59 self.shell.should_raise = True
61 60 self.shell.ask_exit()
62 61
63 62
64 63
65 64 class InteractiveShellEmbed(TerminalInteractiveShell):
66 65
67 66 dummy_mode = Bool(False)
68 67 exit_msg = Unicode('')
69 68 embedded = CBool(True)
70 69 embedded_active = CBool(True)
71 70 should_raise = CBool(False)
72 71 # Like the base class display_banner is not configurable, but here it
73 72 # is True by default.
74 73 display_banner = CBool(True)
75 74 exit_msg = Unicode()
76 75
77 76
78 77 def __init__(self, **kw):
79 78
80 79
81 80 if kw.get('user_global_ns', None) is not None:
82 81 warnings.warn("user_global_ns has been replaced by user_module. The\
83 82 parameter will be ignored, and removed in IPython 5.0", DeprecationWarning)
84 83
85 84 super(InteractiveShellEmbed,self).__init__(**kw)
86 85
87 86 # don't use the ipython crash handler so that user exceptions aren't
88 87 # trapped
89 88 sys.excepthook = ultratb.FormattedTB(color_scheme=self.colors,
90 89 mode=self.xmode,
91 90 call_pdb=self.pdb)
92 91
93 92 def init_sys_modules(self):
94 93 pass
95 94
96 95 def init_magics(self):
97 96 super(InteractiveShellEmbed, self).init_magics()
98 97 self.register_magics(EmbeddedMagics)
99 98
100 99 def __call__(self, header='', local_ns=None, module=None, dummy=None,
101 100 stack_depth=1, global_ns=None, compile_flags=None):
102 101 """Activate the interactive interpreter.
103 102
104 103 __call__(self,header='',local_ns=None,module=None,dummy=None) -> Start
105 104 the interpreter shell with the given local and global namespaces, and
106 105 optionally print a header string at startup.
107 106
108 107 The shell can be globally activated/deactivated using the
109 108 dummy_mode attribute. This allows you to turn off a shell used
110 109 for debugging globally.
111 110
112 111 However, *each* time you call the shell you can override the current
113 112 state of dummy_mode with the optional keyword parameter 'dummy'. For
114 113 example, if you set dummy mode on with IPShell.dummy_mode = True, you
115 114 can still have a specific call work by making it as IPShell(dummy=False).
116 115 """
117 116
118 117 # If the user has turned it off, go away
119 118 if not self.embedded_active:
120 119 return
121 120
122 121 # Normal exits from interactive mode set this flag, so the shell can't
123 122 # re-enter (it checks this variable at the start of interactive mode).
124 123 self.exit_now = False
125 124
126 125 # Allow the dummy parameter to override the global __dummy_mode
127 126 if dummy or (dummy != 0 and self.dummy_mode):
128 127 return
129 128
130 129 if self.has_readline:
131 130 self.set_readline_completer()
132 131
133 132 # self.banner is auto computed
134 133 if header:
135 134 self.old_banner2 = self.banner2
136 135 self.banner2 = self.banner2 + '\n' + header + '\n'
137 136 else:
138 137 self.old_banner2 = ''
139 138
140 139 # Call the embedding code with a stack depth of 1 so it can skip over
141 140 # our call and get the original caller's namespaces.
142 141 self.mainloop(local_ns, module, stack_depth=stack_depth,
143 142 global_ns=global_ns, compile_flags=compile_flags)
144 143
145 144 self.banner2 = self.old_banner2
146 145
147 146 if self.exit_msg is not None:
148 147 print(self.exit_msg)
149 148
150 149 if self.should_raise:
151 raise KillEmbeded('This instance has been marked as must raise on exit.')
150 raise KillEmbeded('Embedded IPython raising error, as user requested.')
152 151
153 152
154 153 def mainloop(self, local_ns=None, module=None, stack_depth=0,
155 154 display_banner=None, global_ns=None, compile_flags=None):
156 155 """Embeds IPython into a running python program.
157 156
158 157 Parameters
159 158 ----------
160 159
161 160 local_ns, module
162 161 Working local namespace (a dict) and module (a module or similar
163 162 object). If given as None, they are automatically taken from the scope
164 163 where the shell was called, so that program variables become visible.
165 164
166 165 stack_depth : int
167 166 How many levels in the stack to go to looking for namespaces (when
168 167 local_ns or module is None). This allows an intermediate caller to
169 168 make sure that this function gets the namespace from the intended
170 169 level in the stack. By default (0) it will get its locals and globals
171 170 from the immediate caller.
172 171
173 172 compile_flags
174 173 A bit field identifying the __future__ features
175 174 that are enabled, as passed to the builtin :func:`compile` function.
176 175 If given as None, they are automatically taken from the scope where
177 176 the shell was called.
178 177
179 178 """
180 179
181 180 if (global_ns is not None) and (module is None):
182 181 warnings.warn("global_ns is deprecated, and will be removed in IPython 5.0 use module instead.", DeprecationWarning)
183 182 module = DummyMod()
184 183 module.__dict__ = global_ns
185 184
186 185 # Get locals and globals from caller
187 186 if ((local_ns is None or module is None or compile_flags is None)
188 187 and self.default_user_namespaces):
189 188 call_frame = sys._getframe(stack_depth).f_back
190 189
191 190 if local_ns is None:
192 191 local_ns = call_frame.f_locals
193 192 if module is None:
194 193 global_ns = call_frame.f_globals
195 194 module = sys.modules[global_ns['__name__']]
196 195 if compile_flags is None:
197 196 compile_flags = (call_frame.f_code.co_flags &
198 197 compilerop.PyCF_MASK)
199 198
200 199 # Save original namespace and module so we can restore them after
201 200 # embedding; otherwise the shell doesn't shut down correctly.
202 201 orig_user_module = self.user_module
203 202 orig_user_ns = self.user_ns
204 203 orig_compile_flags = self.compile.flags
205 204
206 205 # Update namespaces and fire up interpreter
207 206
208 207 # The global one is easy, we can just throw it in
209 208 if module is not None:
210 209 self.user_module = module
211 210
212 211 # But the user/local one is tricky: ipython needs it to store internal
213 212 # data, but we also need the locals. We'll throw our hidden variables
214 213 # like _ih and get_ipython() into the local namespace, but delete them
215 214 # later.
216 215 if local_ns is not None:
217 216 reentrant_local_ns = {k: v for (k, v) in local_ns.items() if k not in self.user_ns_hidden.keys()}
218 217 self.user_ns = reentrant_local_ns
219 218 self.init_user_ns()
220 219
221 220 # Compiler flags
222 221 if compile_flags is not None:
223 222 self.compile.flags = compile_flags
224 223
225 224 # make sure the tab-completer has the correct frame information, so it
226 225 # actually completes using the frame's locals/globals
227 226 self.set_completer_frame()
228 227
229 228 with self.builtin_trap, self.display_trap:
230 229 self.interact(display_banner=display_banner)
231 230
232 231 # now, purge out the local namespace of IPython's hidden variables.
233 232 if local_ns is not None:
234 233 local_ns.update({k: v for (k, v) in self.user_ns.items() if k not in self.user_ns_hidden.keys()})
235 234
236 235
237 236 # Restore original namespace so shell can shut down when we exit.
238 237 self.user_module = orig_user_module
239 238 self.user_ns = orig_user_ns
240 239 self.compile.flags = orig_compile_flags
241 240
242 241
243 242 def embed(**kwargs):
244 243 """Call this to embed IPython at the current point in your program.
245 244
246 245 The first invocation of this will create an :class:`InteractiveShellEmbed`
247 246 instance and then call it. Consecutive calls just call the already
248 247 created instance.
249 248
250 249 If you don't want the kernel to initialize the namespace
251 250 from the scope of the surrounding function,
252 251 and/or you want to load full IPython configuration,
253 252 you probably want `IPython.start_ipython()` instead.
254 253
255 254 Here is a simple example::
256 255
257 256 from IPython import embed
258 257 a = 10
259 258 b = 20
260 259 embed(header='First time')
261 260 c = 30
262 261 d = 40
263 262 embed()
264 263
265 264 Full customization can be done by passing a :class:`Config` in as the
266 265 config argument.
267 266 """
268 267 config = kwargs.get('config')
269 268 header = kwargs.pop('header', u'')
270 269 compile_flags = kwargs.pop('compile_flags', None)
271 270 if config is None:
272 271 config = load_default_config()
273 272 config.InteractiveShellEmbed = config.TerminalInteractiveShell
274 273 kwargs['config'] = config
275 274 #save ps1/ps2 if defined
276 275 ps1 = None
277 276 ps2 = None
278 277 try:
279 278 ps1 = sys.ps1
280 279 ps2 = sys.ps2
281 280 except AttributeError:
282 281 pass
283 282 #save previous instance
284 283 saved_shell_instance = InteractiveShell._instance
285 284 if saved_shell_instance is not None:
286 285 cls = type(saved_shell_instance)
287 286 cls.clear_instance()
288 287 shell = InteractiveShellEmbed.instance(**kwargs)
289 288 shell(header=header, stack_depth=2, compile_flags=compile_flags)
290 289 InteractiveShellEmbed.clear_instance()
291 290 #restore previous instance
292 291 if saved_shell_instance is not None:
293 292 cls = type(saved_shell_instance)
294 293 cls.clear_instance()
295 294 for subclass in cls._walk_mro():
296 295 subclass._instance = saved_shell_instance
297 296 if ps1 is not None:
298 297 sys.ps1 = ps1
299 298 sys.ps2 = ps2
General Comments 0
You need to be logged in to leave comments. Login now