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