##// END OF EJS Templates
embed() doesn't load default config...
muzuiget -
Show More
@@ -1,246 +1,247 b''
1 1 #!/usr/bin/env python
2 2 # encoding: utf-8
3 3 """
4 4 An embedded IPython shell.
5 5
6 6 Authors:
7 7
8 8 * Brian Granger
9 9 * Fernando Perez
10 10
11 11 Notes
12 12 -----
13 13 """
14 14
15 15 #-----------------------------------------------------------------------------
16 16 # Copyright (C) 2008-2009 The IPython Development Team
17 17 #
18 18 # Distributed under the terms of the BSD License. The full license is in
19 19 # the file COPYING, distributed as part of this software.
20 20 #-----------------------------------------------------------------------------
21 21
22 22 #-----------------------------------------------------------------------------
23 23 # Imports
24 24 #-----------------------------------------------------------------------------
25 25
26 26 from __future__ import with_statement
27 27 import __main__
28 28
29 29 import sys
30 30 from contextlib import nested
31 31
32 32 from IPython.core import ultratb
33 33 from IPython.frontend.terminal.interactiveshell import TerminalInteractiveShell
34 34 from IPython.frontend.terminal.ipapp import load_default_config
35 35
36 36 from IPython.utils.traitlets import Bool, Str, CBool, Unicode
37 37 from IPython.utils.io import ask_yes_no
38 38
39 39
40 40 #-----------------------------------------------------------------------------
41 41 # Classes and functions
42 42 #-----------------------------------------------------------------------------
43 43
44 44 # This is an additional magic that is exposed in embedded shells.
45 45 def kill_embedded(self,parameter_s=''):
46 46 """%kill_embedded : deactivate for good the current embedded IPython.
47 47
48 48 This function (after asking for confirmation) sets an internal flag so that
49 49 an embedded IPython will never activate again. This is useful to
50 50 permanently disable a shell that is being called inside a loop: once you've
51 51 figured out what you needed from it, you may then kill it and the program
52 52 will then continue to run without the interactive shell interfering again.
53 53 """
54 54
55 55 kill = ask_yes_no("Are you sure you want to kill this embedded instance "
56 56 "(y/n)? [y/N] ",'n')
57 57 if kill:
58 58 self.embedded_active = False
59 59 print "This embedded IPython will not reactivate anymore once you exit."
60 60
61 61
62 62 class InteractiveShellEmbed(TerminalInteractiveShell):
63 63
64 64 dummy_mode = Bool(False)
65 65 exit_msg = Unicode('')
66 66 embedded = CBool(True)
67 67 embedded_active = CBool(True)
68 68 # Like the base class display_banner is not configurable, but here it
69 69 # is True by default.
70 70 display_banner = CBool(True)
71 71
72 72 def __init__(self, config=None, ipython_dir=None, user_ns=None,
73 73 user_global_ns=None, custom_exceptions=((),None),
74 74 usage=None, banner1=None, banner2=None,
75 75 display_banner=None, exit_msg=u''):
76 76
77 77 super(InteractiveShellEmbed,self).__init__(
78 78 config=config, ipython_dir=ipython_dir, user_ns=user_ns,
79 79 user_global_ns=user_global_ns, custom_exceptions=custom_exceptions,
80 80 usage=usage, banner1=banner1, banner2=banner2,
81 81 display_banner=display_banner
82 82 )
83 83
84 84 self.exit_msg = exit_msg
85 85 self.define_magic("kill_embedded", kill_embedded)
86 86
87 87 # don't use the ipython crash handler so that user exceptions aren't
88 88 # trapped
89 89 sys.excepthook = ultratb.FormattedTB(color_scheme=self.colors,
90 90 mode=self.xmode,
91 91 call_pdb=self.pdb)
92 92
93 93 def init_sys_modules(self):
94 94 pass
95 95
96 96 def __call__(self, header='', local_ns=None, global_ns=None, dummy=None,
97 97 stack_depth=1):
98 98 """Activate the interactive interpreter.
99 99
100 100 __call__(self,header='',local_ns=None,global_ns,dummy=None) -> Start
101 101 the interpreter shell with the given local and global namespaces, and
102 102 optionally print a header string at startup.
103 103
104 104 The shell can be globally activated/deactivated using the
105 105 set/get_dummy_mode methods. This allows you to turn off a shell used
106 106 for debugging globally.
107 107
108 108 However, *each* time you call the shell you can override the current
109 109 state of dummy_mode with the optional keyword parameter 'dummy'. For
110 110 example, if you set dummy mode on with IPShell.set_dummy_mode(1), you
111 111 can still have a specific call work by making it as IPShell(dummy=0).
112 112
113 113 The optional keyword parameter dummy controls whether the call
114 114 actually does anything.
115 115 """
116 116
117 117 # If the user has turned it off, go away
118 118 if not self.embedded_active:
119 119 return
120 120
121 121 # Normal exits from interactive mode set this flag, so the shell can't
122 122 # re-enter (it checks this variable at the start of interactive mode).
123 123 self.exit_now = False
124 124
125 125 # Allow the dummy parameter to override the global __dummy_mode
126 126 if dummy or (dummy != 0 and self.dummy_mode):
127 127 return
128 128
129 129 if self.has_readline:
130 130 self.set_readline_completer()
131 131
132 132 # self.banner is auto computed
133 133 if header:
134 134 self.old_banner2 = self.banner2
135 135 self.banner2 = self.banner2 + '\n' + header + '\n'
136 136 else:
137 137 self.old_banner2 = ''
138 138
139 139 # Call the embedding code with a stack depth of 1 so it can skip over
140 140 # our call and get the original caller's namespaces.
141 141 self.mainloop(local_ns, global_ns, stack_depth=stack_depth)
142 142
143 143 self.banner2 = self.old_banner2
144 144
145 145 if self.exit_msg is not None:
146 146 print self.exit_msg
147 147
148 148 def mainloop(self, local_ns=None, global_ns=None, stack_depth=0,
149 149 display_banner=None):
150 150 """Embeds IPython into a running python program.
151 151
152 152 Input:
153 153
154 154 - header: An optional header message can be specified.
155 155
156 156 - local_ns, global_ns: working namespaces. If given as None, the
157 157 IPython-initialized one is updated with __main__.__dict__, so that
158 158 program variables become visible but user-specific configuration
159 159 remains possible.
160 160
161 161 - stack_depth: specifies how many levels in the stack to go to
162 162 looking for namespaces (when local_ns and global_ns are None). This
163 163 allows an intermediate caller to make sure that this function gets
164 164 the namespace from the intended level in the stack. By default (0)
165 165 it will get its locals and globals from the immediate caller.
166 166
167 167 Warning: it's possible to use this in a program which is being run by
168 168 IPython itself (via %run), but some funny things will happen (a few
169 169 globals get overwritten). In the future this will be cleaned up, as
170 170 there is no fundamental reason why it can't work perfectly."""
171 171
172 172 # Get locals and globals from caller
173 173 if local_ns is None or global_ns is None:
174 174 call_frame = sys._getframe(stack_depth).f_back
175 175
176 176 if local_ns is None:
177 177 local_ns = call_frame.f_locals
178 178 if global_ns is None:
179 179 global_ns = call_frame.f_globals
180 180
181 181 # Update namespaces and fire up interpreter
182 182
183 183 # The global one is easy, we can just throw it in
184 184 self.user_global_ns = global_ns
185 185
186 186 # but the user/local one is tricky: ipython needs it to store internal
187 187 # data, but we also need the locals. We'll copy locals in the user
188 188 # one, but will track what got copied so we can delete them at exit.
189 189 # This is so that a later embedded call doesn't see locals from a
190 190 # previous call (which most likely existed in a separate scope).
191 191 local_varnames = local_ns.keys()
192 192 self.user_ns.update(local_ns)
193 193 #self.user_ns['local_ns'] = local_ns # dbg
194 194
195 195 # Patch for global embedding to make sure that things don't overwrite
196 196 # user globals accidentally. Thanks to Richard <rxe@renre-europe.com>
197 197 # FIXME. Test this a bit more carefully (the if.. is new)
198 198 if local_ns is None and global_ns is None:
199 199 self.user_global_ns.update(__main__.__dict__)
200 200
201 201 # make sure the tab-completer has the correct frame information, so it
202 202 # actually completes using the frame's locals/globals
203 203 self.set_completer_frame()
204 204
205 205 with nested(self.builtin_trap, self.display_trap):
206 206 self.interact(display_banner=display_banner)
207 207
208 208 # now, purge out the user namespace from anything we might have added
209 209 # from the caller's local namespace
210 210 delvar = self.user_ns.pop
211 211 for var in local_varnames:
212 212 delvar(var,None)
213 213
214 214
215 215 _embedded_shell = None
216 216
217 217
218 218 def embed(**kwargs):
219 219 """Call this to embed IPython at the current point in your program.
220 220
221 221 The first invocation of this will create an :class:`InteractiveShellEmbed`
222 222 instance and then call it. Consecutive calls just call the already
223 223 created instance.
224 224
225 225 Here is a simple example::
226 226
227 227 from IPython import embed
228 228 a = 10
229 229 b = 20
230 230 embed('First time')
231 231 c = 30
232 232 d = 40
233 233 embed
234 234
235 235 Full customization can be done by passing a :class:`Struct` in as the
236 236 config argument.
237 237 """
238 238 config = kwargs.get('config')
239 239 header = kwargs.pop('header', u'')
240 240 if config is None:
241 241 config = load_default_config()
242 242 config.InteractiveShellEmbed = config.TerminalInteractiveShell
243 kwargs['config'] = config
243 244 global _embedded_shell
244 245 if _embedded_shell is None:
245 246 _embedded_shell = InteractiveShellEmbed(**kwargs)
246 247 _embedded_shell(header=header, stack_depth=2)
General Comments 0
You need to be logged in to leave comments. Login now