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