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