##// END OF EJS Templates
Backport PR #10207: Fix deactivation of embedded instance....
Thomas Kluyver -
Show More
@@ -1,326 +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.magic import Magics, magics_class, line_magic
16 from IPython.core.magic import Magics, magics_class, line_magic
16 from IPython.core.interactiveshell import DummyMod, InteractiveShell
17 from IPython.core.interactiveshell import DummyMod, InteractiveShell
17 from IPython.terminal.interactiveshell import TerminalInteractiveShell
18 from IPython.terminal.interactiveshell import TerminalInteractiveShell
18 from IPython.terminal.ipapp import load_default_config
19 from IPython.terminal.ipapp import load_default_config
19
20
20 from traitlets import Bool, CBool, Unicode
21 from traitlets import Bool, CBool, Unicode
21 from IPython.utils.io import ask_yes_no
22 from IPython.utils.io import ask_yes_no
22
23
23 class KillEmbeded(Exception):pass
24 class KillEmbeded(Exception):pass
24
25
25 # This is an additional magic that is exposed in embedded shells.
26 # This is an additional magic that is exposed in embedded shells.
26 @magics_class
27 @magics_class
27 class EmbeddedMagics(Magics):
28 class EmbeddedMagics(Magics):
28
29
29 @line_magic
30 @line_magic
31 @magic_arguments.magic_arguments()
32 @magic_arguments.argument('-i', '--instance', action='store_true',
33 help='Kill instance instead of call location')
34 @magic_arguments.argument('-x', '--exit', action='store_true',
35 help='Also exit the current session')
36 @magic_arguments.argument('-y', '--yes', action='store_true',
37 help='Do not ask confirmation')
30 def kill_embedded(self, parameter_s=''):
38 def kill_embedded(self, parameter_s=''):
31 """%kill_embedded : deactivate for good the current embedded IPython.
39 """%kill_embedded : deactivate for good the current embedded IPython
32
40
33 This function (after asking for confirmation) sets an internal flag so
41 This function (after asking for confirmation) sets an internal flag so
34 that an embedded IPython will never activate again. This is useful to
42 that an embedded IPython will never activate again for the given call
35 permanently disable a shell that is being called inside a loop: once
43 location. This is useful to permanently disable a shell that is being
36 you've figured out what you needed from it, you may then kill it and
44 called inside a loop: once you've figured out what you needed from it,
37 the program will then continue to run without the interactive shell
45 you may then kill it and the program will then continue to run without
38 interfering again.
46 the interactive shell interfering again.
47
48
49 Kill Instance Option
50 --------------------
51
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
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``
56 killing an "instance" should work even if it is recreated within a
57 loop.
58
59 .. note::
60
61 This was the default behavior before IPython 5.2
62
39 """
63 """
40
64
41 kill = ask_yes_no("Are you sure you want to kill this embedded instance? [y/N] ",'n')
65 args = magic_arguments.parse_argstring(self.kill_embedded, parameter_s)
42 if kill:
66 print(args)
43 self.shell.embedded_active = False
67 if args.instance:
44 print ("This embedded IPython will not reactivate anymore "
68 # let no ask
45 "once you exit.")
69 if not args.yes:
70 kill = ask_yes_no(
71 "Are you sure you want to kill this embedded instance? [y/N] ", 'n')
72 else:
73 kill = True
74 if kill:
75 self.shell._disable_init_location()
76 print("This embedded IPython instance will not reactivate anymore "
77 "once you exit.")
78 else:
79 if not args.yes:
80 kill = ask_yes_no(
81 "Are you sure you want to kill this embedded call_location? [y/N] ", 'n')
82 else:
83 kill = True
84 if kill:
85 self.shell.embedded_active = False
86 print("This embedded IPython call location will not reactivate anymore "
87 "once you exit.")
88
89 if args.exit:
90 # Ask-exit does not really ask, it just set internals flags to exit
91 # on next loop.
92 self.shell.ask_exit()
46
93
47
94
48 @line_magic
95 @line_magic
49 def exit_raise(self, parameter_s=''):
96 def exit_raise(self, parameter_s=''):
50 """%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.
51
98
52 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
53 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
54 useful to permanently exit a loop that create IPython embed instance.
101 useful to permanently exit a loop that create IPython embed instance.
55 """
102 """
56
103
57 self.shell.should_raise = True
104 self.shell.should_raise = True
58 self.shell.ask_exit()
105 self.shell.ask_exit()
59
106
60
107
61
108
62 class InteractiveShellEmbed(TerminalInteractiveShell):
109 class InteractiveShellEmbed(TerminalInteractiveShell):
63
110
64 dummy_mode = Bool(False)
111 dummy_mode = Bool(False)
65 exit_msg = Unicode('')
112 exit_msg = Unicode('')
66 embedded = CBool(True)
113 embedded = CBool(True)
67 should_raise = CBool(False)
114 should_raise = CBool(False)
68 # 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
69 # is True by default.
116 # is True by default.
70 display_banner = CBool(True)
117 display_banner = CBool(True)
71 exit_msg = Unicode()
118 exit_msg = Unicode()
72
119
73 # When embedding, by default we don't change the terminal title
120 # When embedding, by default we don't change the terminal title
74 term_title = Bool(False,
121 term_title = Bool(False,
75 help="Automatically set the terminal title"
122 help="Automatically set the terminal title"
76 ).tag(config=True)
123 ).tag(config=True)
77
124
78 _inactive_locations = set()
125 _inactive_locations = set()
79
126
80 @property
127 @property
81 def embedded_active(self):
128 def embedded_active(self):
82 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)
131
132 def _disable_init_location(self):
133 """Disable the current Instance creation location"""
134 InteractiveShellEmbed._inactive_locations.add(self._init_location_id)
83
135
84 @embedded_active.setter
136 @embedded_active.setter
85 def embedded_active(self, value):
137 def embedded_active(self, value):
86 if value :
138 if value:
87 if self._call_location_id in InteractiveShellEmbed._inactive_locations:
139 InteractiveShellEmbed._inactive_locations.discard(
88 InteractiveShellEmbed._inactive_locations.remove(self._call_location_id)
140 self._call_location_id)
141 InteractiveShellEmbed._inactive_locations.discard(
142 self._init_location_id)
89 else:
143 else:
90 InteractiveShellEmbed._inactive_locations.add(self._call_location_id)
144 InteractiveShellEmbed._inactive_locations.add(
145 self._call_location_id)
91
146
92 def __init__(self, **kw):
147 def __init__(self, **kw):
93
94
95 if kw.get('user_global_ns', None) is not None:
148 if kw.get('user_global_ns', None) is not None:
96 raise DeprecationWarning("Key word argument `user_global_ns` has been replaced by `user_module` since IPython 4.0.")
149 raise DeprecationWarning(
150 "Key word argument `user_global_ns` has been replaced by `user_module` since IPython 4.0.")
97
151
98 self._call_location_id = kw.pop('_call_location_id', None)
152 clid = kw.pop('_init_location_id', None)
153 if not clid:
154 frame = sys._getframe(1)
155 clid = '%s:%s' % (frame.f_code.co_filename, frame.f_lineno)
156 self._init_location_id = clid
99
157
100 super(InteractiveShellEmbed,self).__init__(**kw)
158 super(InteractiveShellEmbed,self).__init__(**kw)
101
159
102 if not self._call_location_id:
103 frame = sys._getframe(1)
104 self._call_location_id = '%s:%s' % (frame.f_code.co_filename, frame.f_lineno)
105 # 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
106 # trapped
161 # trapped
107 sys.excepthook = ultratb.FormattedTB(color_scheme=self.colors,
162 sys.excepthook = ultratb.FormattedTB(color_scheme=self.colors,
108 mode=self.xmode,
163 mode=self.xmode,
109 call_pdb=self.pdb)
164 call_pdb=self.pdb)
110
165
111 def init_sys_modules(self):
166 def init_sys_modules(self):
167 """
168 Explicitly overwrite :any:`IPython.core.interactiveshell` to do nothing.
169 """
112 pass
170 pass
113
171
114 def init_magics(self):
172 def init_magics(self):
115 super(InteractiveShellEmbed, self).init_magics()
173 super(InteractiveShellEmbed, self).init_magics()
116 self.register_magics(EmbeddedMagics)
174 self.register_magics(EmbeddedMagics)
117
175
118 def __call__(self, header='', local_ns=None, module=None, dummy=None,
176 def __call__(self, header='', local_ns=None, module=None, dummy=None,
119 stack_depth=1, global_ns=None, compile_flags=None):
177 stack_depth=1, global_ns=None, compile_flags=None, **kw):
120 """Activate the interactive interpreter.
178 """Activate the interactive interpreter.
121
179
122 __call__(self,header='',local_ns=None,module=None,dummy=None) -> Start
180 __call__(self,header='',local_ns=None,module=None,dummy=None) -> Start
123 the interpreter shell with the given local and global namespaces, and
181 the interpreter shell with the given local and global namespaces, and
124 optionally print a header string at startup.
182 optionally print a header string at startup.
125
183
126 The shell can be globally activated/deactivated using the
184 The shell can be globally activated/deactivated using the
127 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
128 for debugging globally.
186 for debugging globally.
129
187
130 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
131 state of dummy_mode with the optional keyword parameter 'dummy'. For
189 state of dummy_mode with the optional keyword parameter 'dummy'. For
132 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
133 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).
134 """
192 """
135
193
194 # we are called, set the underlying interactiveshell not to exit.
195 self.keep_running = True
196
136 # 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)
199 if not clid:
200 frame = sys._getframe(1)
201 clid = '%s:%s' % (frame.f_code.co_filename, frame.f_lineno)
202 self._call_location_id = clid
203
137 if not self.embedded_active:
204 if not self.embedded_active:
138 return
205 return
139
206
140 # 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
141 # 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).
142 self.exit_now = False
209 self.exit_now = False
143
210
144 # Allow the dummy parameter to override the global __dummy_mode
211 # Allow the dummy parameter to override the global __dummy_mode
145 if dummy or (dummy != 0 and self.dummy_mode):
212 if dummy or (dummy != 0 and self.dummy_mode):
146 return
213 return
147
214
148 # self.banner is auto computed
215 # self.banner is auto computed
149 if header:
216 if header:
150 self.old_banner2 = self.banner2
217 self.old_banner2 = self.banner2
151 self.banner2 = self.banner2 + '\n' + header + '\n'
218 self.banner2 = self.banner2 + '\n' + header + '\n'
152 else:
219 else:
153 self.old_banner2 = ''
220 self.old_banner2 = ''
154
221
155 if self.display_banner:
222 if self.display_banner:
156 self.show_banner()
223 self.show_banner()
157
224
158 # 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
159 # our call and get the original caller's namespaces.
226 # our call and get the original caller's namespaces.
160 self.mainloop(local_ns, module, stack_depth=stack_depth,
227 self.mainloop(local_ns, module, stack_depth=stack_depth,
161 global_ns=global_ns, compile_flags=compile_flags)
228 global_ns=global_ns, compile_flags=compile_flags)
162
229
163 self.banner2 = self.old_banner2
230 self.banner2 = self.old_banner2
164
231
165 if self.exit_msg is not None:
232 if self.exit_msg is not None:
166 print(self.exit_msg)
233 print(self.exit_msg)
167
234
168 if self.should_raise:
235 if self.should_raise:
169 raise KillEmbeded('Embedded IPython raising error, as user requested.')
236 raise KillEmbeded('Embedded IPython raising error, as user requested.')
170
237
171
238
172 def mainloop(self, local_ns=None, module=None, stack_depth=0,
239 def mainloop(self, local_ns=None, module=None, stack_depth=0,
173 display_banner=None, global_ns=None, compile_flags=None):
240 display_banner=None, global_ns=None, compile_flags=None):
174 """Embeds IPython into a running python program.
241 """Embeds IPython into a running python program.
175
242
176 Parameters
243 Parameters
177 ----------
244 ----------
178
245
179 local_ns, module
246 local_ns, module
180 Working local namespace (a dict) and module (a module or similar
247 Working local namespace (a dict) and module (a module or similar
181 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
182 where the shell was called, so that program variables become visible.
249 where the shell was called, so that program variables become visible.
183
250
184 stack_depth : int
251 stack_depth : int
185 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
186 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
187 make sure that this function gets the namespace from the intended
254 make sure that this function gets the namespace from the intended
188 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
189 from the immediate caller.
256 from the immediate caller.
190
257
191 compile_flags
258 compile_flags
192 A bit field identifying the __future__ features
259 A bit field identifying the __future__ features
193 that are enabled, as passed to the builtin :func:`compile` function.
260 that are enabled, as passed to the builtin :func:`compile` function.
194 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
195 the shell was called.
262 the shell was called.
196
263
197 """
264 """
198
265
199 if (global_ns is not None) and (module is None):
266 if (global_ns is not None) and (module is None):
200 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.")
201
268
202 if (display_banner is not None):
269 if (display_banner is not None):
203 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)
204
271
205 # Get locals and globals from caller
272 # Get locals and globals from caller
206 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)
207 and self.default_user_namespaces):
274 and self.default_user_namespaces):
208 call_frame = sys._getframe(stack_depth).f_back
275 call_frame = sys._getframe(stack_depth).f_back
209
276
210 if local_ns is None:
277 if local_ns is None:
211 local_ns = call_frame.f_locals
278 local_ns = call_frame.f_locals
212 if module is None:
279 if module is None:
213 global_ns = call_frame.f_globals
280 global_ns = call_frame.f_globals
214 try:
281 try:
215 module = sys.modules[global_ns['__name__']]
282 module = sys.modules[global_ns['__name__']]
216 except KeyError:
283 except KeyError:
217 warnings.warn("Failed to get module %s" % \
284 warnings.warn("Failed to get module %s" % \
218 global_ns.get('__name__', 'unknown module')
285 global_ns.get('__name__', 'unknown module')
219 )
286 )
220 module = DummyMod()
287 module = DummyMod()
221 module.__dict__ = global_ns
288 module.__dict__ = global_ns
222 if compile_flags is None:
289 if compile_flags is None:
223 compile_flags = (call_frame.f_code.co_flags &
290 compile_flags = (call_frame.f_code.co_flags &
224 compilerop.PyCF_MASK)
291 compilerop.PyCF_MASK)
225
292
226 # Save original namespace and module so we can restore them after
293 # Save original namespace and module so we can restore them after
227 # embedding; otherwise the shell doesn't shut down correctly.
294 # embedding; otherwise the shell doesn't shut down correctly.
228 orig_user_module = self.user_module
295 orig_user_module = self.user_module
229 orig_user_ns = self.user_ns
296 orig_user_ns = self.user_ns
230 orig_compile_flags = self.compile.flags
297 orig_compile_flags = self.compile.flags
231
298
232 # Update namespaces and fire up interpreter
299 # Update namespaces and fire up interpreter
233
300
234 # The global one is easy, we can just throw it in
301 # The global one is easy, we can just throw it in
235 if module is not None:
302 if module is not None:
236 self.user_module = module
303 self.user_module = module
237
304
238 # 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
239 # 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
240 # 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
241 # later.
308 # later.
242 if local_ns is not None:
309 if local_ns is not None:
243 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()}
244 self.user_ns = reentrant_local_ns
311 self.user_ns = reentrant_local_ns
245 self.init_user_ns()
312 self.init_user_ns()
246
313
247 # Compiler flags
314 # Compiler flags
248 if compile_flags is not None:
315 if compile_flags is not None:
249 self.compile.flags = compile_flags
316 self.compile.flags = compile_flags
250
317
251 # 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
252 # actually completes using the frame's locals/globals
319 # actually completes using the frame's locals/globals
253 self.set_completer_frame()
320 self.set_completer_frame()
254
321
255 with self.builtin_trap, self.display_trap:
322 with self.builtin_trap, self.display_trap:
256 self.interact()
323 self.interact()
257
324
258 # now, purge out the local namespace of IPython's hidden variables.
325 # now, purge out the local namespace of IPython's hidden variables.
259 if local_ns is not None:
326 if local_ns is not None:
260 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()})
261
328
262
329
263 # Restore original namespace so shell can shut down when we exit.
330 # Restore original namespace so shell can shut down when we exit.
264 self.user_module = orig_user_module
331 self.user_module = orig_user_module
265 self.user_ns = orig_user_ns
332 self.user_ns = orig_user_ns
266 self.compile.flags = orig_compile_flags
333 self.compile.flags = orig_compile_flags
267
334
268
335
269 def embed(**kwargs):
336 def embed(**kwargs):
270 """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.
271
338
272 The first invocation of this will create an :class:`InteractiveShellEmbed`
339 The first invocation of this will create an :class:`InteractiveShellEmbed`
273 instance and then call it. Consecutive calls just call the already
340 instance and then call it. Consecutive calls just call the already
274 created instance.
341 created instance.
275
342
276 If you don't want the kernel to initialize the namespace
343 If you don't want the kernel to initialize the namespace
277 from the scope of the surrounding function,
344 from the scope of the surrounding function,
278 and/or you want to load full IPython configuration,
345 and/or you want to load full IPython configuration,
279 you probably want `IPython.start_ipython()` instead.
346 you probably want `IPython.start_ipython()` instead.
280
347
281 Here is a simple example::
348 Here is a simple example::
282
349
283 from IPython import embed
350 from IPython import embed
284 a = 10
351 a = 10
285 b = 20
352 b = 20
286 embed(header='First time')
353 embed(header='First time')
287 c = 30
354 c = 30
288 d = 40
355 d = 40
289 embed()
356 embed()
290
357
291 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
292 config argument.
359 config argument.
293 """
360 """
294 config = kwargs.get('config')
361 config = kwargs.get('config')
295 header = kwargs.pop('header', u'')
362 header = kwargs.pop('header', u'')
296 compile_flags = kwargs.pop('compile_flags', None)
363 compile_flags = kwargs.pop('compile_flags', None)
297 if config is None:
364 if config is None:
298 config = load_default_config()
365 config = load_default_config()
299 config.InteractiveShellEmbed = config.TerminalInteractiveShell
366 config.InteractiveShellEmbed = config.TerminalInteractiveShell
300 kwargs['config'] = config
367 kwargs['config'] = config
301 #save ps1/ps2 if defined
368 #save ps1/ps2 if defined
302 ps1 = None
369 ps1 = None
303 ps2 = None
370 ps2 = None
304 try:
371 try:
305 ps1 = sys.ps1
372 ps1 = sys.ps1
306 ps2 = sys.ps2
373 ps2 = sys.ps2
307 except AttributeError:
374 except AttributeError:
308 pass
375 pass
309 #save previous instance
376 #save previous instance
310 saved_shell_instance = InteractiveShell._instance
377 saved_shell_instance = InteractiveShell._instance
311 if saved_shell_instance is not None:
378 if saved_shell_instance is not None:
312 cls = type(saved_shell_instance)
379 cls = type(saved_shell_instance)
313 cls.clear_instance()
380 cls.clear_instance()
314 frame = sys._getframe(1)
381 frame = sys._getframe(1)
315 shell = InteractiveShellEmbed.instance(_call_location_id='%s:%s' % (frame.f_code.co_filename, frame.f_lineno), **kwargs)
382 shell = InteractiveShellEmbed.instance(_init_location_id='%s:%s' % (
316 shell(header=header, stack_depth=2, compile_flags=compile_flags)
383 frame.f_code.co_filename, frame.f_lineno), **kwargs)
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))
317 InteractiveShellEmbed.clear_instance()
386 InteractiveShellEmbed.clear_instance()
318 #restore previous instance
387 #restore previous instance
319 if saved_shell_instance is not None:
388 if saved_shell_instance is not None:
320 cls = type(saved_shell_instance)
389 cls = type(saved_shell_instance)
321 cls.clear_instance()
390 cls.clear_instance()
322 for subclass in cls._walk_mro():
391 for subclass in cls._walk_mro():
323 subclass._instance = saved_shell_instance
392 subclass._instance = saved_shell_instance
324 if ps1 is not None:
393 if ps1 is not None:
325 sys.ps1 = ps1
394 sys.ps1 = ps1
326 sys.ps2 = ps2
395 sys.ps2 = ps2
@@ -1,230 +1,247 b''
1 ============
1 ============
2 5.x Series
2 5.x Series
3 ============
3 ============
4
4
5
5
6 IPython 5.2
6 IPython 5.2
7 ===========
7 ===========
8
8
9 Remarkable changes and fixes:
9 Remarkable changes and fixes:
10
10
11 * restore IPython's debugger to raise on quit. :ghpull:`10009`
11 * restore IPython's debugger to raise on quit. :ghpull:`10009`
12 * The configuration value ``c.TerminalInteractiveShell.highlighting_style`` can
12 * The configuration value ``c.TerminalInteractiveShell.highlighting_style`` can
13 now directly take a class argument for custom color style. :ghpull:`9848`
13 now directly take a class argument for custom color style. :ghpull:`9848`
14 * Correctly handle matplotlib figures dpi :ghpull:`9868`
14 * Correctly handle matplotlib figures dpi :ghpull:`9868`
15 * Deprecate ``-e`` flag for the ``%notebook`` magic that had no effects.
15 * Deprecate ``-e`` flag for the ``%notebook`` magic that had no effects.
16 :ghpull:`9872`
16 :ghpull:`9872`
17 * You can now press F2 while typing at a terminal prompt to edit the contents
17 * You can now press F2 while typing at a terminal prompt to edit the contents
18 in your favourite terminal editor. Set the :envvar:`EDITOR` environment
18 in your favourite terminal editor. Set the :envvar:`EDITOR` environment
19 variable to pick which editor is used. :ghpull:`9929`
19 variable to pick which editor is used. :ghpull:`9929`
20 * sdists will now only be ``.tar.gz`` as per upstream PyPI requirements.
20 * sdists will now only be ``.tar.gz`` as per upstream PyPI requirements.
21 :ghpull:`9925`
21 :ghpull:`9925`
22 * :any:`IPython.core.debugger` have gained a ``set_trace()`` method for
22 * :any:`IPython.core.debugger` have gained a ``set_trace()`` method for
23 convenience. :ghpull:`9947`
23 convenience. :ghpull:`9947`
24 * The 'smart command mode' added to the debugger in 5.0 was removed, as more
24 * The 'smart command mode' added to the debugger in 5.0 was removed, as more
25 people preferred the previous behaviour. Therefore, debugger commands such as
25 people preferred the previous behaviour. Therefore, debugger commands such as
26 ``c`` will act as debugger commands even when ``c`` is defined as a variable.
26 ``c`` will act as debugger commands even when ``c`` is defined as a variable.
27 :ghpull:`10050`
27 :ghpull:`10050`
28 * Fixes OS X event loop issues at startup, :ghpull:`10150`
28 * Fixes OS X event loop issues at startup, :ghpull:`10150`
29 * Deprecate the ``%autoindent`` magic. :ghpull:`10176`
29 * Deprecate the ``%autoindent`` magic. :ghpull:`10176`
30 * Emit a :any:`DeprecationWarning` when setting the deprecated
30 * Emit a :any:`DeprecationWarning` when setting the deprecated
31 ``limit_to_all`` option of the completer. :ghpull:`10198`
31 ``limit_to_all`` option of the completer. :ghpull:`10198`
32
32
33
33
34 Changes of behavior to :any:`InteractiveShellEmbed`.
35
36 :any:`InteractiveShellEmbed` interactive behavior have changed a bit in between
37 5.1 and 5.2. By default ``%kill_embedded`` magic will prevent further invocation
38 of the current ``call location`` instead of preventing further invocation of
39 the current instance creation location. For most use case this will not change
40 much for you, though previous behavior was confusing and less consistent with
41 previous IPython versions.
42
43 You can now deactivate instances by using ``%kill_embedded --instance`` flag,
44 (or ``-i`` in short). The ``%kill_embedded`` magic also gained a
45 ``--yes``/``-y`` option which skip confirmation step, and ``-x``/``--exit``
46 which also exit the current embedded call without asking for confirmation.
47
48 See :ghpull:`10207`.
49
50
34
51
35 IPython 5.1
52 IPython 5.1
36 ===========
53 ===========
37
54
38 * Broken ``%timeit`` on Python2 due to the use of ``__qualname__``. :ghpull:`9804`
55 * Broken ``%timeit`` on Python2 due to the use of ``__qualname__``. :ghpull:`9804`
39 * Restore ``%gui qt`` to create and return a ``QApplication`` if necessary. :ghpull:`9789`
56 * Restore ``%gui qt`` to create and return a ``QApplication`` if necessary. :ghpull:`9789`
40 * Don't set terminal title by default. :ghpull:`9801`
57 * Don't set terminal title by default. :ghpull:`9801`
41 * Preserve indentation when inserting newlines with ``Ctrl-O``. :ghpull:`9770`
58 * Preserve indentation when inserting newlines with ``Ctrl-O``. :ghpull:`9770`
42 * Restore completion in debugger. :ghpull:`9785`
59 * Restore completion in debugger. :ghpull:`9785`
43 * Deprecate ``IPython.core.debugger.Tracer()`` in favor of simpler, newer, APIs. :ghpull:`9731`
60 * Deprecate ``IPython.core.debugger.Tracer()`` in favor of simpler, newer, APIs. :ghpull:`9731`
44 * Restore ``NoOpContext`` context manager removed by mistake, and add `DeprecationWarning`. :ghpull:`9765`
61 * Restore ``NoOpContext`` context manager removed by mistake, and add `DeprecationWarning`. :ghpull:`9765`
45 * Add option allowing ``Prompt_toolkit`` to use 24bits colors. :ghpull:`9736`
62 * Add option allowing ``Prompt_toolkit`` to use 24bits colors. :ghpull:`9736`
46 * Fix for closing interactive matplotlib windows on OS X. :ghpull:`9854`
63 * Fix for closing interactive matplotlib windows on OS X. :ghpull:`9854`
47 * An embedded interactive shell instance can be used more than once. :ghpull:`9843`
64 * An embedded interactive shell instance can be used more than once. :ghpull:`9843`
48 * More robust check for whether IPython is in a terminal. :ghpull:`9833`
65 * More robust check for whether IPython is in a terminal. :ghpull:`9833`
49 * Better pretty-printing of dicts on PyPy. :ghpull:`9827`
66 * Better pretty-printing of dicts on PyPy. :ghpull:`9827`
50 * Some coloured output now looks better on dark background command prompts in Windows.
67 * Some coloured output now looks better on dark background command prompts in Windows.
51 :ghpull:`9838`
68 :ghpull:`9838`
52 * Improved tab completion of paths on Windows . :ghpull:`9826`
69 * Improved tab completion of paths on Windows . :ghpull:`9826`
53 * Fix tkinter event loop integration on Python 2 with ``future`` installed. :ghpull:`9824`
70 * Fix tkinter event loop integration on Python 2 with ``future`` installed. :ghpull:`9824`
54 * Restore ``Ctrl-\`` as a shortcut to quit IPython.
71 * Restore ``Ctrl-\`` as a shortcut to quit IPython.
55 * Make ``get_ipython()`` accessible when modules are imported by startup files. :ghpull:`9818`
72 * Make ``get_ipython()`` accessible when modules are imported by startup files. :ghpull:`9818`
56 * Add support for running directories containing a ``__main__.py`` file with the
73 * Add support for running directories containing a ``__main__.py`` file with the
57 ``ipython`` command. :ghpull:`9813`
74 ``ipython`` command. :ghpull:`9813`
58
75
59
76
60 True Color feature
77 True Color feature
61 ------------------
78 ------------------
62
79
63 ``prompt_toolkit`` uses pygments styles for syntax highlighting. By default, the
80 ``prompt_toolkit`` uses pygments styles for syntax highlighting. By default, the
64 colors specified in the style are approximated using a standard 256-color
81 colors specified in the style are approximated using a standard 256-color
65 palette. ``prompt_toolkit`` also supports 24bit, a.k.a. "true", a.k.a. 16-million
82 palette. ``prompt_toolkit`` also supports 24bit, a.k.a. "true", a.k.a. 16-million
66 color escape sequences which enable compatible terminals to display the exact
83 color escape sequences which enable compatible terminals to display the exact
67 colors specified instead of an approximation. This true_color option exposes
84 colors specified instead of an approximation. This true_color option exposes
68 that capability in prompt_toolkit to the IPython shell.
85 that capability in prompt_toolkit to the IPython shell.
69
86
70 Here is a good source for the current state of true color support in various
87 Here is a good source for the current state of true color support in various
71 terminal emulators and software projects: https://gist.github.com/XVilka/8346728
88 terminal emulators and software projects: https://gist.github.com/XVilka/8346728
72
89
73
90
74
91
75 IPython 5.0
92 IPython 5.0
76 ===========
93 ===========
77
94
78 Released July 7, 2016
95 Released July 7, 2016
79
96
80 New terminal interface
97 New terminal interface
81 ----------------------
98 ----------------------
82
99
83 IPython 5 features a major upgrade to the terminal interface, bringing live
100 IPython 5 features a major upgrade to the terminal interface, bringing live
84 syntax highlighting as you type, proper multiline editing and multiline paste,
101 syntax highlighting as you type, proper multiline editing and multiline paste,
85 and tab completions that don't clutter up your history.
102 and tab completions that don't clutter up your history.
86
103
87 .. image:: ../_images/ptshell_features.png
104 .. image:: ../_images/ptshell_features.png
88 :alt: New terminal interface features
105 :alt: New terminal interface features
89 :align: center
106 :align: center
90 :target: ../_images/ptshell_features.png
107 :target: ../_images/ptshell_features.png
91
108
92 These features are provided by the Python library `prompt_toolkit
109 These features are provided by the Python library `prompt_toolkit
93 <http://python-prompt-toolkit.readthedocs.io/en/stable/>`__, which replaces
110 <http://python-prompt-toolkit.readthedocs.io/en/stable/>`__, which replaces
94 ``readline`` throughout our terminal interface.
111 ``readline`` throughout our terminal interface.
95
112
96 Relying on this pure-Python, cross platform module also makes it simpler to
113 Relying on this pure-Python, cross platform module also makes it simpler to
97 install IPython. We have removed dependencies on ``pyreadline`` for Windows and
114 install IPython. We have removed dependencies on ``pyreadline`` for Windows and
98 ``gnureadline`` for Mac.
115 ``gnureadline`` for Mac.
99
116
100 Backwards incompatible changes
117 Backwards incompatible changes
101 ------------------------------
118 ------------------------------
102
119
103 - The ``%install_ext`` magic function, deprecated since 4.0, has now been deleted.
120 - The ``%install_ext`` magic function, deprecated since 4.0, has now been deleted.
104 You can distribute and install extensions as packages on PyPI.
121 You can distribute and install extensions as packages on PyPI.
105 - Callbacks registered while an event is being handled will now only be called
122 - Callbacks registered while an event is being handled will now only be called
106 for subsequent events; previously they could be called for the current event.
123 for subsequent events; previously they could be called for the current event.
107 Similarly, callbacks removed while handling an event *will* always get that
124 Similarly, callbacks removed while handling an event *will* always get that
108 event. See :ghissue:`9447` and :ghpull:`9453`.
125 event. See :ghissue:`9447` and :ghpull:`9453`.
109 - Integration with pydb has been removed since pydb development has been stopped
126 - Integration with pydb has been removed since pydb development has been stopped
110 since 2012, and pydb is not installable from PyPI.
127 since 2012, and pydb is not installable from PyPI.
111 - The ``autoedit_syntax`` option has apparently been broken for many years.
128 - The ``autoedit_syntax`` option has apparently been broken for many years.
112 It has been removed.
129 It has been removed.
113
130
114 New terminal interface
131 New terminal interface
115 ~~~~~~~~~~~~~~~~~~~~~~
132 ~~~~~~~~~~~~~~~~~~~~~~
116
133
117 The overhaul of the terminal interface will probably cause a range of minor
134 The overhaul of the terminal interface will probably cause a range of minor
118 issues for existing users.
135 issues for existing users.
119 This is inevitable for such a significant change, and we've done our best to
136 This is inevitable for such a significant change, and we've done our best to
120 minimise these issues.
137 minimise these issues.
121 Some changes that we're aware of, with suggestions on how to handle them:
138 Some changes that we're aware of, with suggestions on how to handle them:
122
139
123 IPython no longer uses readline configuration (``~/.inputrc``). We hope that
140 IPython no longer uses readline configuration (``~/.inputrc``). We hope that
124 the functionality you want (e.g. vi input mode) will be available by configuring
141 the functionality you want (e.g. vi input mode) will be available by configuring
125 IPython directly (see :doc:`/config/options/terminal`).
142 IPython directly (see :doc:`/config/options/terminal`).
126 If something's missing, please file an issue.
143 If something's missing, please file an issue.
127
144
128 The ``PromptManager`` class has been removed, and the prompt machinery simplified.
145 The ``PromptManager`` class has been removed, and the prompt machinery simplified.
129 See :ref:`custom_prompts` to customise prompts with the new machinery.
146 See :ref:`custom_prompts` to customise prompts with the new machinery.
130
147
131 :mod:`IPython.core.debugger` now provides a plainer interface.
148 :mod:`IPython.core.debugger` now provides a plainer interface.
132 :mod:`IPython.terminal.debugger` contains the terminal debugger using
149 :mod:`IPython.terminal.debugger` contains the terminal debugger using
133 prompt_toolkit.
150 prompt_toolkit.
134
151
135 There are new options to configure the colours used in syntax highlighting.
152 There are new options to configure the colours used in syntax highlighting.
136 We have tried to integrate them with our classic ``--colors`` option and
153 We have tried to integrate them with our classic ``--colors`` option and
137 ``%colors`` magic, but there's a mismatch in possibilities, so some configurations
154 ``%colors`` magic, but there's a mismatch in possibilities, so some configurations
138 may produce unexpected results. See :ref:`termcolour` for more information.
155 may produce unexpected results. See :ref:`termcolour` for more information.
139
156
140 The new interface is not compatible with Emacs 'inferior-shell' feature. To
157 The new interface is not compatible with Emacs 'inferior-shell' feature. To
141 continue using this, add the ``--simple-prompt`` flag to the command Emacs
158 continue using this, add the ``--simple-prompt`` flag to the command Emacs
142 runs. This flag disables most IPython features, relying on Emacs to provide
159 runs. This flag disables most IPython features, relying on Emacs to provide
143 things like tab completion.
160 things like tab completion.
144
161
145 Provisional Changes
162 Provisional Changes
146 -------------------
163 -------------------
147
164
148 Provisional changes are experimental functionality that may, or may not, make
165 Provisional changes are experimental functionality that may, or may not, make
149 it into a future version of IPython, and which API may change without warnings.
166 it into a future version of IPython, and which API may change without warnings.
150 Activating these features and using these API are at your own risk, and may have
167 Activating these features and using these API are at your own risk, and may have
151 security implication for your system, especially if used with the Jupyter notebook,
168 security implication for your system, especially if used with the Jupyter notebook,
152
169
153 When running via the Jupyter notebook interfaces, or other compatible client,
170 When running via the Jupyter notebook interfaces, or other compatible client,
154 you can enable rich documentation experimental functionality:
171 you can enable rich documentation experimental functionality:
155
172
156 When the ``docrepr`` package is installed setting the boolean flag
173 When the ``docrepr`` package is installed setting the boolean flag
157 ``InteractiveShell.sphinxify_docstring`` to ``True``, will process the various
174 ``InteractiveShell.sphinxify_docstring`` to ``True``, will process the various
158 object through sphinx before displaying them (see the ``docrepr`` package
175 object through sphinx before displaying them (see the ``docrepr`` package
159 documentation for more information.
176 documentation for more information.
160
177
161 You need to also enable the IPython pager display rich HTML representation
178 You need to also enable the IPython pager display rich HTML representation
162 using the ``InteractiveShell.enable_html_pager`` boolean configuration option.
179 using the ``InteractiveShell.enable_html_pager`` boolean configuration option.
163 As usual you can set these configuration options globally in your configuration
180 As usual you can set these configuration options globally in your configuration
164 files, alternatively you can turn them on dynamically using the following
181 files, alternatively you can turn them on dynamically using the following
165 snippet:
182 snippet:
166
183
167 .. code-block:: python
184 .. code-block:: python
168
185
169 ip = get_ipython()
186 ip = get_ipython()
170 ip.sphinxify_docstring = True
187 ip.sphinxify_docstring = True
171 ip.enable_html_pager = True
188 ip.enable_html_pager = True
172
189
173
190
174 You can test the effect of various combinations of the above configuration in
191 You can test the effect of various combinations of the above configuration in
175 the Jupyter notebook, with things example like :
192 the Jupyter notebook, with things example like :
176
193
177 .. code-block:: ipython
194 .. code-block:: ipython
178
195
179 import numpy as np
196 import numpy as np
180 np.histogram?
197 np.histogram?
181
198
182
199
183 This is part of an effort to make Documentation in Python richer and provide in
200 This is part of an effort to make Documentation in Python richer and provide in
184 the long term if possible dynamic examples that can contain math, images,
201 the long term if possible dynamic examples that can contain math, images,
185 widgets... As stated above this is nightly experimental feature with a lot of
202 widgets... As stated above this is nightly experimental feature with a lot of
186 (fun) problem to solve. We would be happy to get your feedback and expertise on
203 (fun) problem to solve. We would be happy to get your feedback and expertise on
187 it.
204 it.
188
205
189
206
190
207
191 Deprecated Features
208 Deprecated Features
192 -------------------
209 -------------------
193
210
194 Some deprecated features are listed in this section. Don't forget to enable
211 Some deprecated features are listed in this section. Don't forget to enable
195 ``DeprecationWarning`` as an error if you are using IPython in a Continuous
212 ``DeprecationWarning`` as an error if you are using IPython in a Continuous
196 Integration setup or in your testing in general:
213 Integration setup or in your testing in general:
197
214
198 .. code-block:: python
215 .. code-block:: python
199
216
200 import warnings
217 import warnings
201 warnings.filterwarnings('error', '.*', DeprecationWarning, module='yourmodule.*')
218 warnings.filterwarnings('error', '.*', DeprecationWarning, module='yourmodule.*')
202
219
203
220
204 - ``hooks.fix_error_editor`` seems unused and is pending deprecation.
221 - ``hooks.fix_error_editor`` seems unused and is pending deprecation.
205 - `IPython/core/excolors.py:ExceptionColors` is deprecated.
222 - `IPython/core/excolors.py:ExceptionColors` is deprecated.
206 - `IPython.core.InteractiveShell:write()` is deprecated; use `sys.stdout` instead.
223 - `IPython.core.InteractiveShell:write()` is deprecated; use `sys.stdout` instead.
207 - `IPython.core.InteractiveShell:write_err()` is deprecated; use `sys.stderr` instead.
224 - `IPython.core.InteractiveShell:write_err()` is deprecated; use `sys.stderr` instead.
208 - The `formatter` keyword argument to `Inspector.info` in `IPython.core.oinspec` has no effect.
225 - The `formatter` keyword argument to `Inspector.info` in `IPython.core.oinspec` has no effect.
209 - The `global_ns` keyword argument of IPython Embed was deprecated, and has no effect. Use `module` keyword argument instead.
226 - The `global_ns` keyword argument of IPython Embed was deprecated, and has no effect. Use `module` keyword argument instead.
210
227
211
228
212 Known Issues:
229 Known Issues:
213 -------------
230 -------------
214
231
215 - ``<Esc>`` Key does not dismiss the completer and does not clear the current
232 - ``<Esc>`` Key does not dismiss the completer and does not clear the current
216 buffer. This is an on purpose modification due to current technical
233 buffer. This is an on purpose modification due to current technical
217 limitation. Cf :ghpull:`9572`. Escape the control character which is used
234 limitation. Cf :ghpull:`9572`. Escape the control character which is used
218 for other shortcut, and there is no practical way to distinguish. Use Ctr-G
235 for other shortcut, and there is no practical way to distinguish. Use Ctr-G
219 or Ctrl-C as an alternative.
236 or Ctrl-C as an alternative.
220
237
221 - Cannot use ``Shift-Enter`` and ``Ctrl-Enter`` to submit code in terminal. cf
238 - Cannot use ``Shift-Enter`` and ``Ctrl-Enter`` to submit code in terminal. cf
222 :ghissue:`9587` and :ghissue:`9401`. In terminal there is no practical way to
239 :ghissue:`9587` and :ghissue:`9401`. In terminal there is no practical way to
223 distinguish these key sequences from a normal new line return.
240 distinguish these key sequences from a normal new line return.
224
241
225 - ``PageUp`` and ``pageDown`` do not move through completion menu.
242 - ``PageUp`` and ``pageDown`` do not move through completion menu.
226
243
227 - Color styles might not adapt to terminal emulator themes. This will need new
244 - Color styles might not adapt to terminal emulator themes. This will need new
228 version of Pygments to be released, and can be mitigated with custom themes.
245 version of Pygments to be released, and can be mitigated with custom themes.
229
246
230
247
General Comments 0
You need to be logged in to leave comments. Login now