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