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