Show More
@@ -1,399 +1,415 b'' | |||||
1 | # encoding: utf-8 |
|
1 | # encoding: utf-8 | |
2 | """ |
|
2 | """ | |
3 | An embedded IPython shell. |
|
3 | An embedded IPython shell. | |
4 | """ |
|
4 | """ | |
5 | # Copyright (c) IPython Development Team. |
|
5 | # Copyright (c) IPython Development Team. | |
6 | # Distributed under the terms of the Modified BSD License. |
|
6 | # Distributed under the terms of the Modified BSD License. | |
7 |
|
7 | |||
8 |
|
8 | |||
9 | import sys |
|
9 | import sys | |
10 | import warnings |
|
10 | import warnings | |
11 |
|
11 | |||
12 | from IPython.core import ultratb, compilerop |
|
12 | from IPython.core import ultratb, compilerop | |
13 | from IPython.core import magic_arguments |
|
13 | from IPython.core import magic_arguments | |
14 | from IPython.core.magic import Magics, magics_class, line_magic |
|
14 | from IPython.core.magic import Magics, magics_class, line_magic | |
15 | from IPython.core.interactiveshell import DummyMod, InteractiveShell |
|
15 | from IPython.core.interactiveshell import DummyMod, InteractiveShell | |
16 | from IPython.terminal.interactiveshell import TerminalInteractiveShell |
|
16 | from IPython.terminal.interactiveshell import TerminalInteractiveShell | |
17 | from IPython.terminal.ipapp import load_default_config |
|
17 | from IPython.terminal.ipapp import load_default_config | |
18 |
|
18 | |||
19 | from traitlets import Bool, CBool, Unicode |
|
19 | from traitlets import Bool, CBool, Unicode | |
20 | from IPython.utils.io import ask_yes_no |
|
20 | from IPython.utils.io import ask_yes_no | |
21 |
|
21 | |||
22 | from typing import Set |
|
22 | from typing import Set | |
23 |
|
23 | |||
24 | class KillEmbedded(Exception):pass |
|
24 | class KillEmbedded(Exception):pass | |
25 |
|
25 | |||
26 | # kept for backward compatibility as IPython 6 was released with |
|
26 | # kept for backward compatibility as IPython 6 was released with | |
27 | # the typo. See https://github.com/ipython/ipython/pull/10706 |
|
27 | # the typo. See https://github.com/ipython/ipython/pull/10706 | |
28 | KillEmbeded = KillEmbedded |
|
28 | KillEmbeded = KillEmbedded | |
29 |
|
29 | |||
30 | # This is an additional magic that is exposed in embedded shells. |
|
30 | # This is an additional magic that is exposed in embedded shells. | |
31 | @magics_class |
|
31 | @magics_class | |
32 | class EmbeddedMagics(Magics): |
|
32 | class EmbeddedMagics(Magics): | |
33 |
|
33 | |||
34 | @line_magic |
|
34 | @line_magic | |
35 | @magic_arguments.magic_arguments() |
|
35 | @magic_arguments.magic_arguments() | |
36 | @magic_arguments.argument('-i', '--instance', action='store_true', |
|
36 | @magic_arguments.argument('-i', '--instance', action='store_true', | |
37 | help='Kill instance instead of call location') |
|
37 | help='Kill instance instead of call location') | |
38 | @magic_arguments.argument('-x', '--exit', action='store_true', |
|
38 | @magic_arguments.argument('-x', '--exit', action='store_true', | |
39 | help='Also exit the current session') |
|
39 | help='Also exit the current session') | |
40 | @magic_arguments.argument('-y', '--yes', action='store_true', |
|
40 | @magic_arguments.argument('-y', '--yes', action='store_true', | |
41 | help='Do not ask confirmation') |
|
41 | help='Do not ask confirmation') | |
42 | def kill_embedded(self, parameter_s=''): |
|
42 | def kill_embedded(self, parameter_s=''): | |
43 | """%kill_embedded : deactivate for good the current embedded IPython |
|
43 | """%kill_embedded : deactivate for good the current embedded IPython | |
44 |
|
44 | |||
45 | This function (after asking for confirmation) sets an internal flag so |
|
45 | This function (after asking for confirmation) sets an internal flag so | |
46 | that an embedded IPython will never activate again for the given call |
|
46 | that an embedded IPython will never activate again for the given call | |
47 | location. This is useful to permanently disable a shell that is being |
|
47 | location. This is useful to permanently disable a shell that is being | |
48 | called inside a loop: once you've figured out what you needed from it, |
|
48 | called inside a loop: once you've figured out what you needed from it, | |
49 | you may then kill it and the program will then continue to run without |
|
49 | you may then kill it and the program will then continue to run without | |
50 | the interactive shell interfering again. |
|
50 | the interactive shell interfering again. | |
51 |
|
51 | |||
52 |
|
52 | |||
53 | Kill Instance Option: |
|
53 | Kill Instance Option: | |
54 |
|
54 | |||
55 | If for some reasons you need to kill the location where the instance |
|
55 | If for some reasons you need to kill the location where the instance | |
56 | is created and not called, for example if you create a single |
|
56 | is created and not called, for example if you create a single | |
57 | instance in one place and debug in many locations, you can use the |
|
57 | instance in one place and debug in many locations, you can use the | |
58 | ``--instance`` option to kill this specific instance. Like for the |
|
58 | ``--instance`` option to kill this specific instance. Like for the | |
59 | ``call location`` killing an "instance" should work even if it is |
|
59 | ``call location`` killing an "instance" should work even if it is | |
60 | recreated within a loop. |
|
60 | recreated within a loop. | |
61 |
|
61 | |||
62 | .. note:: |
|
62 | .. note:: | |
63 |
|
63 | |||
64 | This was the default behavior before IPython 5.2 |
|
64 | This was the default behavior before IPython 5.2 | |
65 |
|
65 | |||
66 | """ |
|
66 | """ | |
67 |
|
67 | |||
68 | args = magic_arguments.parse_argstring(self.kill_embedded, parameter_s) |
|
68 | args = magic_arguments.parse_argstring(self.kill_embedded, parameter_s) | |
69 | print(args) |
|
69 | print(args) | |
70 | if args.instance: |
|
70 | if args.instance: | |
71 | # let no ask |
|
71 | # let no ask | |
72 | if not args.yes: |
|
72 | if not args.yes: | |
73 | kill = ask_yes_no( |
|
73 | kill = ask_yes_no( | |
74 | "Are you sure you want to kill this embedded instance? [y/N] ", 'n') |
|
74 | "Are you sure you want to kill this embedded instance? [y/N] ", 'n') | |
75 | else: |
|
75 | else: | |
76 | kill = True |
|
76 | kill = True | |
77 | if kill: |
|
77 | if kill: | |
78 | self.shell._disable_init_location() |
|
78 | self.shell._disable_init_location() | |
79 | print("This embedded IPython instance will not reactivate anymore " |
|
79 | print("This embedded IPython instance will not reactivate anymore " | |
80 | "once you exit.") |
|
80 | "once you exit.") | |
81 | else: |
|
81 | else: | |
82 | if not args.yes: |
|
82 | if not args.yes: | |
83 | kill = ask_yes_no( |
|
83 | kill = ask_yes_no( | |
84 | "Are you sure you want to kill this embedded call_location? [y/N] ", 'n') |
|
84 | "Are you sure you want to kill this embedded call_location? [y/N] ", 'n') | |
85 | else: |
|
85 | else: | |
86 | kill = True |
|
86 | kill = True | |
87 | if kill: |
|
87 | if kill: | |
88 | self.shell.embedded_active = False |
|
88 | self.shell.embedded_active = False | |
89 | print("This embedded IPython call location will not reactivate anymore " |
|
89 | print("This embedded IPython call location will not reactivate anymore " | |
90 | "once you exit.") |
|
90 | "once you exit.") | |
91 |
|
91 | |||
92 | if args.exit: |
|
92 | if args.exit: | |
93 | # Ask-exit does not really ask, it just set internals flags to exit |
|
93 | # Ask-exit does not really ask, it just set internals flags to exit | |
94 | # on next loop. |
|
94 | # on next loop. | |
95 | self.shell.ask_exit() |
|
95 | self.shell.ask_exit() | |
96 |
|
96 | |||
97 |
|
97 | |||
98 | @line_magic |
|
98 | @line_magic | |
99 | def exit_raise(self, parameter_s=''): |
|
99 | def exit_raise(self, parameter_s=''): | |
100 | """%exit_raise Make the current embedded kernel exit and raise and exception. |
|
100 | """%exit_raise Make the current embedded kernel exit and raise and exception. | |
101 |
|
101 | |||
102 | This function sets an internal flag so that an embedded IPython will |
|
102 | This function sets an internal flag so that an embedded IPython will | |
103 | raise a `IPython.terminal.embed.KillEmbedded` Exception on exit, and then exit the current I. This is |
|
103 | raise a `IPython.terminal.embed.KillEmbedded` Exception on exit, and then exit the current I. This is | |
104 | useful to permanently exit a loop that create IPython embed instance. |
|
104 | useful to permanently exit a loop that create IPython embed instance. | |
105 | """ |
|
105 | """ | |
106 |
|
106 | |||
107 | self.shell.should_raise = True |
|
107 | self.shell.should_raise = True | |
108 | self.shell.ask_exit() |
|
108 | self.shell.ask_exit() | |
109 |
|
109 | |||
110 |
|
110 | |||
|
111 | class _Sentinel: | |||
|
112 | def __init__(self, repr): | |||
|
113 | assert isinstance(repr, str) | |||
|
114 | self.repr = repr | |||
|
115 | ||||
|
116 | def __repr__(self): | |||
|
117 | return repr | |||
|
118 | ||||
111 |
|
119 | |||
112 | class InteractiveShellEmbed(TerminalInteractiveShell): |
|
120 | class InteractiveShellEmbed(TerminalInteractiveShell): | |
113 |
|
121 | |||
114 | dummy_mode = Bool(False) |
|
122 | dummy_mode = Bool(False) | |
115 | exit_msg = Unicode('') |
|
123 | exit_msg = Unicode('') | |
116 | embedded = CBool(True) |
|
124 | embedded = CBool(True) | |
117 | should_raise = CBool(False) |
|
125 | should_raise = CBool(False) | |
118 | # Like the base class display_banner is not configurable, but here it |
|
126 | # Like the base class display_banner is not configurable, but here it | |
119 | # is True by default. |
|
127 | # is True by default. | |
120 | display_banner = CBool(True) |
|
128 | display_banner = CBool(True) | |
121 | exit_msg = Unicode() |
|
129 | exit_msg = Unicode() | |
122 |
|
130 | |||
123 | # When embedding, by default we don't change the terminal title |
|
131 | # When embedding, by default we don't change the terminal title | |
124 | term_title = Bool(False, |
|
132 | term_title = Bool(False, | |
125 | help="Automatically set the terminal title" |
|
133 | help="Automatically set the terminal title" | |
126 | ).tag(config=True) |
|
134 | ).tag(config=True) | |
127 |
|
135 | |||
128 | _inactive_locations: Set[str] = set() |
|
136 | _inactive_locations: Set[str] = set() | |
129 |
|
137 | |||
130 | def _disable_init_location(self): |
|
138 | def _disable_init_location(self): | |
131 | """Disable the current Instance creation location""" |
|
139 | """Disable the current Instance creation location""" | |
132 | InteractiveShellEmbed._inactive_locations.add(self._init_location_id) |
|
140 | InteractiveShellEmbed._inactive_locations.add(self._init_location_id) | |
133 |
|
141 | |||
134 | @property |
|
142 | @property | |
135 | def embedded_active(self): |
|
143 | def embedded_active(self): | |
136 | return (self._call_location_id not in InteractiveShellEmbed._inactive_locations)\ |
|
144 | return (self._call_location_id not in InteractiveShellEmbed._inactive_locations)\ | |
137 | and (self._init_location_id not in InteractiveShellEmbed._inactive_locations) |
|
145 | and (self._init_location_id not in InteractiveShellEmbed._inactive_locations) | |
138 |
|
146 | |||
139 | @embedded_active.setter |
|
147 | @embedded_active.setter | |
140 | def embedded_active(self, value): |
|
148 | def embedded_active(self, value): | |
141 | if value: |
|
149 | if value: | |
142 | InteractiveShellEmbed._inactive_locations.discard( |
|
150 | InteractiveShellEmbed._inactive_locations.discard( | |
143 | self._call_location_id) |
|
151 | self._call_location_id) | |
144 | InteractiveShellEmbed._inactive_locations.discard( |
|
152 | InteractiveShellEmbed._inactive_locations.discard( | |
145 | self._init_location_id) |
|
153 | self._init_location_id) | |
146 | else: |
|
154 | else: | |
147 | InteractiveShellEmbed._inactive_locations.add( |
|
155 | InteractiveShellEmbed._inactive_locations.add( | |
148 | self._call_location_id) |
|
156 | self._call_location_id) | |
149 |
|
157 | |||
150 | def __init__(self, **kw): |
|
158 | def __init__(self, **kw): | |
151 | if kw.get('user_global_ns', None) is not None: |
|
159 | assert ( | |
152 | raise DeprecationWarning( |
|
160 | "user_global_ns" not in kw | |
153 |
|
|
161 | ), "Key word argument `user_global_ns` has been replaced by `user_module` since IPython 4.0." | |
154 |
|
162 | |||
155 | clid = kw.pop('_init_location_id', None) |
|
163 | clid = kw.pop('_init_location_id', None) | |
156 | if not clid: |
|
164 | if not clid: | |
157 | frame = sys._getframe(1) |
|
165 | frame = sys._getframe(1) | |
158 | clid = '%s:%s' % (frame.f_code.co_filename, frame.f_lineno) |
|
166 | clid = '%s:%s' % (frame.f_code.co_filename, frame.f_lineno) | |
159 | self._init_location_id = clid |
|
167 | self._init_location_id = clid | |
160 |
|
168 | |||
161 | super(InteractiveShellEmbed,self).__init__(**kw) |
|
169 | super(InteractiveShellEmbed,self).__init__(**kw) | |
162 |
|
170 | |||
163 | # don't use the ipython crash handler so that user exceptions aren't |
|
171 | # don't use the ipython crash handler so that user exceptions aren't | |
164 | # trapped |
|
172 | # trapped | |
165 | sys.excepthook = ultratb.FormattedTB(color_scheme=self.colors, |
|
173 | sys.excepthook = ultratb.FormattedTB(color_scheme=self.colors, | |
166 | mode=self.xmode, |
|
174 | mode=self.xmode, | |
167 | call_pdb=self.pdb) |
|
175 | call_pdb=self.pdb) | |
168 |
|
176 | |||
169 | def init_sys_modules(self): |
|
177 | def init_sys_modules(self): | |
170 | """ |
|
178 | """ | |
171 | Explicitly overwrite :mod:`IPython.core.interactiveshell` to do nothing. |
|
179 | Explicitly overwrite :mod:`IPython.core.interactiveshell` to do nothing. | |
172 | """ |
|
180 | """ | |
173 | pass |
|
181 | pass | |
174 |
|
182 | |||
175 | def init_magics(self): |
|
183 | def init_magics(self): | |
176 | super(InteractiveShellEmbed, self).init_magics() |
|
184 | super(InteractiveShellEmbed, self).init_magics() | |
177 | self.register_magics(EmbeddedMagics) |
|
185 | self.register_magics(EmbeddedMagics) | |
178 |
|
186 | |||
179 | def __call__(self, header='', local_ns=None, module=None, dummy=None, |
|
187 | def __call__( | |
180 | stack_depth=1, global_ns=None, compile_flags=None, **kw): |
|
188 | self, | |
|
189 | header="", | |||
|
190 | local_ns=None, | |||
|
191 | module=None, | |||
|
192 | dummy=None, | |||
|
193 | stack_depth=1, | |||
|
194 | compile_flags=None, | |||
|
195 | **kw | |||
|
196 | ): | |||
181 | """Activate the interactive interpreter. |
|
197 | """Activate the interactive interpreter. | |
182 |
|
198 | |||
183 | __call__(self,header='',local_ns=None,module=None,dummy=None) -> Start |
|
199 | __call__(self,header='',local_ns=None,module=None,dummy=None) -> Start | |
184 | the interpreter shell with the given local and global namespaces, and |
|
200 | the interpreter shell with the given local and global namespaces, and | |
185 | optionally print a header string at startup. |
|
201 | optionally print a header string at startup. | |
186 |
|
202 | |||
187 | The shell can be globally activated/deactivated using the |
|
203 | The shell can be globally activated/deactivated using the | |
188 | dummy_mode attribute. This allows you to turn off a shell used |
|
204 | dummy_mode attribute. This allows you to turn off a shell used | |
189 | for debugging globally. |
|
205 | for debugging globally. | |
190 |
|
206 | |||
191 | However, *each* time you call the shell you can override the current |
|
207 | However, *each* time you call the shell you can override the current | |
192 | state of dummy_mode with the optional keyword parameter 'dummy'. For |
|
208 | state of dummy_mode with the optional keyword parameter 'dummy'. For | |
193 | example, if you set dummy mode on with IPShell.dummy_mode = True, you |
|
209 | example, if you set dummy mode on with IPShell.dummy_mode = True, you | |
194 | can still have a specific call work by making it as IPShell(dummy=False). |
|
210 | can still have a specific call work by making it as IPShell(dummy=False). | |
195 | """ |
|
211 | """ | |
196 |
|
212 | |||
197 | # we are called, set the underlying interactiveshell not to exit. |
|
213 | # we are called, set the underlying interactiveshell not to exit. | |
198 | self.keep_running = True |
|
214 | self.keep_running = True | |
199 |
|
215 | |||
200 | # If the user has turned it off, go away |
|
216 | # If the user has turned it off, go away | |
201 | clid = kw.pop('_call_location_id', None) |
|
217 | clid = kw.pop('_call_location_id', None) | |
202 | if not clid: |
|
218 | if not clid: | |
203 | frame = sys._getframe(1) |
|
219 | frame = sys._getframe(1) | |
204 | clid = '%s:%s' % (frame.f_code.co_filename, frame.f_lineno) |
|
220 | clid = '%s:%s' % (frame.f_code.co_filename, frame.f_lineno) | |
205 | self._call_location_id = clid |
|
221 | self._call_location_id = clid | |
206 |
|
222 | |||
207 | if not self.embedded_active: |
|
223 | if not self.embedded_active: | |
208 | return |
|
224 | return | |
209 |
|
225 | |||
210 | # Normal exits from interactive mode set this flag, so the shell can't |
|
226 | # Normal exits from interactive mode set this flag, so the shell can't | |
211 | # re-enter (it checks this variable at the start of interactive mode). |
|
227 | # re-enter (it checks this variable at the start of interactive mode). | |
212 | self.exit_now = False |
|
228 | self.exit_now = False | |
213 |
|
229 | |||
214 | # Allow the dummy parameter to override the global __dummy_mode |
|
230 | # Allow the dummy parameter to override the global __dummy_mode | |
215 | if dummy or (dummy != 0 and self.dummy_mode): |
|
231 | if dummy or (dummy != 0 and self.dummy_mode): | |
216 | return |
|
232 | return | |
217 |
|
233 | |||
218 | # self.banner is auto computed |
|
234 | # self.banner is auto computed | |
219 | if header: |
|
235 | if header: | |
220 | self.old_banner2 = self.banner2 |
|
236 | self.old_banner2 = self.banner2 | |
221 | self.banner2 = self.banner2 + '\n' + header + '\n' |
|
237 | self.banner2 = self.banner2 + '\n' + header + '\n' | |
222 | else: |
|
238 | else: | |
223 | self.old_banner2 = '' |
|
239 | self.old_banner2 = '' | |
224 |
|
240 | |||
225 | if self.display_banner: |
|
241 | if self.display_banner: | |
226 | self.show_banner() |
|
242 | self.show_banner() | |
227 |
|
243 | |||
228 | # Call the embedding code with a stack depth of 1 so it can skip over |
|
244 | # Call the embedding code with a stack depth of 1 so it can skip over | |
229 | # our call and get the original caller's namespaces. |
|
245 | # our call and get the original caller's namespaces. | |
230 | self.mainloop(local_ns, module, stack_depth=stack_depth, |
|
246 | self.mainloop( | |
231 |
|
|
247 | local_ns, module, stack_depth=stack_depth, compile_flags=compile_flags | |
|
248 | ) | |||
232 |
|
249 | |||
233 | self.banner2 = self.old_banner2 |
|
250 | self.banner2 = self.old_banner2 | |
234 |
|
251 | |||
235 | if self.exit_msg is not None: |
|
252 | if self.exit_msg is not None: | |
236 | print(self.exit_msg) |
|
253 | print(self.exit_msg) | |
237 |
|
254 | |||
238 | if self.should_raise: |
|
255 | if self.should_raise: | |
239 | raise KillEmbedded('Embedded IPython raising error, as user requested.') |
|
256 | raise KillEmbedded('Embedded IPython raising error, as user requested.') | |
240 |
|
257 | |||
241 |
|
258 | def mainloop( | ||
242 | def mainloop(self, local_ns=None, module=None, stack_depth=0, |
|
259 | self, | |
243 | display_banner=None, global_ns=None, compile_flags=None): |
|
260 | local_ns=None, | |
|
261 | module=None, | |||
|
262 | stack_depth=0, | |||
|
263 | compile_flags=None, | |||
|
264 | ): | |||
244 | """Embeds IPython into a running python program. |
|
265 | """Embeds IPython into a running python program. | |
245 |
|
266 | |||
246 | Parameters |
|
267 | Parameters | |
247 | ---------- |
|
268 | ---------- | |
248 |
|
269 | |||
|
270 | ||||
249 | local_ns, module |
|
271 | local_ns, module | |
250 | Working local namespace (a dict) and module (a module or similar |
|
272 | Working local namespace (a dict) and module (a module or similar | |
251 | object). If given as None, they are automatically taken from the scope |
|
273 | object). If given as None, they are automatically taken from the scope | |
252 | where the shell was called, so that program variables become visible. |
|
274 | where the shell was called, so that program variables become visible. | |
253 |
|
275 | |||
254 | stack_depth : int |
|
276 | stack_depth : int | |
255 | How many levels in the stack to go to looking for namespaces (when |
|
277 | How many levels in the stack to go to looking for namespaces (when | |
256 | local_ns or module is None). This allows an intermediate caller to |
|
278 | local_ns or module is None). This allows an intermediate caller to | |
257 | make sure that this function gets the namespace from the intended |
|
279 | make sure that this function gets the namespace from the intended | |
258 | level in the stack. By default (0) it will get its locals and globals |
|
280 | level in the stack. By default (0) it will get its locals and globals | |
259 | from the immediate caller. |
|
281 | from the immediate caller. | |
260 |
|
282 | |||
261 | compile_flags |
|
283 | compile_flags | |
262 | A bit field identifying the __future__ features |
|
284 | A bit field identifying the __future__ features | |
263 | that are enabled, as passed to the builtin :func:`compile` function. |
|
285 | that are enabled, as passed to the builtin :func:`compile` function. | |
264 | If given as None, they are automatically taken from the scope where |
|
286 | If given as None, they are automatically taken from the scope where | |
265 | the shell was called. |
|
287 | the shell was called. | |
266 |
|
288 | |||
267 | """ |
|
289 | """ | |
268 |
|
290 | |||
269 | if (global_ns is not None) and (module is None): |
|
|||
270 | raise DeprecationWarning("'global_ns' keyword argument is deprecated, and has been removed in IPython 5.0 use `module` keyword argument instead.") |
|
|||
271 |
|
||||
272 | if (display_banner is not None): |
|
|||
273 | warnings.warn("The display_banner parameter is deprecated since IPython 4.0", DeprecationWarning) |
|
|||
274 |
|
||||
275 | # Get locals and globals from caller |
|
291 | # Get locals and globals from caller | |
276 | if ((local_ns is None or module is None or compile_flags is None) |
|
292 | if ((local_ns is None or module is None or compile_flags is None) | |
277 | and self.default_user_namespaces): |
|
293 | and self.default_user_namespaces): | |
278 | call_frame = sys._getframe(stack_depth).f_back |
|
294 | call_frame = sys._getframe(stack_depth).f_back | |
279 |
|
295 | |||
280 | if local_ns is None: |
|
296 | if local_ns is None: | |
281 | local_ns = call_frame.f_locals |
|
297 | local_ns = call_frame.f_locals | |
282 | if module is None: |
|
298 | if module is None: | |
283 | global_ns = call_frame.f_globals |
|
299 | global_ns = call_frame.f_globals | |
284 | try: |
|
300 | try: | |
285 | module = sys.modules[global_ns['__name__']] |
|
301 | module = sys.modules[global_ns['__name__']] | |
286 | except KeyError: |
|
302 | except KeyError: | |
287 | warnings.warn("Failed to get module %s" % \ |
|
303 | warnings.warn("Failed to get module %s" % \ | |
288 | global_ns.get('__name__', 'unknown module') |
|
304 | global_ns.get('__name__', 'unknown module') | |
289 | ) |
|
305 | ) | |
290 | module = DummyMod() |
|
306 | module = DummyMod() | |
291 | module.__dict__ = global_ns |
|
307 | module.__dict__ = global_ns | |
292 | if compile_flags is None: |
|
308 | if compile_flags is None: | |
293 | compile_flags = (call_frame.f_code.co_flags & |
|
309 | compile_flags = (call_frame.f_code.co_flags & | |
294 | compilerop.PyCF_MASK) |
|
310 | compilerop.PyCF_MASK) | |
295 |
|
311 | |||
296 | # Save original namespace and module so we can restore them after |
|
312 | # Save original namespace and module so we can restore them after | |
297 | # embedding; otherwise the shell doesn't shut down correctly. |
|
313 | # embedding; otherwise the shell doesn't shut down correctly. | |
298 | orig_user_module = self.user_module |
|
314 | orig_user_module = self.user_module | |
299 | orig_user_ns = self.user_ns |
|
315 | orig_user_ns = self.user_ns | |
300 | orig_compile_flags = self.compile.flags |
|
316 | orig_compile_flags = self.compile.flags | |
301 |
|
317 | |||
302 | # Update namespaces and fire up interpreter |
|
318 | # Update namespaces and fire up interpreter | |
303 |
|
319 | |||
304 | # The global one is easy, we can just throw it in |
|
320 | # The global one is easy, we can just throw it in | |
305 | if module is not None: |
|
321 | if module is not None: | |
306 | self.user_module = module |
|
322 | self.user_module = module | |
307 |
|
323 | |||
308 | # But the user/local one is tricky: ipython needs it to store internal |
|
324 | # But the user/local one is tricky: ipython needs it to store internal | |
309 | # data, but we also need the locals. We'll throw our hidden variables |
|
325 | # data, but we also need the locals. We'll throw our hidden variables | |
310 | # like _ih and get_ipython() into the local namespace, but delete them |
|
326 | # like _ih and get_ipython() into the local namespace, but delete them | |
311 | # later. |
|
327 | # later. | |
312 | if local_ns is not None: |
|
328 | if local_ns is not None: | |
313 | reentrant_local_ns = {k: v for (k, v) in local_ns.items() if k not in self.user_ns_hidden.keys()} |
|
329 | reentrant_local_ns = {k: v for (k, v) in local_ns.items() if k not in self.user_ns_hidden.keys()} | |
314 | self.user_ns = reentrant_local_ns |
|
330 | self.user_ns = reentrant_local_ns | |
315 | self.init_user_ns() |
|
331 | self.init_user_ns() | |
316 |
|
332 | |||
317 | # Compiler flags |
|
333 | # Compiler flags | |
318 | if compile_flags is not None: |
|
334 | if compile_flags is not None: | |
319 | self.compile.flags = compile_flags |
|
335 | self.compile.flags = compile_flags | |
320 |
|
336 | |||
321 | # make sure the tab-completer has the correct frame information, so it |
|
337 | # make sure the tab-completer has the correct frame information, so it | |
322 | # actually completes using the frame's locals/globals |
|
338 | # actually completes using the frame's locals/globals | |
323 | self.set_completer_frame() |
|
339 | self.set_completer_frame() | |
324 |
|
340 | |||
325 | with self.builtin_trap, self.display_trap: |
|
341 | with self.builtin_trap, self.display_trap: | |
326 | self.interact() |
|
342 | self.interact() | |
327 |
|
343 | |||
328 | # now, purge out the local namespace of IPython's hidden variables. |
|
344 | # now, purge out the local namespace of IPython's hidden variables. | |
329 | if local_ns is not None: |
|
345 | if local_ns is not None: | |
330 | local_ns.update({k: v for (k, v) in self.user_ns.items() if k not in self.user_ns_hidden.keys()}) |
|
346 | local_ns.update({k: v for (k, v) in self.user_ns.items() if k not in self.user_ns_hidden.keys()}) | |
331 |
|
347 | |||
332 |
|
348 | |||
333 | # Restore original namespace so shell can shut down when we exit. |
|
349 | # Restore original namespace so shell can shut down when we exit. | |
334 | self.user_module = orig_user_module |
|
350 | self.user_module = orig_user_module | |
335 | self.user_ns = orig_user_ns |
|
351 | self.user_ns = orig_user_ns | |
336 | self.compile.flags = orig_compile_flags |
|
352 | self.compile.flags = orig_compile_flags | |
337 |
|
353 | |||
338 |
|
354 | |||
339 | def embed(*, header="", compile_flags=None, **kwargs): |
|
355 | def embed(*, header="", compile_flags=None, **kwargs): | |
340 | """Call this to embed IPython at the current point in your program. |
|
356 | """Call this to embed IPython at the current point in your program. | |
341 |
|
357 | |||
342 | The first invocation of this will create an :class:`InteractiveShellEmbed` |
|
358 | The first invocation of this will create an :class:`InteractiveShellEmbed` | |
343 | instance and then call it. Consecutive calls just call the already |
|
359 | instance and then call it. Consecutive calls just call the already | |
344 | created instance. |
|
360 | created instance. | |
345 |
|
361 | |||
346 | If you don't want the kernel to initialize the namespace |
|
362 | If you don't want the kernel to initialize the namespace | |
347 | from the scope of the surrounding function, |
|
363 | from the scope of the surrounding function, | |
348 | and/or you want to load full IPython configuration, |
|
364 | and/or you want to load full IPython configuration, | |
349 | you probably want `IPython.start_ipython()` instead. |
|
365 | you probably want `IPython.start_ipython()` instead. | |
350 |
|
366 | |||
351 | Here is a simple example:: |
|
367 | Here is a simple example:: | |
352 |
|
368 | |||
353 | from IPython import embed |
|
369 | from IPython import embed | |
354 | a = 10 |
|
370 | a = 10 | |
355 | b = 20 |
|
371 | b = 20 | |
356 | embed(header='First time') |
|
372 | embed(header='First time') | |
357 | c = 30 |
|
373 | c = 30 | |
358 | d = 40 |
|
374 | d = 40 | |
359 | embed() |
|
375 | embed() | |
360 |
|
376 | |||
361 | Full customization can be done by passing a :class:`Config` in as the |
|
377 | Full customization can be done by passing a :class:`Config` in as the | |
362 | config argument. |
|
378 | config argument. | |
363 | """ |
|
379 | """ | |
364 | config = kwargs.get('config') |
|
380 | config = kwargs.get('config') | |
365 | if config is None: |
|
381 | if config is None: | |
366 | config = load_default_config() |
|
382 | config = load_default_config() | |
367 | config.InteractiveShellEmbed = config.TerminalInteractiveShell |
|
383 | config.InteractiveShellEmbed = config.TerminalInteractiveShell | |
368 | kwargs['config'] = config |
|
384 | kwargs['config'] = config | |
369 | using = kwargs.get('using', 'sync') |
|
385 | using = kwargs.get('using', 'sync') | |
370 | if using : |
|
386 | if using : | |
371 | kwargs['config'].update({'TerminalInteractiveShell':{'loop_runner':using, 'colors':'NoColor', 'autoawait': using!='sync'}}) |
|
387 | kwargs['config'].update({'TerminalInteractiveShell':{'loop_runner':using, 'colors':'NoColor', 'autoawait': using!='sync'}}) | |
372 | #save ps1/ps2 if defined |
|
388 | #save ps1/ps2 if defined | |
373 | ps1 = None |
|
389 | ps1 = None | |
374 | ps2 = None |
|
390 | ps2 = None | |
375 | try: |
|
391 | try: | |
376 | ps1 = sys.ps1 |
|
392 | ps1 = sys.ps1 | |
377 | ps2 = sys.ps2 |
|
393 | ps2 = sys.ps2 | |
378 | except AttributeError: |
|
394 | except AttributeError: | |
379 | pass |
|
395 | pass | |
380 | #save previous instance |
|
396 | #save previous instance | |
381 | saved_shell_instance = InteractiveShell._instance |
|
397 | saved_shell_instance = InteractiveShell._instance | |
382 | if saved_shell_instance is not None: |
|
398 | if saved_shell_instance is not None: | |
383 | cls = type(saved_shell_instance) |
|
399 | cls = type(saved_shell_instance) | |
384 | cls.clear_instance() |
|
400 | cls.clear_instance() | |
385 | frame = sys._getframe(1) |
|
401 | frame = sys._getframe(1) | |
386 | shell = InteractiveShellEmbed.instance(_init_location_id='%s:%s' % ( |
|
402 | shell = InteractiveShellEmbed.instance(_init_location_id='%s:%s' % ( | |
387 | frame.f_code.co_filename, frame.f_lineno), **kwargs) |
|
403 | frame.f_code.co_filename, frame.f_lineno), **kwargs) | |
388 | shell(header=header, stack_depth=2, compile_flags=compile_flags, |
|
404 | shell(header=header, stack_depth=2, compile_flags=compile_flags, | |
389 | _call_location_id='%s:%s' % (frame.f_code.co_filename, frame.f_lineno)) |
|
405 | _call_location_id='%s:%s' % (frame.f_code.co_filename, frame.f_lineno)) | |
390 | InteractiveShellEmbed.clear_instance() |
|
406 | InteractiveShellEmbed.clear_instance() | |
391 | #restore previous instance |
|
407 | #restore previous instance | |
392 | if saved_shell_instance is not None: |
|
408 | if saved_shell_instance is not None: | |
393 | cls = type(saved_shell_instance) |
|
409 | cls = type(saved_shell_instance) | |
394 | cls.clear_instance() |
|
410 | cls.clear_instance() | |
395 | for subclass in cls._walk_mro(): |
|
411 | for subclass in cls._walk_mro(): | |
396 | subclass._instance = saved_shell_instance |
|
412 | subclass._instance = saved_shell_instance | |
397 | if ps1 is not None: |
|
413 | if ps1 is not None: | |
398 | sys.ps1 = ps1 |
|
414 | sys.ps1 = ps1 | |
399 | sys.ps2 = ps2 |
|
415 | sys.ps2 = ps2 |
General Comments 0
You need to be logged in to leave comments.
Login now