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