##// END OF EJS Templates
Merge pull request #9673 from takluyver/rm-colors-force...
Matthias Bussonnier -
r22620:107350a6 merge
parent child Browse files
Show More
@@ -1,3291 +1,3286 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Main IPython class."""
2 """Main IPython class."""
3
3
4 #-----------------------------------------------------------------------------
4 #-----------------------------------------------------------------------------
5 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
5 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
6 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
6 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
7 # Copyright (C) 2008-2011 The IPython Development Team
7 # Copyright (C) 2008-2011 The IPython Development Team
8 #
8 #
9 # Distributed under the terms of the BSD License. The full license is in
9 # Distributed under the terms of the BSD License. The full license is in
10 # the file COPYING, distributed as part of this software.
10 # the file COPYING, distributed as part of this software.
11 #-----------------------------------------------------------------------------
11 #-----------------------------------------------------------------------------
12
12
13 from __future__ import absolute_import, print_function
13 from __future__ import absolute_import, print_function
14
14
15 import __future__
15 import __future__
16 import abc
16 import abc
17 import ast
17 import ast
18 import atexit
18 import atexit
19 import functools
19 import functools
20 import os
20 import os
21 import re
21 import re
22 import runpy
22 import runpy
23 import sys
23 import sys
24 import tempfile
24 import tempfile
25 import traceback
25 import traceback
26 import types
26 import types
27 import subprocess
27 import subprocess
28 import warnings
28 import warnings
29 from io import open as io_open
29 from io import open as io_open
30
30
31 from pickleshare import PickleShareDB
31 from pickleshare import PickleShareDB
32
32
33 from traitlets.config.configurable import SingletonConfigurable
33 from traitlets.config.configurable import SingletonConfigurable
34 from IPython.core import oinspect
34 from IPython.core import oinspect
35 from IPython.core import magic
35 from IPython.core import magic
36 from IPython.core import page
36 from IPython.core import page
37 from IPython.core import prefilter
37 from IPython.core import prefilter
38 from IPython.core import shadowns
38 from IPython.core import shadowns
39 from IPython.core import ultratb
39 from IPython.core import ultratb
40 from IPython.core.alias import Alias, AliasManager
40 from IPython.core.alias import Alias, AliasManager
41 from IPython.core.autocall import ExitAutocall
41 from IPython.core.autocall import ExitAutocall
42 from IPython.core.builtin_trap import BuiltinTrap
42 from IPython.core.builtin_trap import BuiltinTrap
43 from IPython.core.events import EventManager, available_events
43 from IPython.core.events import EventManager, available_events
44 from IPython.core.compilerop import CachingCompiler, check_linecache_ipython
44 from IPython.core.compilerop import CachingCompiler, check_linecache_ipython
45 from IPython.core.debugger import Pdb
45 from IPython.core.debugger import Pdb
46 from IPython.core.display_trap import DisplayTrap
46 from IPython.core.display_trap import DisplayTrap
47 from IPython.core.displayhook import DisplayHook
47 from IPython.core.displayhook import DisplayHook
48 from IPython.core.displaypub import DisplayPublisher
48 from IPython.core.displaypub import DisplayPublisher
49 from IPython.core.error import InputRejected, UsageError
49 from IPython.core.error import InputRejected, UsageError
50 from IPython.core.extensions import ExtensionManager
50 from IPython.core.extensions import ExtensionManager
51 from IPython.core.formatters import DisplayFormatter
51 from IPython.core.formatters import DisplayFormatter
52 from IPython.core.history import HistoryManager
52 from IPython.core.history import HistoryManager
53 from IPython.core.inputsplitter import ESC_MAGIC, ESC_MAGIC2
53 from IPython.core.inputsplitter import ESC_MAGIC, ESC_MAGIC2
54 from IPython.core.logger import Logger
54 from IPython.core.logger import Logger
55 from IPython.core.macro import Macro
55 from IPython.core.macro import Macro
56 from IPython.core.payload import PayloadManager
56 from IPython.core.payload import PayloadManager
57 from IPython.core.prefilter import PrefilterManager
57 from IPython.core.prefilter import PrefilterManager
58 from IPython.core.profiledir import ProfileDir
58 from IPython.core.profiledir import ProfileDir
59 from IPython.core.usage import default_banner
59 from IPython.core.usage import default_banner
60 from IPython.testing.skipdoctest import skip_doctest_py2, skip_doctest
60 from IPython.testing.skipdoctest import skip_doctest_py2, skip_doctest
61 from IPython.utils import PyColorize
61 from IPython.utils import PyColorize
62 from IPython.utils import io
62 from IPython.utils import io
63 from IPython.utils import py3compat
63 from IPython.utils import py3compat
64 from IPython.utils import openpy
64 from IPython.utils import openpy
65 from IPython.utils.contexts import NoOpContext
65 from IPython.utils.contexts import NoOpContext
66 from IPython.utils.decorators import undoc
66 from IPython.utils.decorators import undoc
67 from IPython.utils.io import ask_yes_no
67 from IPython.utils.io import ask_yes_no
68 from IPython.utils.ipstruct import Struct
68 from IPython.utils.ipstruct import Struct
69 from IPython.paths import get_ipython_dir
69 from IPython.paths import get_ipython_dir
70 from IPython.utils.path import get_home_dir, get_py_filename, ensure_dir_exists
70 from IPython.utils.path import get_home_dir, get_py_filename, ensure_dir_exists
71 from IPython.utils.process import system, getoutput
71 from IPython.utils.process import system, getoutput
72 from IPython.utils.py3compat import (builtin_mod, unicode_type, string_types,
72 from IPython.utils.py3compat import (builtin_mod, unicode_type, string_types,
73 with_metaclass, iteritems)
73 with_metaclass, iteritems)
74 from IPython.utils.strdispatch import StrDispatch
74 from IPython.utils.strdispatch import StrDispatch
75 from IPython.utils.syspathcontext import prepended_to_syspath
75 from IPython.utils.syspathcontext import prepended_to_syspath
76 from IPython.utils.text import format_screen, LSString, SList, DollarFormatter
76 from IPython.utils.text import format_screen, LSString, SList, DollarFormatter
77 from IPython.utils.tempdir import TemporaryDirectory
77 from IPython.utils.tempdir import TemporaryDirectory
78 from traitlets import (
78 from traitlets import (
79 Integer, Bool, CaselessStrEnum, Enum, List, Dict, Unicode, Instance, Type,
79 Integer, Bool, CaselessStrEnum, Enum, List, Dict, Unicode, Instance, Type,
80 observe, default,
80 observe, default,
81 )
81 )
82 from warnings import warn
82 from warnings import warn
83 from logging import error
83 from logging import error
84 import IPython.core.hooks
84 import IPython.core.hooks
85
85
86 try:
86 try:
87 import docrepr.sphinxify as sphx
87 import docrepr.sphinxify as sphx
88
88
89 def sphinxify(doc):
89 def sphinxify(doc):
90 with TemporaryDirectory() as dirname:
90 with TemporaryDirectory() as dirname:
91 return {
91 return {
92 'text/html': sphx.sphinxify(doc, dirname),
92 'text/html': sphx.sphinxify(doc, dirname),
93 'text/plain': doc
93 'text/plain': doc
94 }
94 }
95 except ImportError:
95 except ImportError:
96 sphinxify = None
96 sphinxify = None
97
97
98
98
99 class ProvisionalWarning(DeprecationWarning):
99 class ProvisionalWarning(DeprecationWarning):
100 """
100 """
101 Warning class for unstable features
101 Warning class for unstable features
102 """
102 """
103 pass
103 pass
104
104
105 #-----------------------------------------------------------------------------
105 #-----------------------------------------------------------------------------
106 # Globals
106 # Globals
107 #-----------------------------------------------------------------------------
107 #-----------------------------------------------------------------------------
108
108
109 # compiled regexps for autoindent management
109 # compiled regexps for autoindent management
110 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
110 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
111
111
112 #-----------------------------------------------------------------------------
112 #-----------------------------------------------------------------------------
113 # Utilities
113 # Utilities
114 #-----------------------------------------------------------------------------
114 #-----------------------------------------------------------------------------
115
115
116 @undoc
116 @undoc
117 def softspace(file, newvalue):
117 def softspace(file, newvalue):
118 """Copied from code.py, to remove the dependency"""
118 """Copied from code.py, to remove the dependency"""
119
119
120 oldvalue = 0
120 oldvalue = 0
121 try:
121 try:
122 oldvalue = file.softspace
122 oldvalue = file.softspace
123 except AttributeError:
123 except AttributeError:
124 pass
124 pass
125 try:
125 try:
126 file.softspace = newvalue
126 file.softspace = newvalue
127 except (AttributeError, TypeError):
127 except (AttributeError, TypeError):
128 # "attribute-less object" or "read-only attributes"
128 # "attribute-less object" or "read-only attributes"
129 pass
129 pass
130 return oldvalue
130 return oldvalue
131
131
132 @undoc
132 @undoc
133 def no_op(*a, **kw): pass
133 def no_op(*a, **kw): pass
134
134
135
135
136 class SpaceInInput(Exception): pass
136 class SpaceInInput(Exception): pass
137
137
138
138
139 def get_default_colors():
139 def get_default_colors():
140 "DEPRECATED"
140 "DEPRECATED"
141 warn('get_default_color is Deprecated, and is `Neutral` on all platforms.',
141 warn('get_default_color is Deprecated, and is `Neutral` on all platforms.',
142 DeprecationWarning, stacklevel=2)
142 DeprecationWarning, stacklevel=2)
143 return 'Neutral'
143 return 'Neutral'
144
144
145
145
146 class SeparateUnicode(Unicode):
146 class SeparateUnicode(Unicode):
147 r"""A Unicode subclass to validate separate_in, separate_out, etc.
147 r"""A Unicode subclass to validate separate_in, separate_out, etc.
148
148
149 This is a Unicode based trait that converts '0'->'' and ``'\\n'->'\n'``.
149 This is a Unicode based trait that converts '0'->'' and ``'\\n'->'\n'``.
150 """
150 """
151
151
152 def validate(self, obj, value):
152 def validate(self, obj, value):
153 if value == '0': value = ''
153 if value == '0': value = ''
154 value = value.replace('\\n','\n')
154 value = value.replace('\\n','\n')
155 return super(SeparateUnicode, self).validate(obj, value)
155 return super(SeparateUnicode, self).validate(obj, value)
156
156
157
157
158 @undoc
158 @undoc
159 class DummyMod(object):
159 class DummyMod(object):
160 """A dummy module used for IPython's interactive module when
160 """A dummy module used for IPython's interactive module when
161 a namespace must be assigned to the module's __dict__."""
161 a namespace must be assigned to the module's __dict__."""
162 pass
162 pass
163
163
164
164
165 class ExecutionResult(object):
165 class ExecutionResult(object):
166 """The result of a call to :meth:`InteractiveShell.run_cell`
166 """The result of a call to :meth:`InteractiveShell.run_cell`
167
167
168 Stores information about what took place.
168 Stores information about what took place.
169 """
169 """
170 execution_count = None
170 execution_count = None
171 error_before_exec = None
171 error_before_exec = None
172 error_in_exec = None
172 error_in_exec = None
173 result = None
173 result = None
174
174
175 @property
175 @property
176 def success(self):
176 def success(self):
177 return (self.error_before_exec is None) and (self.error_in_exec is None)
177 return (self.error_before_exec is None) and (self.error_in_exec is None)
178
178
179 def raise_error(self):
179 def raise_error(self):
180 """Reraises error if `success` is `False`, otherwise does nothing"""
180 """Reraises error if `success` is `False`, otherwise does nothing"""
181 if self.error_before_exec is not None:
181 if self.error_before_exec is not None:
182 raise self.error_before_exec
182 raise self.error_before_exec
183 if self.error_in_exec is not None:
183 if self.error_in_exec is not None:
184 raise self.error_in_exec
184 raise self.error_in_exec
185
185
186 def __repr__(self):
186 def __repr__(self):
187 return '<%s object at %x, execution_count=%s error_before_exec=%s error_in_exec=%s result=%s>' %\
187 return '<%s object at %x, execution_count=%s error_before_exec=%s error_in_exec=%s result=%s>' %\
188 (self.__class__.__qualname__, id(self), self.execution_count, self.error_before_exec, self.error_in_exec, repr(self.result))
188 (self.__class__.__qualname__, id(self), self.execution_count, self.error_before_exec, self.error_in_exec, repr(self.result))
189
189
190
190
191 class InteractiveShell(SingletonConfigurable):
191 class InteractiveShell(SingletonConfigurable):
192 """An enhanced, interactive shell for Python."""
192 """An enhanced, interactive shell for Python."""
193
193
194 _instance = None
194 _instance = None
195
195
196 ast_transformers = List([], help=
196 ast_transformers = List([], help=
197 """
197 """
198 A list of ast.NodeTransformer subclass instances, which will be applied
198 A list of ast.NodeTransformer subclass instances, which will be applied
199 to user input before code is run.
199 to user input before code is run.
200 """
200 """
201 ).tag(config=True)
201 ).tag(config=True)
202
202
203 autocall = Enum((0,1,2), default_value=0, help=
203 autocall = Enum((0,1,2), default_value=0, help=
204 """
204 """
205 Make IPython automatically call any callable object even if you didn't
205 Make IPython automatically call any callable object even if you didn't
206 type explicit parentheses. For example, 'str 43' becomes 'str(43)'
206 type explicit parentheses. For example, 'str 43' becomes 'str(43)'
207 automatically. The value can be '0' to disable the feature, '1' for
207 automatically. The value can be '0' to disable the feature, '1' for
208 'smart' autocall, where it is not applied if there are no more
208 'smart' autocall, where it is not applied if there are no more
209 arguments on the line, and '2' for 'full' autocall, where all callable
209 arguments on the line, and '2' for 'full' autocall, where all callable
210 objects are automatically called (even if no arguments are present).
210 objects are automatically called (even if no arguments are present).
211 """
211 """
212 ).tag(config=True)
212 ).tag(config=True)
213 # TODO: remove all autoindent logic and put into frontends.
213 # TODO: remove all autoindent logic and put into frontends.
214 # We can't do this yet because even runlines uses the autoindent.
214 # We can't do this yet because even runlines uses the autoindent.
215 autoindent = Bool(True, help=
215 autoindent = Bool(True, help=
216 """
216 """
217 Autoindent IPython code entered interactively.
217 Autoindent IPython code entered interactively.
218 """
218 """
219 ).tag(config=True)
219 ).tag(config=True)
220
220
221 automagic = Bool(True, help=
221 automagic = Bool(True, help=
222 """
222 """
223 Enable magic commands to be called without the leading %.
223 Enable magic commands to be called without the leading %.
224 """
224 """
225 ).tag(config=True)
225 ).tag(config=True)
226
226
227 banner1 = Unicode(default_banner,
227 banner1 = Unicode(default_banner,
228 help="""The part of the banner to be printed before the profile"""
228 help="""The part of the banner to be printed before the profile"""
229 ).tag(config=True)
229 ).tag(config=True)
230 banner2 = Unicode('',
230 banner2 = Unicode('',
231 help="""The part of the banner to be printed after the profile"""
231 help="""The part of the banner to be printed after the profile"""
232 ).tag(config=True)
232 ).tag(config=True)
233
233
234 cache_size = Integer(1000, help=
234 cache_size = Integer(1000, help=
235 """
235 """
236 Set the size of the output cache. The default is 1000, you can
236 Set the size of the output cache. The default is 1000, you can
237 change it permanently in your config file. Setting it to 0 completely
237 change it permanently in your config file. Setting it to 0 completely
238 disables the caching system, and the minimum value accepted is 20 (if
238 disables the caching system, and the minimum value accepted is 20 (if
239 you provide a value less than 20, it is reset to 0 and a warning is
239 you provide a value less than 20, it is reset to 0 and a warning is
240 issued). This limit is defined because otherwise you'll spend more
240 issued). This limit is defined because otherwise you'll spend more
241 time re-flushing a too small cache than working
241 time re-flushing a too small cache than working
242 """
242 """
243 ).tag(config=True)
243 ).tag(config=True)
244 color_info = Bool(True, help=
244 color_info = Bool(True, help=
245 """
245 """
246 Use colors for displaying information about objects. Because this
246 Use colors for displaying information about objects. Because this
247 information is passed through a pager (like 'less'), and some pagers
247 information is passed through a pager (like 'less'), and some pagers
248 get confused with color codes, this capability can be turned off.
248 get confused with color codes, this capability can be turned off.
249 """
249 """
250 ).tag(config=True)
250 ).tag(config=True)
251 colors = CaselessStrEnum(('Neutral', 'NoColor','LightBG','Linux'),
251 colors = CaselessStrEnum(('Neutral', 'NoColor','LightBG','Linux'),
252 default_value='Neutral',
252 default_value='Neutral',
253 help="Set the color scheme (NoColor, Neutral, Linux, or LightBG)."
253 help="Set the color scheme (NoColor, Neutral, Linux, or LightBG)."
254 ).tag(config=True)
254 ).tag(config=True)
255 colors_force = Bool(False, help=
256 """
257 Force use of ANSI color codes, regardless of OS and readline
258 availability.
259 """
260 # FIXME: This is essentially a hack to allow ZMQShell to show colors
261 # without readline on Win32. When the ZMQ formatting system is
262 # refactored, this should be removed.
263 )
264 debug = Bool(False).tag(config=True)
255 debug = Bool(False).tag(config=True)
265 deep_reload = Bool(False, help=
256 deep_reload = Bool(False, help=
266 """
257 """
267 **Deprecated**
258 **Deprecated**
268
259
269 Will be removed in IPython 6.0
260 Will be removed in IPython 6.0
270
261
271 Enable deep (recursive) reloading by default. IPython can use the
262 Enable deep (recursive) reloading by default. IPython can use the
272 deep_reload module which reloads changes in modules recursively (it
263 deep_reload module which reloads changes in modules recursively (it
273 replaces the reload() function, so you don't need to change anything to
264 replaces the reload() function, so you don't need to change anything to
274 use it). `deep_reload` forces a full reload of modules whose code may
265 use it). `deep_reload` forces a full reload of modules whose code may
275 have changed, which the default reload() function does not. When
266 have changed, which the default reload() function does not. When
276 deep_reload is off, IPython will use the normal reload(), but
267 deep_reload is off, IPython will use the normal reload(), but
277 deep_reload will still be available as dreload().
268 deep_reload will still be available as dreload().
278 """
269 """
279 ).tag(config=True)
270 ).tag(config=True)
280 disable_failing_post_execute = Bool(False,
271 disable_failing_post_execute = Bool(False,
281 help="Don't call post-execute functions that have failed in the past."
272 help="Don't call post-execute functions that have failed in the past."
282 ).tag(config=True)
273 ).tag(config=True)
283 display_formatter = Instance(DisplayFormatter, allow_none=True)
274 display_formatter = Instance(DisplayFormatter, allow_none=True)
284 displayhook_class = Type(DisplayHook)
275 displayhook_class = Type(DisplayHook)
285 display_pub_class = Type(DisplayPublisher)
276 display_pub_class = Type(DisplayPublisher)
286
277
287 sphinxify_docstring = Bool(False, help=
278 sphinxify_docstring = Bool(False, help=
288 """
279 """
289 Enables rich html representation of docstrings. (This requires the
280 Enables rich html representation of docstrings. (This requires the
290 docrepr module).
281 docrepr module).
291 """).tag(config=True)
282 """).tag(config=True)
292
283
293 @observe("sphinxify_docstring")
284 @observe("sphinxify_docstring")
294 def _sphinxify_docstring_changed(self, change):
285 def _sphinxify_docstring_changed(self, change):
295 if change['new']:
286 if change['new']:
296 warn("`sphinxify_docstring` is provisional since IPython 5.0 and might change in future versions." , ProvisionalWarning)
287 warn("`sphinxify_docstring` is provisional since IPython 5.0 and might change in future versions." , ProvisionalWarning)
297
288
298 enable_html_pager = Bool(False, help=
289 enable_html_pager = Bool(False, help=
299 """
290 """
300 (Provisional API) enables html representation in mime bundles sent
291 (Provisional API) enables html representation in mime bundles sent
301 to pagers.
292 to pagers.
302 """).tag(config=True)
293 """).tag(config=True)
303
294
304 @observe("enable_html_pager")
295 @observe("enable_html_pager")
305 def _enable_html_pager_changed(self, change):
296 def _enable_html_pager_changed(self, change):
306 if change['new']:
297 if change['new']:
307 warn("`enable_html_pager` is provisional since IPython 5.0 and might change in future versions.", ProvisionalWarning)
298 warn("`enable_html_pager` is provisional since IPython 5.0 and might change in future versions.", ProvisionalWarning)
308
299
309 data_pub_class = None
300 data_pub_class = None
310
301
311 exit_now = Bool(False)
302 exit_now = Bool(False)
312 exiter = Instance(ExitAutocall)
303 exiter = Instance(ExitAutocall)
313 @default('exiter')
304 @default('exiter')
314 def _exiter_default(self):
305 def _exiter_default(self):
315 return ExitAutocall(self)
306 return ExitAutocall(self)
316 # Monotonically increasing execution counter
307 # Monotonically increasing execution counter
317 execution_count = Integer(1)
308 execution_count = Integer(1)
318 filename = Unicode("<ipython console>")
309 filename = Unicode("<ipython console>")
319 ipython_dir= Unicode('').tag(config=True) # Set to get_ipython_dir() in __init__
310 ipython_dir= Unicode('').tag(config=True) # Set to get_ipython_dir() in __init__
320
311
321 # Input splitter, to transform input line by line and detect when a block
312 # Input splitter, to transform input line by line and detect when a block
322 # is ready to be executed.
313 # is ready to be executed.
323 input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
314 input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
324 (), {'line_input_checker': True})
315 (), {'line_input_checker': True})
325
316
326 # This InputSplitter instance is used to transform completed cells before
317 # This InputSplitter instance is used to transform completed cells before
327 # running them. It allows cell magics to contain blank lines.
318 # running them. It allows cell magics to contain blank lines.
328 input_transformer_manager = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
319 input_transformer_manager = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
329 (), {'line_input_checker': False})
320 (), {'line_input_checker': False})
330
321
331 logstart = Bool(False, help=
322 logstart = Bool(False, help=
332 """
323 """
333 Start logging to the default log file in overwrite mode.
324 Start logging to the default log file in overwrite mode.
334 Use `logappend` to specify a log file to **append** logs to.
325 Use `logappend` to specify a log file to **append** logs to.
335 """
326 """
336 ).tag(config=True)
327 ).tag(config=True)
337 logfile = Unicode('', help=
328 logfile = Unicode('', help=
338 """
329 """
339 The name of the logfile to use.
330 The name of the logfile to use.
340 """
331 """
341 ).tag(config=True)
332 ).tag(config=True)
342 logappend = Unicode('', help=
333 logappend = Unicode('', help=
343 """
334 """
344 Start logging to the given file in append mode.
335 Start logging to the given file in append mode.
345 Use `logfile` to specify a log file to **overwrite** logs to.
336 Use `logfile` to specify a log file to **overwrite** logs to.
346 """
337 """
347 ).tag(config=True)
338 ).tag(config=True)
348 object_info_string_level = Enum((0,1,2), default_value=0,
339 object_info_string_level = Enum((0,1,2), default_value=0,
349 ).tag(config=True)
340 ).tag(config=True)
350 pdb = Bool(False, help=
341 pdb = Bool(False, help=
351 """
342 """
352 Automatically call the pdb debugger after every exception.
343 Automatically call the pdb debugger after every exception.
353 """
344 """
354 ).tag(config=True)
345 ).tag(config=True)
355 multiline_history = Bool(sys.platform != 'win32',
346 multiline_history = Bool(sys.platform != 'win32',
356 help="Save multi-line entries as one entry in readline history"
347 help="Save multi-line entries as one entry in readline history"
357 ).tag(config=True)
348 ).tag(config=True)
358 display_page = Bool(False,
349 display_page = Bool(False,
359 help="""If True, anything that would be passed to the pager
350 help="""If True, anything that would be passed to the pager
360 will be displayed as regular output instead."""
351 will be displayed as regular output instead."""
361 ).tag(config=True)
352 ).tag(config=True)
362
353
363 # deprecated prompt traits:
354 # deprecated prompt traits:
364
355
365 prompt_in1 = Unicode('In [\\#]: ',
356 prompt_in1 = Unicode('In [\\#]: ',
366 help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
357 help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
367 ).tag(config=True)
358 ).tag(config=True)
368 prompt_in2 = Unicode(' .\\D.: ',
359 prompt_in2 = Unicode(' .\\D.: ',
369 help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
360 help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
370 ).tag(config=True)
361 ).tag(config=True)
371 prompt_out = Unicode('Out[\\#]: ',
362 prompt_out = Unicode('Out[\\#]: ',
372 help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
363 help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
373 ).tag(config=True)
364 ).tag(config=True)
374 prompts_pad_left = Bool(True,
365 prompts_pad_left = Bool(True,
375 help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
366 help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
376 ).tag(config=True)
367 ).tag(config=True)
377
368
378 @observe('prompt_in1', 'prompt_in2', 'prompt_out', 'prompt_pad_left')
369 @observe('prompt_in1', 'prompt_in2', 'prompt_out', 'prompt_pad_left')
379 def _prompt_trait_changed(self, change):
370 def _prompt_trait_changed(self, change):
380 name = change['name']
371 name = change['name']
381 warn("InteractiveShell.{name} is deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly.".format(
372 warn("InteractiveShell.{name} is deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly.".format(
382 name=name)
373 name=name)
383 )
374 )
384 # protect against weird cases where self.config may not exist:
375 # protect against weird cases where self.config may not exist:
385
376
386 show_rewritten_input = Bool(True,
377 show_rewritten_input = Bool(True,
387 help="Show rewritten input, e.g. for autocall."
378 help="Show rewritten input, e.g. for autocall."
388 ).tag(config=True)
379 ).tag(config=True)
389
380
390 quiet = Bool(False).tag(config=True)
381 quiet = Bool(False).tag(config=True)
391
382
392 history_length = Integer(10000,
383 history_length = Integer(10000,
393 help='Total length of command history'
384 help='Total length of command history'
394 ).tag(config=True)
385 ).tag(config=True)
395
386
396 history_load_length = Integer(1000, help=
387 history_load_length = Integer(1000, help=
397 """
388 """
398 The number of saved history entries to be loaded
389 The number of saved history entries to be loaded
399 into the readline buffer at startup.
390 into the readline buffer at startup.
400 """
391 """
401 ).tag(config=True)
392 ).tag(config=True)
402
393
403 # The readline stuff will eventually be moved to the terminal subclass
394 # The readline stuff will eventually be moved to the terminal subclass
404 # but for now, we can't do that as readline is welded in everywhere.
395 # but for now, we can't do that as readline is welded in everywhere.
405 readline_use = Bool(True).tag(config=True)
396 readline_use = Bool(True).tag(config=True)
406 readline_remove_delims = Unicode('-/~').tag(config=True)
397 readline_remove_delims = Unicode('-/~').tag(config=True)
407 readline_delims = Unicode() # set by init_readline()
398 readline_delims = Unicode() # set by init_readline()
408 # don't use \M- bindings by default, because they
399 # don't use \M- bindings by default, because they
409 # conflict with 8-bit encodings. See gh-58,gh-88
400 # conflict with 8-bit encodings. See gh-58,gh-88
410 readline_parse_and_bind = List([
401 readline_parse_and_bind = List([
411 'tab: complete',
402 'tab: complete',
412 '"\C-l": clear-screen',
403 '"\C-l": clear-screen',
413 'set show-all-if-ambiguous on',
404 'set show-all-if-ambiguous on',
414 '"\C-o": tab-insert',
405 '"\C-o": tab-insert',
415 '"\C-r": reverse-search-history',
406 '"\C-r": reverse-search-history',
416 '"\C-s": forward-search-history',
407 '"\C-s": forward-search-history',
417 '"\C-p": history-search-backward',
408 '"\C-p": history-search-backward',
418 '"\C-n": history-search-forward',
409 '"\C-n": history-search-forward',
419 '"\e[A": history-search-backward',
410 '"\e[A": history-search-backward',
420 '"\e[B": history-search-forward',
411 '"\e[B": history-search-forward',
421 '"\C-k": kill-line',
412 '"\C-k": kill-line',
422 '"\C-u": unix-line-discard',
413 '"\C-u": unix-line-discard',
423 ]).tag(config=True)
414 ]).tag(config=True)
424
415
425 _custom_readline_config = False
416 _custom_readline_config = False
426
417
427 @observe('readline_parse_and_bind')
418 @observe('readline_parse_and_bind')
428 def _readline_parse_and_bind_changed(self, change):
419 def _readline_parse_and_bind_changed(self, change):
429 # notice that readline config is customized
420 # notice that readline config is customized
430 # indicates that it should have higher priority than inputrc
421 # indicates that it should have higher priority than inputrc
431 self._custom_readline_config = True
422 self._custom_readline_config = True
432
423
433 ast_node_interactivity = Enum(['all', 'last', 'last_expr', 'none'],
424 ast_node_interactivity = Enum(['all', 'last', 'last_expr', 'none'],
434 default_value='last_expr',
425 default_value='last_expr',
435 help="""
426 help="""
436 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
427 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
437 run interactively (displaying output from expressions)."""
428 run interactively (displaying output from expressions)."""
438 ).tag(config=True)
429 ).tag(config=True)
439
430
440 # TODO: this part of prompt management should be moved to the frontends.
431 # TODO: this part of prompt management should be moved to the frontends.
441 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
432 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
442 separate_in = SeparateUnicode('\n').tag(config=True)
433 separate_in = SeparateUnicode('\n').tag(config=True)
443 separate_out = SeparateUnicode('').tag(config=True)
434 separate_out = SeparateUnicode('').tag(config=True)
444 separate_out2 = SeparateUnicode('').tag(config=True)
435 separate_out2 = SeparateUnicode('').tag(config=True)
445 wildcards_case_sensitive = Bool(True).tag(config=True)
436 wildcards_case_sensitive = Bool(True).tag(config=True)
446 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
437 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
447 default_value='Context').tag(config=True)
438 default_value='Context').tag(config=True)
448
439
449 # Subcomponents of InteractiveShell
440 # Subcomponents of InteractiveShell
450 alias_manager = Instance('IPython.core.alias.AliasManager', allow_none=True)
441 alias_manager = Instance('IPython.core.alias.AliasManager', allow_none=True)
451 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager', allow_none=True)
442 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager', allow_none=True)
452 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap', allow_none=True)
443 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap', allow_none=True)
453 display_trap = Instance('IPython.core.display_trap.DisplayTrap', allow_none=True)
444 display_trap = Instance('IPython.core.display_trap.DisplayTrap', allow_none=True)
454 extension_manager = Instance('IPython.core.extensions.ExtensionManager', allow_none=True)
445 extension_manager = Instance('IPython.core.extensions.ExtensionManager', allow_none=True)
455 payload_manager = Instance('IPython.core.payload.PayloadManager', allow_none=True)
446 payload_manager = Instance('IPython.core.payload.PayloadManager', allow_none=True)
456 history_manager = Instance('IPython.core.history.HistoryAccessorBase', allow_none=True)
447 history_manager = Instance('IPython.core.history.HistoryAccessorBase', allow_none=True)
457 magics_manager = Instance('IPython.core.magic.MagicsManager', allow_none=True)
448 magics_manager = Instance('IPython.core.magic.MagicsManager', allow_none=True)
458
449
459 profile_dir = Instance('IPython.core.application.ProfileDir', allow_none=True)
450 profile_dir = Instance('IPython.core.application.ProfileDir', allow_none=True)
460 @property
451 @property
461 def profile(self):
452 def profile(self):
462 if self.profile_dir is not None:
453 if self.profile_dir is not None:
463 name = os.path.basename(self.profile_dir.location)
454 name = os.path.basename(self.profile_dir.location)
464 return name.replace('profile_','')
455 return name.replace('profile_','')
465
456
466
457
467 # Private interface
458 # Private interface
468 _post_execute = Dict()
459 _post_execute = Dict()
469
460
470 # Tracks any GUI loop loaded for pylab
461 # Tracks any GUI loop loaded for pylab
471 pylab_gui_select = None
462 pylab_gui_select = None
472
463
473 last_execution_succeeded = Bool(True, help='Did last executed command succeeded')
464 last_execution_succeeded = Bool(True, help='Did last executed command succeeded')
474
465
475 def __init__(self, ipython_dir=None, profile_dir=None,
466 def __init__(self, ipython_dir=None, profile_dir=None,
476 user_module=None, user_ns=None,
467 user_module=None, user_ns=None,
477 custom_exceptions=((), None), **kwargs):
468 custom_exceptions=((), None), **kwargs):
478
469
479 # This is where traits with a config_key argument are updated
470 # This is where traits with a config_key argument are updated
480 # from the values on config.
471 # from the values on config.
481 super(InteractiveShell, self).__init__(**kwargs)
472 super(InteractiveShell, self).__init__(**kwargs)
482 if 'PromptManager' in self.config:
473 if 'PromptManager' in self.config:
483 warn('As of IPython 5.0 `PromptManager` config will have no effect'
474 warn('As of IPython 5.0 `PromptManager` config will have no effect'
484 ' and has been replaced by TerminalInteractiveShell.prompts_class')
475 ' and has been replaced by TerminalInteractiveShell.prompts_class')
485 self.configurables = [self]
476 self.configurables = [self]
486
477
487 # These are relatively independent and stateless
478 # These are relatively independent and stateless
488 self.init_ipython_dir(ipython_dir)
479 self.init_ipython_dir(ipython_dir)
489 self.init_profile_dir(profile_dir)
480 self.init_profile_dir(profile_dir)
490 self.init_instance_attrs()
481 self.init_instance_attrs()
491 self.init_environment()
482 self.init_environment()
492
483
493 # Check if we're in a virtualenv, and set up sys.path.
484 # Check if we're in a virtualenv, and set up sys.path.
494 self.init_virtualenv()
485 self.init_virtualenv()
495
486
496 # Create namespaces (user_ns, user_global_ns, etc.)
487 # Create namespaces (user_ns, user_global_ns, etc.)
497 self.init_create_namespaces(user_module, user_ns)
488 self.init_create_namespaces(user_module, user_ns)
498 # This has to be done after init_create_namespaces because it uses
489 # This has to be done after init_create_namespaces because it uses
499 # something in self.user_ns, but before init_sys_modules, which
490 # something in self.user_ns, but before init_sys_modules, which
500 # is the first thing to modify sys.
491 # is the first thing to modify sys.
501 # TODO: When we override sys.stdout and sys.stderr before this class
492 # TODO: When we override sys.stdout and sys.stderr before this class
502 # is created, we are saving the overridden ones here. Not sure if this
493 # is created, we are saving the overridden ones here. Not sure if this
503 # is what we want to do.
494 # is what we want to do.
504 self.save_sys_module_state()
495 self.save_sys_module_state()
505 self.init_sys_modules()
496 self.init_sys_modules()
506
497
507 # While we're trying to have each part of the code directly access what
498 # While we're trying to have each part of the code directly access what
508 # it needs without keeping redundant references to objects, we have too
499 # it needs without keeping redundant references to objects, we have too
509 # much legacy code that expects ip.db to exist.
500 # much legacy code that expects ip.db to exist.
510 self.db = PickleShareDB(os.path.join(self.profile_dir.location, 'db'))
501 self.db = PickleShareDB(os.path.join(self.profile_dir.location, 'db'))
511
502
512 self.init_history()
503 self.init_history()
513 self.init_encoding()
504 self.init_encoding()
514 self.init_prefilter()
505 self.init_prefilter()
515
506
516 self.init_syntax_highlighting()
507 self.init_syntax_highlighting()
517 self.init_hooks()
508 self.init_hooks()
518 self.init_events()
509 self.init_events()
519 self.init_pushd_popd_magic()
510 self.init_pushd_popd_magic()
520 # self.init_traceback_handlers use to be here, but we moved it below
511 # self.init_traceback_handlers use to be here, but we moved it below
521 # because it and init_io have to come after init_readline.
512 # because it and init_io have to come after init_readline.
522 self.init_user_ns()
513 self.init_user_ns()
523 self.init_logger()
514 self.init_logger()
524 self.init_builtins()
515 self.init_builtins()
525
516
526 # The following was in post_config_initialization
517 # The following was in post_config_initialization
527 self.init_inspector()
518 self.init_inspector()
528 # init_readline() must come before init_io(), because init_io uses
519 # init_readline() must come before init_io(), because init_io uses
529 # readline related things.
520 # readline related things.
530 self.init_readline()
521 self.init_readline()
531 # We save this here in case user code replaces raw_input, but it needs
522 # We save this here in case user code replaces raw_input, but it needs
532 # to be after init_readline(), because PyPy's readline works by replacing
523 # to be after init_readline(), because PyPy's readline works by replacing
533 # raw_input.
524 # raw_input.
534 if py3compat.PY3:
525 if py3compat.PY3:
535 self.raw_input_original = input
526 self.raw_input_original = input
536 else:
527 else:
537 self.raw_input_original = raw_input
528 self.raw_input_original = raw_input
538 # init_completer must come after init_readline, because it needs to
529 # init_completer must come after init_readline, because it needs to
539 # know whether readline is present or not system-wide to configure the
530 # know whether readline is present or not system-wide to configure the
540 # completers, since the completion machinery can now operate
531 # completers, since the completion machinery can now operate
541 # independently of readline (e.g. over the network)
532 # independently of readline (e.g. over the network)
542 self.init_completer()
533 self.init_completer()
543 # TODO: init_io() needs to happen before init_traceback handlers
534 # TODO: init_io() needs to happen before init_traceback handlers
544 # because the traceback handlers hardcode the stdout/stderr streams.
535 # because the traceback handlers hardcode the stdout/stderr streams.
545 # This logic in in debugger.Pdb and should eventually be changed.
536 # This logic in in debugger.Pdb and should eventually be changed.
546 self.init_io()
537 self.init_io()
547 self.init_traceback_handlers(custom_exceptions)
538 self.init_traceback_handlers(custom_exceptions)
548 self.init_prompts()
539 self.init_prompts()
549 self.init_display_formatter()
540 self.init_display_formatter()
550 self.init_display_pub()
541 self.init_display_pub()
551 self.init_data_pub()
542 self.init_data_pub()
552 self.init_displayhook()
543 self.init_displayhook()
553 self.init_magics()
544 self.init_magics()
554 self.init_alias()
545 self.init_alias()
555 self.init_logstart()
546 self.init_logstart()
556 self.init_pdb()
547 self.init_pdb()
557 self.init_extension_manager()
548 self.init_extension_manager()
558 self.init_payload()
549 self.init_payload()
559 self.init_deprecation_warnings()
550 self.init_deprecation_warnings()
560 self.hooks.late_startup_hook()
551 self.hooks.late_startup_hook()
561 self.events.trigger('shell_initialized', self)
552 self.events.trigger('shell_initialized', self)
562 atexit.register(self.atexit_operations)
553 atexit.register(self.atexit_operations)
563
554
564 def get_ipython(self):
555 def get_ipython(self):
565 """Return the currently running IPython instance."""
556 """Return the currently running IPython instance."""
566 return self
557 return self
567
558
568 #-------------------------------------------------------------------------
559 #-------------------------------------------------------------------------
569 # Trait changed handlers
560 # Trait changed handlers
570 #-------------------------------------------------------------------------
561 #-------------------------------------------------------------------------
571 @observe('ipython_dir')
562 @observe('ipython_dir')
572 def _ipython_dir_changed(self, change):
563 def _ipython_dir_changed(self, change):
573 ensure_dir_exists(change['new'])
564 ensure_dir_exists(change['new'])
574
565
575 def set_autoindent(self,value=None):
566 def set_autoindent(self,value=None):
576 """Set the autoindent flag.
567 """Set the autoindent flag.
577
568
578 If called with no arguments, it acts as a toggle."""
569 If called with no arguments, it acts as a toggle."""
579 if value is None:
570 if value is None:
580 self.autoindent = not self.autoindent
571 self.autoindent = not self.autoindent
581 else:
572 else:
582 self.autoindent = value
573 self.autoindent = value
583
574
584 #-------------------------------------------------------------------------
575 #-------------------------------------------------------------------------
585 # init_* methods called by __init__
576 # init_* methods called by __init__
586 #-------------------------------------------------------------------------
577 #-------------------------------------------------------------------------
587
578
588 def init_ipython_dir(self, ipython_dir):
579 def init_ipython_dir(self, ipython_dir):
589 if ipython_dir is not None:
580 if ipython_dir is not None:
590 self.ipython_dir = ipython_dir
581 self.ipython_dir = ipython_dir
591 return
582 return
592
583
593 self.ipython_dir = get_ipython_dir()
584 self.ipython_dir = get_ipython_dir()
594
585
595 def init_profile_dir(self, profile_dir):
586 def init_profile_dir(self, profile_dir):
596 if profile_dir is not None:
587 if profile_dir is not None:
597 self.profile_dir = profile_dir
588 self.profile_dir = profile_dir
598 return
589 return
599 self.profile_dir =\
590 self.profile_dir =\
600 ProfileDir.create_profile_dir_by_name(self.ipython_dir, 'default')
591 ProfileDir.create_profile_dir_by_name(self.ipython_dir, 'default')
601
592
602 def init_instance_attrs(self):
593 def init_instance_attrs(self):
603 self.more = False
594 self.more = False
604
595
605 # command compiler
596 # command compiler
606 self.compile = CachingCompiler()
597 self.compile = CachingCompiler()
607
598
608 # Make an empty namespace, which extension writers can rely on both
599 # Make an empty namespace, which extension writers can rely on both
609 # existing and NEVER being used by ipython itself. This gives them a
600 # existing and NEVER being used by ipython itself. This gives them a
610 # convenient location for storing additional information and state
601 # convenient location for storing additional information and state
611 # their extensions may require, without fear of collisions with other
602 # their extensions may require, without fear of collisions with other
612 # ipython names that may develop later.
603 # ipython names that may develop later.
613 self.meta = Struct()
604 self.meta = Struct()
614
605
615 # Temporary files used for various purposes. Deleted at exit.
606 # Temporary files used for various purposes. Deleted at exit.
616 self.tempfiles = []
607 self.tempfiles = []
617 self.tempdirs = []
608 self.tempdirs = []
618
609
619 # Keep track of readline usage (later set by init_readline)
610 # Keep track of readline usage (later set by init_readline)
620 self.has_readline = False
611 self.has_readline = False
621
612
622 # keep track of where we started running (mainly for crash post-mortem)
613 # keep track of where we started running (mainly for crash post-mortem)
623 # This is not being used anywhere currently.
614 # This is not being used anywhere currently.
624 self.starting_dir = py3compat.getcwd()
615 self.starting_dir = py3compat.getcwd()
625
616
626 # Indentation management
617 # Indentation management
627 self.indent_current_nsp = 0
618 self.indent_current_nsp = 0
628
619
629 # Dict to track post-execution functions that have been registered
620 # Dict to track post-execution functions that have been registered
630 self._post_execute = {}
621 self._post_execute = {}
631
622
632 def init_environment(self):
623 def init_environment(self):
633 """Any changes we need to make to the user's environment."""
624 """Any changes we need to make to the user's environment."""
634 pass
625 pass
635
626
636 def init_encoding(self):
627 def init_encoding(self):
637 # Get system encoding at startup time. Certain terminals (like Emacs
628 # Get system encoding at startup time. Certain terminals (like Emacs
638 # under Win32 have it set to None, and we need to have a known valid
629 # under Win32 have it set to None, and we need to have a known valid
639 # encoding to use in the raw_input() method
630 # encoding to use in the raw_input() method
640 try:
631 try:
641 self.stdin_encoding = sys.stdin.encoding or 'ascii'
632 self.stdin_encoding = sys.stdin.encoding or 'ascii'
642 except AttributeError:
633 except AttributeError:
643 self.stdin_encoding = 'ascii'
634 self.stdin_encoding = 'ascii'
644
635
645 def init_syntax_highlighting(self):
636 def init_syntax_highlighting(self):
646 # Python source parser/formatter for syntax highlighting
637 # Python source parser/formatter for syntax highlighting
647 pyformat = PyColorize.Parser().format
638 pyformat = PyColorize.Parser().format
648 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
639 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
649
640
641 def refresh_style(self):
642 # No-op here, used in subclass
643 pass
644
650 def init_pushd_popd_magic(self):
645 def init_pushd_popd_magic(self):
651 # for pushd/popd management
646 # for pushd/popd management
652 self.home_dir = get_home_dir()
647 self.home_dir = get_home_dir()
653
648
654 self.dir_stack = []
649 self.dir_stack = []
655
650
656 def init_logger(self):
651 def init_logger(self):
657 self.logger = Logger(self.home_dir, logfname='ipython_log.py',
652 self.logger = Logger(self.home_dir, logfname='ipython_log.py',
658 logmode='rotate')
653 logmode='rotate')
659
654
660 def init_logstart(self):
655 def init_logstart(self):
661 """Initialize logging in case it was requested at the command line.
656 """Initialize logging in case it was requested at the command line.
662 """
657 """
663 if self.logappend:
658 if self.logappend:
664 self.magic('logstart %s append' % self.logappend)
659 self.magic('logstart %s append' % self.logappend)
665 elif self.logfile:
660 elif self.logfile:
666 self.magic('logstart %s' % self.logfile)
661 self.magic('logstart %s' % self.logfile)
667 elif self.logstart:
662 elif self.logstart:
668 self.magic('logstart')
663 self.magic('logstart')
669
664
670 def init_deprecation_warnings(self):
665 def init_deprecation_warnings(self):
671 """
666 """
672 register default filter for deprecation warning.
667 register default filter for deprecation warning.
673
668
674 This will allow deprecation warning of function used interactively to show
669 This will allow deprecation warning of function used interactively to show
675 warning to users, and still hide deprecation warning from libraries import.
670 warning to users, and still hide deprecation warning from libraries import.
676 """
671 """
677 warnings.filterwarnings("default", category=DeprecationWarning, module=self.user_ns.get("__name__"))
672 warnings.filterwarnings("default", category=DeprecationWarning, module=self.user_ns.get("__name__"))
678
673
679 def init_builtins(self):
674 def init_builtins(self):
680 # A single, static flag that we set to True. Its presence indicates
675 # A single, static flag that we set to True. Its presence indicates
681 # that an IPython shell has been created, and we make no attempts at
676 # that an IPython shell has been created, and we make no attempts at
682 # removing on exit or representing the existence of more than one
677 # removing on exit or representing the existence of more than one
683 # IPython at a time.
678 # IPython at a time.
684 builtin_mod.__dict__['__IPYTHON__'] = True
679 builtin_mod.__dict__['__IPYTHON__'] = True
685
680
686 self.builtin_trap = BuiltinTrap(shell=self)
681 self.builtin_trap = BuiltinTrap(shell=self)
687
682
688 def init_inspector(self):
683 def init_inspector(self):
689 # Object inspector
684 # Object inspector
690 self.inspector = oinspect.Inspector(oinspect.InspectColors,
685 self.inspector = oinspect.Inspector(oinspect.InspectColors,
691 PyColorize.ANSICodeColors,
686 PyColorize.ANSICodeColors,
692 'NoColor',
687 'NoColor',
693 self.object_info_string_level)
688 self.object_info_string_level)
694
689
695 def init_io(self):
690 def init_io(self):
696 # This will just use sys.stdout and sys.stderr. If you want to
691 # This will just use sys.stdout and sys.stderr. If you want to
697 # override sys.stdout and sys.stderr themselves, you need to do that
692 # override sys.stdout and sys.stderr themselves, you need to do that
698 # *before* instantiating this class, because io holds onto
693 # *before* instantiating this class, because io holds onto
699 # references to the underlying streams.
694 # references to the underlying streams.
700 if (sys.platform == 'win32' or sys.platform == 'cli') and self.has_readline:
695 if (sys.platform == 'win32' or sys.platform == 'cli') and self.has_readline:
701 io.stdout = io.stderr = io.IOStream(self.readline._outputfile)
696 io.stdout = io.stderr = io.IOStream(self.readline._outputfile)
702 else:
697 else:
703 io.stdout = io.IOStream(sys.stdout)
698 io.stdout = io.IOStream(sys.stdout)
704 io.stderr = io.IOStream(sys.stderr)
699 io.stderr = io.IOStream(sys.stderr)
705
700
706 def init_prompts(self):
701 def init_prompts(self):
707 # Set system prompts, so that scripts can decide if they are running
702 # Set system prompts, so that scripts can decide if they are running
708 # interactively.
703 # interactively.
709 sys.ps1 = 'In : '
704 sys.ps1 = 'In : '
710 sys.ps2 = '...: '
705 sys.ps2 = '...: '
711 sys.ps3 = 'Out: '
706 sys.ps3 = 'Out: '
712
707
713 def init_display_formatter(self):
708 def init_display_formatter(self):
714 self.display_formatter = DisplayFormatter(parent=self)
709 self.display_formatter = DisplayFormatter(parent=self)
715 self.configurables.append(self.display_formatter)
710 self.configurables.append(self.display_formatter)
716
711
717 def init_display_pub(self):
712 def init_display_pub(self):
718 self.display_pub = self.display_pub_class(parent=self)
713 self.display_pub = self.display_pub_class(parent=self)
719 self.configurables.append(self.display_pub)
714 self.configurables.append(self.display_pub)
720
715
721 def init_data_pub(self):
716 def init_data_pub(self):
722 if not self.data_pub_class:
717 if not self.data_pub_class:
723 self.data_pub = None
718 self.data_pub = None
724 return
719 return
725 self.data_pub = self.data_pub_class(parent=self)
720 self.data_pub = self.data_pub_class(parent=self)
726 self.configurables.append(self.data_pub)
721 self.configurables.append(self.data_pub)
727
722
728 def init_displayhook(self):
723 def init_displayhook(self):
729 # Initialize displayhook, set in/out prompts and printing system
724 # Initialize displayhook, set in/out prompts and printing system
730 self.displayhook = self.displayhook_class(
725 self.displayhook = self.displayhook_class(
731 parent=self,
726 parent=self,
732 shell=self,
727 shell=self,
733 cache_size=self.cache_size,
728 cache_size=self.cache_size,
734 )
729 )
735 self.configurables.append(self.displayhook)
730 self.configurables.append(self.displayhook)
736 # This is a context manager that installs/revmoes the displayhook at
731 # This is a context manager that installs/revmoes the displayhook at
737 # the appropriate time.
732 # the appropriate time.
738 self.display_trap = DisplayTrap(hook=self.displayhook)
733 self.display_trap = DisplayTrap(hook=self.displayhook)
739
734
740 def init_virtualenv(self):
735 def init_virtualenv(self):
741 """Add a virtualenv to sys.path so the user can import modules from it.
736 """Add a virtualenv to sys.path so the user can import modules from it.
742 This isn't perfect: it doesn't use the Python interpreter with which the
737 This isn't perfect: it doesn't use the Python interpreter with which the
743 virtualenv was built, and it ignores the --no-site-packages option. A
738 virtualenv was built, and it ignores the --no-site-packages option. A
744 warning will appear suggesting the user installs IPython in the
739 warning will appear suggesting the user installs IPython in the
745 virtualenv, but for many cases, it probably works well enough.
740 virtualenv, but for many cases, it probably works well enough.
746
741
747 Adapted from code snippets online.
742 Adapted from code snippets online.
748
743
749 http://blog.ufsoft.org/2009/1/29/ipython-and-virtualenv
744 http://blog.ufsoft.org/2009/1/29/ipython-and-virtualenv
750 """
745 """
751 if 'VIRTUAL_ENV' not in os.environ:
746 if 'VIRTUAL_ENV' not in os.environ:
752 # Not in a virtualenv
747 # Not in a virtualenv
753 return
748 return
754
749
755 # venv detection:
750 # venv detection:
756 # stdlib venv may symlink sys.executable, so we can't use realpath.
751 # stdlib venv may symlink sys.executable, so we can't use realpath.
757 # but others can symlink *to* the venv Python, so we can't just use sys.executable.
752 # but others can symlink *to* the venv Python, so we can't just use sys.executable.
758 # So we just check every item in the symlink tree (generally <= 3)
753 # So we just check every item in the symlink tree (generally <= 3)
759 p = os.path.normcase(sys.executable)
754 p = os.path.normcase(sys.executable)
760 paths = [p]
755 paths = [p]
761 while os.path.islink(p):
756 while os.path.islink(p):
762 p = os.path.normcase(os.path.join(os.path.dirname(p), os.readlink(p)))
757 p = os.path.normcase(os.path.join(os.path.dirname(p), os.readlink(p)))
763 paths.append(p)
758 paths.append(p)
764 p_venv = os.path.normcase(os.environ['VIRTUAL_ENV'])
759 p_venv = os.path.normcase(os.environ['VIRTUAL_ENV'])
765 if any(p.startswith(p_venv) for p in paths):
760 if any(p.startswith(p_venv) for p in paths):
766 # Running properly in the virtualenv, don't need to do anything
761 # Running properly in the virtualenv, don't need to do anything
767 return
762 return
768
763
769 warn("Attempting to work in a virtualenv. If you encounter problems, please "
764 warn("Attempting to work in a virtualenv. If you encounter problems, please "
770 "install IPython inside the virtualenv.")
765 "install IPython inside the virtualenv.")
771 if sys.platform == "win32":
766 if sys.platform == "win32":
772 virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'Lib', 'site-packages')
767 virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'Lib', 'site-packages')
773 else:
768 else:
774 virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'lib',
769 virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'lib',
775 'python%d.%d' % sys.version_info[:2], 'site-packages')
770 'python%d.%d' % sys.version_info[:2], 'site-packages')
776
771
777 import site
772 import site
778 sys.path.insert(0, virtual_env)
773 sys.path.insert(0, virtual_env)
779 site.addsitedir(virtual_env)
774 site.addsitedir(virtual_env)
780
775
781 #-------------------------------------------------------------------------
776 #-------------------------------------------------------------------------
782 # Things related to injections into the sys module
777 # Things related to injections into the sys module
783 #-------------------------------------------------------------------------
778 #-------------------------------------------------------------------------
784
779
785 def save_sys_module_state(self):
780 def save_sys_module_state(self):
786 """Save the state of hooks in the sys module.
781 """Save the state of hooks in the sys module.
787
782
788 This has to be called after self.user_module is created.
783 This has to be called after self.user_module is created.
789 """
784 """
790 self._orig_sys_module_state = {'stdin': sys.stdin,
785 self._orig_sys_module_state = {'stdin': sys.stdin,
791 'stdout': sys.stdout,
786 'stdout': sys.stdout,
792 'stderr': sys.stderr,
787 'stderr': sys.stderr,
793 'excepthook': sys.excepthook}
788 'excepthook': sys.excepthook}
794 self._orig_sys_modules_main_name = self.user_module.__name__
789 self._orig_sys_modules_main_name = self.user_module.__name__
795 self._orig_sys_modules_main_mod = sys.modules.get(self.user_module.__name__)
790 self._orig_sys_modules_main_mod = sys.modules.get(self.user_module.__name__)
796
791
797 def restore_sys_module_state(self):
792 def restore_sys_module_state(self):
798 """Restore the state of the sys module."""
793 """Restore the state of the sys module."""
799 try:
794 try:
800 for k, v in iteritems(self._orig_sys_module_state):
795 for k, v in iteritems(self._orig_sys_module_state):
801 setattr(sys, k, v)
796 setattr(sys, k, v)
802 except AttributeError:
797 except AttributeError:
803 pass
798 pass
804 # Reset what what done in self.init_sys_modules
799 # Reset what what done in self.init_sys_modules
805 if self._orig_sys_modules_main_mod is not None:
800 if self._orig_sys_modules_main_mod is not None:
806 sys.modules[self._orig_sys_modules_main_name] = self._orig_sys_modules_main_mod
801 sys.modules[self._orig_sys_modules_main_name] = self._orig_sys_modules_main_mod
807
802
808 #-------------------------------------------------------------------------
803 #-------------------------------------------------------------------------
809 # Things related to the banner
804 # Things related to the banner
810 #-------------------------------------------------------------------------
805 #-------------------------------------------------------------------------
811
806
812 @property
807 @property
813 def banner(self):
808 def banner(self):
814 banner = self.banner1
809 banner = self.banner1
815 if self.profile and self.profile != 'default':
810 if self.profile and self.profile != 'default':
816 banner += '\nIPython profile: %s\n' % self.profile
811 banner += '\nIPython profile: %s\n' % self.profile
817 if self.banner2:
812 if self.banner2:
818 banner += '\n' + self.banner2
813 banner += '\n' + self.banner2
819 return banner
814 return banner
820
815
821 def show_banner(self, banner=None):
816 def show_banner(self, banner=None):
822 if banner is None:
817 if banner is None:
823 banner = self.banner
818 banner = self.banner
824 sys.stdout.write(banner)
819 sys.stdout.write(banner)
825
820
826 #-------------------------------------------------------------------------
821 #-------------------------------------------------------------------------
827 # Things related to hooks
822 # Things related to hooks
828 #-------------------------------------------------------------------------
823 #-------------------------------------------------------------------------
829
824
830 def init_hooks(self):
825 def init_hooks(self):
831 # hooks holds pointers used for user-side customizations
826 # hooks holds pointers used for user-side customizations
832 self.hooks = Struct()
827 self.hooks = Struct()
833
828
834 self.strdispatchers = {}
829 self.strdispatchers = {}
835
830
836 # Set all default hooks, defined in the IPython.hooks module.
831 # Set all default hooks, defined in the IPython.hooks module.
837 hooks = IPython.core.hooks
832 hooks = IPython.core.hooks
838 for hook_name in hooks.__all__:
833 for hook_name in hooks.__all__:
839 # default hooks have priority 100, i.e. low; user hooks should have
834 # default hooks have priority 100, i.e. low; user hooks should have
840 # 0-100 priority
835 # 0-100 priority
841 self.set_hook(hook_name,getattr(hooks,hook_name), 100, _warn_deprecated=False)
836 self.set_hook(hook_name,getattr(hooks,hook_name), 100, _warn_deprecated=False)
842
837
843 if self.display_page:
838 if self.display_page:
844 self.set_hook('show_in_pager', page.as_hook(page.display_page), 90)
839 self.set_hook('show_in_pager', page.as_hook(page.display_page), 90)
845
840
846 def set_hook(self,name,hook, priority=50, str_key=None, re_key=None,
841 def set_hook(self,name,hook, priority=50, str_key=None, re_key=None,
847 _warn_deprecated=True):
842 _warn_deprecated=True):
848 """set_hook(name,hook) -> sets an internal IPython hook.
843 """set_hook(name,hook) -> sets an internal IPython hook.
849
844
850 IPython exposes some of its internal API as user-modifiable hooks. By
845 IPython exposes some of its internal API as user-modifiable hooks. By
851 adding your function to one of these hooks, you can modify IPython's
846 adding your function to one of these hooks, you can modify IPython's
852 behavior to call at runtime your own routines."""
847 behavior to call at runtime your own routines."""
853
848
854 # At some point in the future, this should validate the hook before it
849 # At some point in the future, this should validate the hook before it
855 # accepts it. Probably at least check that the hook takes the number
850 # accepts it. Probably at least check that the hook takes the number
856 # of args it's supposed to.
851 # of args it's supposed to.
857
852
858 f = types.MethodType(hook,self)
853 f = types.MethodType(hook,self)
859
854
860 # check if the hook is for strdispatcher first
855 # check if the hook is for strdispatcher first
861 if str_key is not None:
856 if str_key is not None:
862 sdp = self.strdispatchers.get(name, StrDispatch())
857 sdp = self.strdispatchers.get(name, StrDispatch())
863 sdp.add_s(str_key, f, priority )
858 sdp.add_s(str_key, f, priority )
864 self.strdispatchers[name] = sdp
859 self.strdispatchers[name] = sdp
865 return
860 return
866 if re_key is not None:
861 if re_key is not None:
867 sdp = self.strdispatchers.get(name, StrDispatch())
862 sdp = self.strdispatchers.get(name, StrDispatch())
868 sdp.add_re(re.compile(re_key), f, priority )
863 sdp.add_re(re.compile(re_key), f, priority )
869 self.strdispatchers[name] = sdp
864 self.strdispatchers[name] = sdp
870 return
865 return
871
866
872 dp = getattr(self.hooks, name, None)
867 dp = getattr(self.hooks, name, None)
873 if name not in IPython.core.hooks.__all__:
868 if name not in IPython.core.hooks.__all__:
874 print("Warning! Hook '%s' is not one of %s" % \
869 print("Warning! Hook '%s' is not one of %s" % \
875 (name, IPython.core.hooks.__all__ ))
870 (name, IPython.core.hooks.__all__ ))
876
871
877 if _warn_deprecated and (name in IPython.core.hooks.deprecated):
872 if _warn_deprecated and (name in IPython.core.hooks.deprecated):
878 alternative = IPython.core.hooks.deprecated[name]
873 alternative = IPython.core.hooks.deprecated[name]
879 warn("Hook {} is deprecated. Use {} instead.".format(name, alternative))
874 warn("Hook {} is deprecated. Use {} instead.".format(name, alternative))
880
875
881 if not dp:
876 if not dp:
882 dp = IPython.core.hooks.CommandChainDispatcher()
877 dp = IPython.core.hooks.CommandChainDispatcher()
883
878
884 try:
879 try:
885 dp.add(f,priority)
880 dp.add(f,priority)
886 except AttributeError:
881 except AttributeError:
887 # it was not commandchain, plain old func - replace
882 # it was not commandchain, plain old func - replace
888 dp = f
883 dp = f
889
884
890 setattr(self.hooks,name, dp)
885 setattr(self.hooks,name, dp)
891
886
892 #-------------------------------------------------------------------------
887 #-------------------------------------------------------------------------
893 # Things related to events
888 # Things related to events
894 #-------------------------------------------------------------------------
889 #-------------------------------------------------------------------------
895
890
896 def init_events(self):
891 def init_events(self):
897 self.events = EventManager(self, available_events)
892 self.events = EventManager(self, available_events)
898
893
899 self.events.register("pre_execute", self._clear_warning_registry)
894 self.events.register("pre_execute", self._clear_warning_registry)
900
895
901 def register_post_execute(self, func):
896 def register_post_execute(self, func):
902 """DEPRECATED: Use ip.events.register('post_run_cell', func)
897 """DEPRECATED: Use ip.events.register('post_run_cell', func)
903
898
904 Register a function for calling after code execution.
899 Register a function for calling after code execution.
905 """
900 """
906 warn("ip.register_post_execute is deprecated, use "
901 warn("ip.register_post_execute is deprecated, use "
907 "ip.events.register('post_run_cell', func) instead.")
902 "ip.events.register('post_run_cell', func) instead.")
908 self.events.register('post_run_cell', func)
903 self.events.register('post_run_cell', func)
909
904
910 def _clear_warning_registry(self):
905 def _clear_warning_registry(self):
911 # clear the warning registry, so that different code blocks with
906 # clear the warning registry, so that different code blocks with
912 # overlapping line number ranges don't cause spurious suppression of
907 # overlapping line number ranges don't cause spurious suppression of
913 # warnings (see gh-6611 for details)
908 # warnings (see gh-6611 for details)
914 if "__warningregistry__" in self.user_global_ns:
909 if "__warningregistry__" in self.user_global_ns:
915 del self.user_global_ns["__warningregistry__"]
910 del self.user_global_ns["__warningregistry__"]
916
911
917 #-------------------------------------------------------------------------
912 #-------------------------------------------------------------------------
918 # Things related to the "main" module
913 # Things related to the "main" module
919 #-------------------------------------------------------------------------
914 #-------------------------------------------------------------------------
920
915
921 def new_main_mod(self, filename, modname):
916 def new_main_mod(self, filename, modname):
922 """Return a new 'main' module object for user code execution.
917 """Return a new 'main' module object for user code execution.
923
918
924 ``filename`` should be the path of the script which will be run in the
919 ``filename`` should be the path of the script which will be run in the
925 module. Requests with the same filename will get the same module, with
920 module. Requests with the same filename will get the same module, with
926 its namespace cleared.
921 its namespace cleared.
927
922
928 ``modname`` should be the module name - normally either '__main__' or
923 ``modname`` should be the module name - normally either '__main__' or
929 the basename of the file without the extension.
924 the basename of the file without the extension.
930
925
931 When scripts are executed via %run, we must keep a reference to their
926 When scripts are executed via %run, we must keep a reference to their
932 __main__ module around so that Python doesn't
927 __main__ module around so that Python doesn't
933 clear it, rendering references to module globals useless.
928 clear it, rendering references to module globals useless.
934
929
935 This method keeps said reference in a private dict, keyed by the
930 This method keeps said reference in a private dict, keyed by the
936 absolute path of the script. This way, for multiple executions of the
931 absolute path of the script. This way, for multiple executions of the
937 same script we only keep one copy of the namespace (the last one),
932 same script we only keep one copy of the namespace (the last one),
938 thus preventing memory leaks from old references while allowing the
933 thus preventing memory leaks from old references while allowing the
939 objects from the last execution to be accessible.
934 objects from the last execution to be accessible.
940 """
935 """
941 filename = os.path.abspath(filename)
936 filename = os.path.abspath(filename)
942 try:
937 try:
943 main_mod = self._main_mod_cache[filename]
938 main_mod = self._main_mod_cache[filename]
944 except KeyError:
939 except KeyError:
945 main_mod = self._main_mod_cache[filename] = types.ModuleType(
940 main_mod = self._main_mod_cache[filename] = types.ModuleType(
946 py3compat.cast_bytes_py2(modname),
941 py3compat.cast_bytes_py2(modname),
947 doc="Module created for script run in IPython")
942 doc="Module created for script run in IPython")
948 else:
943 else:
949 main_mod.__dict__.clear()
944 main_mod.__dict__.clear()
950 main_mod.__name__ = modname
945 main_mod.__name__ = modname
951
946
952 main_mod.__file__ = filename
947 main_mod.__file__ = filename
953 # It seems pydoc (and perhaps others) needs any module instance to
948 # It seems pydoc (and perhaps others) needs any module instance to
954 # implement a __nonzero__ method
949 # implement a __nonzero__ method
955 main_mod.__nonzero__ = lambda : True
950 main_mod.__nonzero__ = lambda : True
956
951
957 return main_mod
952 return main_mod
958
953
959 def clear_main_mod_cache(self):
954 def clear_main_mod_cache(self):
960 """Clear the cache of main modules.
955 """Clear the cache of main modules.
961
956
962 Mainly for use by utilities like %reset.
957 Mainly for use by utilities like %reset.
963
958
964 Examples
959 Examples
965 --------
960 --------
966
961
967 In [15]: import IPython
962 In [15]: import IPython
968
963
969 In [16]: m = _ip.new_main_mod(IPython.__file__, 'IPython')
964 In [16]: m = _ip.new_main_mod(IPython.__file__, 'IPython')
970
965
971 In [17]: len(_ip._main_mod_cache) > 0
966 In [17]: len(_ip._main_mod_cache) > 0
972 Out[17]: True
967 Out[17]: True
973
968
974 In [18]: _ip.clear_main_mod_cache()
969 In [18]: _ip.clear_main_mod_cache()
975
970
976 In [19]: len(_ip._main_mod_cache) == 0
971 In [19]: len(_ip._main_mod_cache) == 0
977 Out[19]: True
972 Out[19]: True
978 """
973 """
979 self._main_mod_cache.clear()
974 self._main_mod_cache.clear()
980
975
981 #-------------------------------------------------------------------------
976 #-------------------------------------------------------------------------
982 # Things related to debugging
977 # Things related to debugging
983 #-------------------------------------------------------------------------
978 #-------------------------------------------------------------------------
984
979
985 def init_pdb(self):
980 def init_pdb(self):
986 # Set calling of pdb on exceptions
981 # Set calling of pdb on exceptions
987 # self.call_pdb is a property
982 # self.call_pdb is a property
988 self.call_pdb = self.pdb
983 self.call_pdb = self.pdb
989
984
990 def _get_call_pdb(self):
985 def _get_call_pdb(self):
991 return self._call_pdb
986 return self._call_pdb
992
987
993 def _set_call_pdb(self,val):
988 def _set_call_pdb(self,val):
994
989
995 if val not in (0,1,False,True):
990 if val not in (0,1,False,True):
996 raise ValueError('new call_pdb value must be boolean')
991 raise ValueError('new call_pdb value must be boolean')
997
992
998 # store value in instance
993 # store value in instance
999 self._call_pdb = val
994 self._call_pdb = val
1000
995
1001 # notify the actual exception handlers
996 # notify the actual exception handlers
1002 self.InteractiveTB.call_pdb = val
997 self.InteractiveTB.call_pdb = val
1003
998
1004 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
999 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
1005 'Control auto-activation of pdb at exceptions')
1000 'Control auto-activation of pdb at exceptions')
1006
1001
1007 def debugger(self,force=False):
1002 def debugger(self,force=False):
1008 """Call the pdb debugger.
1003 """Call the pdb debugger.
1009
1004
1010 Keywords:
1005 Keywords:
1011
1006
1012 - force(False): by default, this routine checks the instance call_pdb
1007 - force(False): by default, this routine checks the instance call_pdb
1013 flag and does not actually invoke the debugger if the flag is false.
1008 flag and does not actually invoke the debugger if the flag is false.
1014 The 'force' option forces the debugger to activate even if the flag
1009 The 'force' option forces the debugger to activate even if the flag
1015 is false.
1010 is false.
1016 """
1011 """
1017
1012
1018 if not (force or self.call_pdb):
1013 if not (force or self.call_pdb):
1019 return
1014 return
1020
1015
1021 if not hasattr(sys,'last_traceback'):
1016 if not hasattr(sys,'last_traceback'):
1022 error('No traceback has been produced, nothing to debug.')
1017 error('No traceback has been produced, nothing to debug.')
1023 return
1018 return
1024
1019
1025
1020
1026 with self.readline_no_record:
1021 with self.readline_no_record:
1027 self.InteractiveTB.debugger(force=True)
1022 self.InteractiveTB.debugger(force=True)
1028
1023
1029 #-------------------------------------------------------------------------
1024 #-------------------------------------------------------------------------
1030 # Things related to IPython's various namespaces
1025 # Things related to IPython's various namespaces
1031 #-------------------------------------------------------------------------
1026 #-------------------------------------------------------------------------
1032 default_user_namespaces = True
1027 default_user_namespaces = True
1033
1028
1034 def init_create_namespaces(self, user_module=None, user_ns=None):
1029 def init_create_namespaces(self, user_module=None, user_ns=None):
1035 # Create the namespace where the user will operate. user_ns is
1030 # Create the namespace where the user will operate. user_ns is
1036 # normally the only one used, and it is passed to the exec calls as
1031 # normally the only one used, and it is passed to the exec calls as
1037 # the locals argument. But we do carry a user_global_ns namespace
1032 # the locals argument. But we do carry a user_global_ns namespace
1038 # given as the exec 'globals' argument, This is useful in embedding
1033 # given as the exec 'globals' argument, This is useful in embedding
1039 # situations where the ipython shell opens in a context where the
1034 # situations where the ipython shell opens in a context where the
1040 # distinction between locals and globals is meaningful. For
1035 # distinction between locals and globals is meaningful. For
1041 # non-embedded contexts, it is just the same object as the user_ns dict.
1036 # non-embedded contexts, it is just the same object as the user_ns dict.
1042
1037
1043 # FIXME. For some strange reason, __builtins__ is showing up at user
1038 # FIXME. For some strange reason, __builtins__ is showing up at user
1044 # level as a dict instead of a module. This is a manual fix, but I
1039 # level as a dict instead of a module. This is a manual fix, but I
1045 # should really track down where the problem is coming from. Alex
1040 # should really track down where the problem is coming from. Alex
1046 # Schmolck reported this problem first.
1041 # Schmolck reported this problem first.
1047
1042
1048 # A useful post by Alex Martelli on this topic:
1043 # A useful post by Alex Martelli on this topic:
1049 # Re: inconsistent value from __builtins__
1044 # Re: inconsistent value from __builtins__
1050 # Von: Alex Martelli <aleaxit@yahoo.com>
1045 # Von: Alex Martelli <aleaxit@yahoo.com>
1051 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
1046 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
1052 # Gruppen: comp.lang.python
1047 # Gruppen: comp.lang.python
1053
1048
1054 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
1049 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
1055 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
1050 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
1056 # > <type 'dict'>
1051 # > <type 'dict'>
1057 # > >>> print type(__builtins__)
1052 # > >>> print type(__builtins__)
1058 # > <type 'module'>
1053 # > <type 'module'>
1059 # > Is this difference in return value intentional?
1054 # > Is this difference in return value intentional?
1060
1055
1061 # Well, it's documented that '__builtins__' can be either a dictionary
1056 # Well, it's documented that '__builtins__' can be either a dictionary
1062 # or a module, and it's been that way for a long time. Whether it's
1057 # or a module, and it's been that way for a long time. Whether it's
1063 # intentional (or sensible), I don't know. In any case, the idea is
1058 # intentional (or sensible), I don't know. In any case, the idea is
1064 # that if you need to access the built-in namespace directly, you
1059 # that if you need to access the built-in namespace directly, you
1065 # should start with "import __builtin__" (note, no 's') which will
1060 # should start with "import __builtin__" (note, no 's') which will
1066 # definitely give you a module. Yeah, it's somewhat confusing:-(.
1061 # definitely give you a module. Yeah, it's somewhat confusing:-(.
1067
1062
1068 # These routines return a properly built module and dict as needed by
1063 # These routines return a properly built module and dict as needed by
1069 # the rest of the code, and can also be used by extension writers to
1064 # the rest of the code, and can also be used by extension writers to
1070 # generate properly initialized namespaces.
1065 # generate properly initialized namespaces.
1071 if (user_ns is not None) or (user_module is not None):
1066 if (user_ns is not None) or (user_module is not None):
1072 self.default_user_namespaces = False
1067 self.default_user_namespaces = False
1073 self.user_module, self.user_ns = self.prepare_user_module(user_module, user_ns)
1068 self.user_module, self.user_ns = self.prepare_user_module(user_module, user_ns)
1074
1069
1075 # A record of hidden variables we have added to the user namespace, so
1070 # A record of hidden variables we have added to the user namespace, so
1076 # we can list later only variables defined in actual interactive use.
1071 # we can list later only variables defined in actual interactive use.
1077 self.user_ns_hidden = {}
1072 self.user_ns_hidden = {}
1078
1073
1079 # Now that FakeModule produces a real module, we've run into a nasty
1074 # Now that FakeModule produces a real module, we've run into a nasty
1080 # problem: after script execution (via %run), the module where the user
1075 # problem: after script execution (via %run), the module where the user
1081 # code ran is deleted. Now that this object is a true module (needed
1076 # code ran is deleted. Now that this object is a true module (needed
1082 # so doctest and other tools work correctly), the Python module
1077 # so doctest and other tools work correctly), the Python module
1083 # teardown mechanism runs over it, and sets to None every variable
1078 # teardown mechanism runs over it, and sets to None every variable
1084 # present in that module. Top-level references to objects from the
1079 # present in that module. Top-level references to objects from the
1085 # script survive, because the user_ns is updated with them. However,
1080 # script survive, because the user_ns is updated with them. However,
1086 # calling functions defined in the script that use other things from
1081 # calling functions defined in the script that use other things from
1087 # the script will fail, because the function's closure had references
1082 # the script will fail, because the function's closure had references
1088 # to the original objects, which are now all None. So we must protect
1083 # to the original objects, which are now all None. So we must protect
1089 # these modules from deletion by keeping a cache.
1084 # these modules from deletion by keeping a cache.
1090 #
1085 #
1091 # To avoid keeping stale modules around (we only need the one from the
1086 # To avoid keeping stale modules around (we only need the one from the
1092 # last run), we use a dict keyed with the full path to the script, so
1087 # last run), we use a dict keyed with the full path to the script, so
1093 # only the last version of the module is held in the cache. Note,
1088 # only the last version of the module is held in the cache. Note,
1094 # however, that we must cache the module *namespace contents* (their
1089 # however, that we must cache the module *namespace contents* (their
1095 # __dict__). Because if we try to cache the actual modules, old ones
1090 # __dict__). Because if we try to cache the actual modules, old ones
1096 # (uncached) could be destroyed while still holding references (such as
1091 # (uncached) could be destroyed while still holding references (such as
1097 # those held by GUI objects that tend to be long-lived)>
1092 # those held by GUI objects that tend to be long-lived)>
1098 #
1093 #
1099 # The %reset command will flush this cache. See the cache_main_mod()
1094 # The %reset command will flush this cache. See the cache_main_mod()
1100 # and clear_main_mod_cache() methods for details on use.
1095 # and clear_main_mod_cache() methods for details on use.
1101
1096
1102 # This is the cache used for 'main' namespaces
1097 # This is the cache used for 'main' namespaces
1103 self._main_mod_cache = {}
1098 self._main_mod_cache = {}
1104
1099
1105 # A table holding all the namespaces IPython deals with, so that
1100 # A table holding all the namespaces IPython deals with, so that
1106 # introspection facilities can search easily.
1101 # introspection facilities can search easily.
1107 self.ns_table = {'user_global':self.user_module.__dict__,
1102 self.ns_table = {'user_global':self.user_module.__dict__,
1108 'user_local':self.user_ns,
1103 'user_local':self.user_ns,
1109 'builtin':builtin_mod.__dict__
1104 'builtin':builtin_mod.__dict__
1110 }
1105 }
1111
1106
1112 @property
1107 @property
1113 def user_global_ns(self):
1108 def user_global_ns(self):
1114 return self.user_module.__dict__
1109 return self.user_module.__dict__
1115
1110
1116 def prepare_user_module(self, user_module=None, user_ns=None):
1111 def prepare_user_module(self, user_module=None, user_ns=None):
1117 """Prepare the module and namespace in which user code will be run.
1112 """Prepare the module and namespace in which user code will be run.
1118
1113
1119 When IPython is started normally, both parameters are None: a new module
1114 When IPython is started normally, both parameters are None: a new module
1120 is created automatically, and its __dict__ used as the namespace.
1115 is created automatically, and its __dict__ used as the namespace.
1121
1116
1122 If only user_module is provided, its __dict__ is used as the namespace.
1117 If only user_module is provided, its __dict__ is used as the namespace.
1123 If only user_ns is provided, a dummy module is created, and user_ns
1118 If only user_ns is provided, a dummy module is created, and user_ns
1124 becomes the global namespace. If both are provided (as they may be
1119 becomes the global namespace. If both are provided (as they may be
1125 when embedding), user_ns is the local namespace, and user_module
1120 when embedding), user_ns is the local namespace, and user_module
1126 provides the global namespace.
1121 provides the global namespace.
1127
1122
1128 Parameters
1123 Parameters
1129 ----------
1124 ----------
1130 user_module : module, optional
1125 user_module : module, optional
1131 The current user module in which IPython is being run. If None,
1126 The current user module in which IPython is being run. If None,
1132 a clean module will be created.
1127 a clean module will be created.
1133 user_ns : dict, optional
1128 user_ns : dict, optional
1134 A namespace in which to run interactive commands.
1129 A namespace in which to run interactive commands.
1135
1130
1136 Returns
1131 Returns
1137 -------
1132 -------
1138 A tuple of user_module and user_ns, each properly initialised.
1133 A tuple of user_module and user_ns, each properly initialised.
1139 """
1134 """
1140 if user_module is None and user_ns is not None:
1135 if user_module is None and user_ns is not None:
1141 user_ns.setdefault("__name__", "__main__")
1136 user_ns.setdefault("__name__", "__main__")
1142 user_module = DummyMod()
1137 user_module = DummyMod()
1143 user_module.__dict__ = user_ns
1138 user_module.__dict__ = user_ns
1144
1139
1145 if user_module is None:
1140 if user_module is None:
1146 user_module = types.ModuleType("__main__",
1141 user_module = types.ModuleType("__main__",
1147 doc="Automatically created module for IPython interactive environment")
1142 doc="Automatically created module for IPython interactive environment")
1148
1143
1149 # We must ensure that __builtin__ (without the final 's') is always
1144 # We must ensure that __builtin__ (without the final 's') is always
1150 # available and pointing to the __builtin__ *module*. For more details:
1145 # available and pointing to the __builtin__ *module*. For more details:
1151 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1146 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1152 user_module.__dict__.setdefault('__builtin__', builtin_mod)
1147 user_module.__dict__.setdefault('__builtin__', builtin_mod)
1153 user_module.__dict__.setdefault('__builtins__', builtin_mod)
1148 user_module.__dict__.setdefault('__builtins__', builtin_mod)
1154
1149
1155 if user_ns is None:
1150 if user_ns is None:
1156 user_ns = user_module.__dict__
1151 user_ns = user_module.__dict__
1157
1152
1158 return user_module, user_ns
1153 return user_module, user_ns
1159
1154
1160 def init_sys_modules(self):
1155 def init_sys_modules(self):
1161 # We need to insert into sys.modules something that looks like a
1156 # We need to insert into sys.modules something that looks like a
1162 # module but which accesses the IPython namespace, for shelve and
1157 # module but which accesses the IPython namespace, for shelve and
1163 # pickle to work interactively. Normally they rely on getting
1158 # pickle to work interactively. Normally they rely on getting
1164 # everything out of __main__, but for embedding purposes each IPython
1159 # everything out of __main__, but for embedding purposes each IPython
1165 # instance has its own private namespace, so we can't go shoving
1160 # instance has its own private namespace, so we can't go shoving
1166 # everything into __main__.
1161 # everything into __main__.
1167
1162
1168 # note, however, that we should only do this for non-embedded
1163 # note, however, that we should only do this for non-embedded
1169 # ipythons, which really mimic the __main__.__dict__ with their own
1164 # ipythons, which really mimic the __main__.__dict__ with their own
1170 # namespace. Embedded instances, on the other hand, should not do
1165 # namespace. Embedded instances, on the other hand, should not do
1171 # this because they need to manage the user local/global namespaces
1166 # this because they need to manage the user local/global namespaces
1172 # only, but they live within a 'normal' __main__ (meaning, they
1167 # only, but they live within a 'normal' __main__ (meaning, they
1173 # shouldn't overtake the execution environment of the script they're
1168 # shouldn't overtake the execution environment of the script they're
1174 # embedded in).
1169 # embedded in).
1175
1170
1176 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
1171 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
1177 main_name = self.user_module.__name__
1172 main_name = self.user_module.__name__
1178 sys.modules[main_name] = self.user_module
1173 sys.modules[main_name] = self.user_module
1179
1174
1180 def init_user_ns(self):
1175 def init_user_ns(self):
1181 """Initialize all user-visible namespaces to their minimum defaults.
1176 """Initialize all user-visible namespaces to their minimum defaults.
1182
1177
1183 Certain history lists are also initialized here, as they effectively
1178 Certain history lists are also initialized here, as they effectively
1184 act as user namespaces.
1179 act as user namespaces.
1185
1180
1186 Notes
1181 Notes
1187 -----
1182 -----
1188 All data structures here are only filled in, they are NOT reset by this
1183 All data structures here are only filled in, they are NOT reset by this
1189 method. If they were not empty before, data will simply be added to
1184 method. If they were not empty before, data will simply be added to
1190 therm.
1185 therm.
1191 """
1186 """
1192 # This function works in two parts: first we put a few things in
1187 # This function works in two parts: first we put a few things in
1193 # user_ns, and we sync that contents into user_ns_hidden so that these
1188 # user_ns, and we sync that contents into user_ns_hidden so that these
1194 # initial variables aren't shown by %who. After the sync, we add the
1189 # initial variables aren't shown by %who. After the sync, we add the
1195 # rest of what we *do* want the user to see with %who even on a new
1190 # rest of what we *do* want the user to see with %who even on a new
1196 # session (probably nothing, so they really only see their own stuff)
1191 # session (probably nothing, so they really only see their own stuff)
1197
1192
1198 # The user dict must *always* have a __builtin__ reference to the
1193 # The user dict must *always* have a __builtin__ reference to the
1199 # Python standard __builtin__ namespace, which must be imported.
1194 # Python standard __builtin__ namespace, which must be imported.
1200 # This is so that certain operations in prompt evaluation can be
1195 # This is so that certain operations in prompt evaluation can be
1201 # reliably executed with builtins. Note that we can NOT use
1196 # reliably executed with builtins. Note that we can NOT use
1202 # __builtins__ (note the 's'), because that can either be a dict or a
1197 # __builtins__ (note the 's'), because that can either be a dict or a
1203 # module, and can even mutate at runtime, depending on the context
1198 # module, and can even mutate at runtime, depending on the context
1204 # (Python makes no guarantees on it). In contrast, __builtin__ is
1199 # (Python makes no guarantees on it). In contrast, __builtin__ is
1205 # always a module object, though it must be explicitly imported.
1200 # always a module object, though it must be explicitly imported.
1206
1201
1207 # For more details:
1202 # For more details:
1208 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1203 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1209 ns = dict()
1204 ns = dict()
1210
1205
1211 # make global variables for user access to the histories
1206 # make global variables for user access to the histories
1212 ns['_ih'] = self.history_manager.input_hist_parsed
1207 ns['_ih'] = self.history_manager.input_hist_parsed
1213 ns['_oh'] = self.history_manager.output_hist
1208 ns['_oh'] = self.history_manager.output_hist
1214 ns['_dh'] = self.history_manager.dir_hist
1209 ns['_dh'] = self.history_manager.dir_hist
1215
1210
1216 ns['_sh'] = shadowns
1211 ns['_sh'] = shadowns
1217
1212
1218 # user aliases to input and output histories. These shouldn't show up
1213 # user aliases to input and output histories. These shouldn't show up
1219 # in %who, as they can have very large reprs.
1214 # in %who, as they can have very large reprs.
1220 ns['In'] = self.history_manager.input_hist_parsed
1215 ns['In'] = self.history_manager.input_hist_parsed
1221 ns['Out'] = self.history_manager.output_hist
1216 ns['Out'] = self.history_manager.output_hist
1222
1217
1223 # Store myself as the public api!!!
1218 # Store myself as the public api!!!
1224 ns['get_ipython'] = self.get_ipython
1219 ns['get_ipython'] = self.get_ipython
1225
1220
1226 ns['exit'] = self.exiter
1221 ns['exit'] = self.exiter
1227 ns['quit'] = self.exiter
1222 ns['quit'] = self.exiter
1228
1223
1229 # Sync what we've added so far to user_ns_hidden so these aren't seen
1224 # Sync what we've added so far to user_ns_hidden so these aren't seen
1230 # by %who
1225 # by %who
1231 self.user_ns_hidden.update(ns)
1226 self.user_ns_hidden.update(ns)
1232
1227
1233 # Anything put into ns now would show up in %who. Think twice before
1228 # Anything put into ns now would show up in %who. Think twice before
1234 # putting anything here, as we really want %who to show the user their
1229 # putting anything here, as we really want %who to show the user their
1235 # stuff, not our variables.
1230 # stuff, not our variables.
1236
1231
1237 # Finally, update the real user's namespace
1232 # Finally, update the real user's namespace
1238 self.user_ns.update(ns)
1233 self.user_ns.update(ns)
1239
1234
1240 @property
1235 @property
1241 def all_ns_refs(self):
1236 def all_ns_refs(self):
1242 """Get a list of references to all the namespace dictionaries in which
1237 """Get a list of references to all the namespace dictionaries in which
1243 IPython might store a user-created object.
1238 IPython might store a user-created object.
1244
1239
1245 Note that this does not include the displayhook, which also caches
1240 Note that this does not include the displayhook, which also caches
1246 objects from the output."""
1241 objects from the output."""
1247 return [self.user_ns, self.user_global_ns, self.user_ns_hidden] + \
1242 return [self.user_ns, self.user_global_ns, self.user_ns_hidden] + \
1248 [m.__dict__ for m in self._main_mod_cache.values()]
1243 [m.__dict__ for m in self._main_mod_cache.values()]
1249
1244
1250 def reset(self, new_session=True):
1245 def reset(self, new_session=True):
1251 """Clear all internal namespaces, and attempt to release references to
1246 """Clear all internal namespaces, and attempt to release references to
1252 user objects.
1247 user objects.
1253
1248
1254 If new_session is True, a new history session will be opened.
1249 If new_session is True, a new history session will be opened.
1255 """
1250 """
1256 # Clear histories
1251 # Clear histories
1257 self.history_manager.reset(new_session)
1252 self.history_manager.reset(new_session)
1258 # Reset counter used to index all histories
1253 # Reset counter used to index all histories
1259 if new_session:
1254 if new_session:
1260 self.execution_count = 1
1255 self.execution_count = 1
1261
1256
1262 # Flush cached output items
1257 # Flush cached output items
1263 if self.displayhook.do_full_cache:
1258 if self.displayhook.do_full_cache:
1264 self.displayhook.flush()
1259 self.displayhook.flush()
1265
1260
1266 # The main execution namespaces must be cleared very carefully,
1261 # The main execution namespaces must be cleared very carefully,
1267 # skipping the deletion of the builtin-related keys, because doing so
1262 # skipping the deletion of the builtin-related keys, because doing so
1268 # would cause errors in many object's __del__ methods.
1263 # would cause errors in many object's __del__ methods.
1269 if self.user_ns is not self.user_global_ns:
1264 if self.user_ns is not self.user_global_ns:
1270 self.user_ns.clear()
1265 self.user_ns.clear()
1271 ns = self.user_global_ns
1266 ns = self.user_global_ns
1272 drop_keys = set(ns.keys())
1267 drop_keys = set(ns.keys())
1273 drop_keys.discard('__builtin__')
1268 drop_keys.discard('__builtin__')
1274 drop_keys.discard('__builtins__')
1269 drop_keys.discard('__builtins__')
1275 drop_keys.discard('__name__')
1270 drop_keys.discard('__name__')
1276 for k in drop_keys:
1271 for k in drop_keys:
1277 del ns[k]
1272 del ns[k]
1278
1273
1279 self.user_ns_hidden.clear()
1274 self.user_ns_hidden.clear()
1280
1275
1281 # Restore the user namespaces to minimal usability
1276 # Restore the user namespaces to minimal usability
1282 self.init_user_ns()
1277 self.init_user_ns()
1283
1278
1284 # Restore the default and user aliases
1279 # Restore the default and user aliases
1285 self.alias_manager.clear_aliases()
1280 self.alias_manager.clear_aliases()
1286 self.alias_manager.init_aliases()
1281 self.alias_manager.init_aliases()
1287
1282
1288 # Flush the private list of module references kept for script
1283 # Flush the private list of module references kept for script
1289 # execution protection
1284 # execution protection
1290 self.clear_main_mod_cache()
1285 self.clear_main_mod_cache()
1291
1286
1292 def del_var(self, varname, by_name=False):
1287 def del_var(self, varname, by_name=False):
1293 """Delete a variable from the various namespaces, so that, as
1288 """Delete a variable from the various namespaces, so that, as
1294 far as possible, we're not keeping any hidden references to it.
1289 far as possible, we're not keeping any hidden references to it.
1295
1290
1296 Parameters
1291 Parameters
1297 ----------
1292 ----------
1298 varname : str
1293 varname : str
1299 The name of the variable to delete.
1294 The name of the variable to delete.
1300 by_name : bool
1295 by_name : bool
1301 If True, delete variables with the given name in each
1296 If True, delete variables with the given name in each
1302 namespace. If False (default), find the variable in the user
1297 namespace. If False (default), find the variable in the user
1303 namespace, and delete references to it.
1298 namespace, and delete references to it.
1304 """
1299 """
1305 if varname in ('__builtin__', '__builtins__'):
1300 if varname in ('__builtin__', '__builtins__'):
1306 raise ValueError("Refusing to delete %s" % varname)
1301 raise ValueError("Refusing to delete %s" % varname)
1307
1302
1308 ns_refs = self.all_ns_refs
1303 ns_refs = self.all_ns_refs
1309
1304
1310 if by_name: # Delete by name
1305 if by_name: # Delete by name
1311 for ns in ns_refs:
1306 for ns in ns_refs:
1312 try:
1307 try:
1313 del ns[varname]
1308 del ns[varname]
1314 except KeyError:
1309 except KeyError:
1315 pass
1310 pass
1316 else: # Delete by object
1311 else: # Delete by object
1317 try:
1312 try:
1318 obj = self.user_ns[varname]
1313 obj = self.user_ns[varname]
1319 except KeyError:
1314 except KeyError:
1320 raise NameError("name '%s' is not defined" % varname)
1315 raise NameError("name '%s' is not defined" % varname)
1321 # Also check in output history
1316 # Also check in output history
1322 ns_refs.append(self.history_manager.output_hist)
1317 ns_refs.append(self.history_manager.output_hist)
1323 for ns in ns_refs:
1318 for ns in ns_refs:
1324 to_delete = [n for n, o in iteritems(ns) if o is obj]
1319 to_delete = [n for n, o in iteritems(ns) if o is obj]
1325 for name in to_delete:
1320 for name in to_delete:
1326 del ns[name]
1321 del ns[name]
1327
1322
1328 # displayhook keeps extra references, but not in a dictionary
1323 # displayhook keeps extra references, but not in a dictionary
1329 for name in ('_', '__', '___'):
1324 for name in ('_', '__', '___'):
1330 if getattr(self.displayhook, name) is obj:
1325 if getattr(self.displayhook, name) is obj:
1331 setattr(self.displayhook, name, None)
1326 setattr(self.displayhook, name, None)
1332
1327
1333 def reset_selective(self, regex=None):
1328 def reset_selective(self, regex=None):
1334 """Clear selective variables from internal namespaces based on a
1329 """Clear selective variables from internal namespaces based on a
1335 specified regular expression.
1330 specified regular expression.
1336
1331
1337 Parameters
1332 Parameters
1338 ----------
1333 ----------
1339 regex : string or compiled pattern, optional
1334 regex : string or compiled pattern, optional
1340 A regular expression pattern that will be used in searching
1335 A regular expression pattern that will be used in searching
1341 variable names in the users namespaces.
1336 variable names in the users namespaces.
1342 """
1337 """
1343 if regex is not None:
1338 if regex is not None:
1344 try:
1339 try:
1345 m = re.compile(regex)
1340 m = re.compile(regex)
1346 except TypeError:
1341 except TypeError:
1347 raise TypeError('regex must be a string or compiled pattern')
1342 raise TypeError('regex must be a string or compiled pattern')
1348 # Search for keys in each namespace that match the given regex
1343 # Search for keys in each namespace that match the given regex
1349 # If a match is found, delete the key/value pair.
1344 # If a match is found, delete the key/value pair.
1350 for ns in self.all_ns_refs:
1345 for ns in self.all_ns_refs:
1351 for var in ns:
1346 for var in ns:
1352 if m.search(var):
1347 if m.search(var):
1353 del ns[var]
1348 del ns[var]
1354
1349
1355 def push(self, variables, interactive=True):
1350 def push(self, variables, interactive=True):
1356 """Inject a group of variables into the IPython user namespace.
1351 """Inject a group of variables into the IPython user namespace.
1357
1352
1358 Parameters
1353 Parameters
1359 ----------
1354 ----------
1360 variables : dict, str or list/tuple of str
1355 variables : dict, str or list/tuple of str
1361 The variables to inject into the user's namespace. If a dict, a
1356 The variables to inject into the user's namespace. If a dict, a
1362 simple update is done. If a str, the string is assumed to have
1357 simple update is done. If a str, the string is assumed to have
1363 variable names separated by spaces. A list/tuple of str can also
1358 variable names separated by spaces. A list/tuple of str can also
1364 be used to give the variable names. If just the variable names are
1359 be used to give the variable names. If just the variable names are
1365 give (list/tuple/str) then the variable values looked up in the
1360 give (list/tuple/str) then the variable values looked up in the
1366 callers frame.
1361 callers frame.
1367 interactive : bool
1362 interactive : bool
1368 If True (default), the variables will be listed with the ``who``
1363 If True (default), the variables will be listed with the ``who``
1369 magic.
1364 magic.
1370 """
1365 """
1371 vdict = None
1366 vdict = None
1372
1367
1373 # We need a dict of name/value pairs to do namespace updates.
1368 # We need a dict of name/value pairs to do namespace updates.
1374 if isinstance(variables, dict):
1369 if isinstance(variables, dict):
1375 vdict = variables
1370 vdict = variables
1376 elif isinstance(variables, string_types+(list, tuple)):
1371 elif isinstance(variables, string_types+(list, tuple)):
1377 if isinstance(variables, string_types):
1372 if isinstance(variables, string_types):
1378 vlist = variables.split()
1373 vlist = variables.split()
1379 else:
1374 else:
1380 vlist = variables
1375 vlist = variables
1381 vdict = {}
1376 vdict = {}
1382 cf = sys._getframe(1)
1377 cf = sys._getframe(1)
1383 for name in vlist:
1378 for name in vlist:
1384 try:
1379 try:
1385 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1380 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1386 except:
1381 except:
1387 print('Could not get variable %s from %s' %
1382 print('Could not get variable %s from %s' %
1388 (name,cf.f_code.co_name))
1383 (name,cf.f_code.co_name))
1389 else:
1384 else:
1390 raise ValueError('variables must be a dict/str/list/tuple')
1385 raise ValueError('variables must be a dict/str/list/tuple')
1391
1386
1392 # Propagate variables to user namespace
1387 # Propagate variables to user namespace
1393 self.user_ns.update(vdict)
1388 self.user_ns.update(vdict)
1394
1389
1395 # And configure interactive visibility
1390 # And configure interactive visibility
1396 user_ns_hidden = self.user_ns_hidden
1391 user_ns_hidden = self.user_ns_hidden
1397 if interactive:
1392 if interactive:
1398 for name in vdict:
1393 for name in vdict:
1399 user_ns_hidden.pop(name, None)
1394 user_ns_hidden.pop(name, None)
1400 else:
1395 else:
1401 user_ns_hidden.update(vdict)
1396 user_ns_hidden.update(vdict)
1402
1397
1403 def drop_by_id(self, variables):
1398 def drop_by_id(self, variables):
1404 """Remove a dict of variables from the user namespace, if they are the
1399 """Remove a dict of variables from the user namespace, if they are the
1405 same as the values in the dictionary.
1400 same as the values in the dictionary.
1406
1401
1407 This is intended for use by extensions: variables that they've added can
1402 This is intended for use by extensions: variables that they've added can
1408 be taken back out if they are unloaded, without removing any that the
1403 be taken back out if they are unloaded, without removing any that the
1409 user has overwritten.
1404 user has overwritten.
1410
1405
1411 Parameters
1406 Parameters
1412 ----------
1407 ----------
1413 variables : dict
1408 variables : dict
1414 A dictionary mapping object names (as strings) to the objects.
1409 A dictionary mapping object names (as strings) to the objects.
1415 """
1410 """
1416 for name, obj in iteritems(variables):
1411 for name, obj in iteritems(variables):
1417 if name in self.user_ns and self.user_ns[name] is obj:
1412 if name in self.user_ns and self.user_ns[name] is obj:
1418 del self.user_ns[name]
1413 del self.user_ns[name]
1419 self.user_ns_hidden.pop(name, None)
1414 self.user_ns_hidden.pop(name, None)
1420
1415
1421 #-------------------------------------------------------------------------
1416 #-------------------------------------------------------------------------
1422 # Things related to object introspection
1417 # Things related to object introspection
1423 #-------------------------------------------------------------------------
1418 #-------------------------------------------------------------------------
1424
1419
1425 def _ofind(self, oname, namespaces=None):
1420 def _ofind(self, oname, namespaces=None):
1426 """Find an object in the available namespaces.
1421 """Find an object in the available namespaces.
1427
1422
1428 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
1423 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
1429
1424
1430 Has special code to detect magic functions.
1425 Has special code to detect magic functions.
1431 """
1426 """
1432 oname = oname.strip()
1427 oname = oname.strip()
1433 #print '1- oname: <%r>' % oname # dbg
1428 #print '1- oname: <%r>' % oname # dbg
1434 if not oname.startswith(ESC_MAGIC) and \
1429 if not oname.startswith(ESC_MAGIC) and \
1435 not oname.startswith(ESC_MAGIC2) and \
1430 not oname.startswith(ESC_MAGIC2) and \
1436 not py3compat.isidentifier(oname, dotted=True):
1431 not py3compat.isidentifier(oname, dotted=True):
1437 return dict(found=False)
1432 return dict(found=False)
1438
1433
1439 if namespaces is None:
1434 if namespaces is None:
1440 # Namespaces to search in:
1435 # Namespaces to search in:
1441 # Put them in a list. The order is important so that we
1436 # Put them in a list. The order is important so that we
1442 # find things in the same order that Python finds them.
1437 # find things in the same order that Python finds them.
1443 namespaces = [ ('Interactive', self.user_ns),
1438 namespaces = [ ('Interactive', self.user_ns),
1444 ('Interactive (global)', self.user_global_ns),
1439 ('Interactive (global)', self.user_global_ns),
1445 ('Python builtin', builtin_mod.__dict__),
1440 ('Python builtin', builtin_mod.__dict__),
1446 ]
1441 ]
1447
1442
1448 # initialize results to 'null'
1443 # initialize results to 'null'
1449 found = False; obj = None; ospace = None;
1444 found = False; obj = None; ospace = None;
1450 ismagic = False; isalias = False; parent = None
1445 ismagic = False; isalias = False; parent = None
1451
1446
1452 # We need to special-case 'print', which as of python2.6 registers as a
1447 # We need to special-case 'print', which as of python2.6 registers as a
1453 # function but should only be treated as one if print_function was
1448 # function but should only be treated as one if print_function was
1454 # loaded with a future import. In this case, just bail.
1449 # loaded with a future import. In this case, just bail.
1455 if (oname == 'print' and not py3compat.PY3 and not \
1450 if (oname == 'print' and not py3compat.PY3 and not \
1456 (self.compile.compiler_flags & __future__.CO_FUTURE_PRINT_FUNCTION)):
1451 (self.compile.compiler_flags & __future__.CO_FUTURE_PRINT_FUNCTION)):
1457 return {'found':found, 'obj':obj, 'namespace':ospace,
1452 return {'found':found, 'obj':obj, 'namespace':ospace,
1458 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1453 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1459
1454
1460 # Look for the given name by splitting it in parts. If the head is
1455 # Look for the given name by splitting it in parts. If the head is
1461 # found, then we look for all the remaining parts as members, and only
1456 # found, then we look for all the remaining parts as members, and only
1462 # declare success if we can find them all.
1457 # declare success if we can find them all.
1463 oname_parts = oname.split('.')
1458 oname_parts = oname.split('.')
1464 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
1459 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
1465 for nsname,ns in namespaces:
1460 for nsname,ns in namespaces:
1466 try:
1461 try:
1467 obj = ns[oname_head]
1462 obj = ns[oname_head]
1468 except KeyError:
1463 except KeyError:
1469 continue
1464 continue
1470 else:
1465 else:
1471 #print 'oname_rest:', oname_rest # dbg
1466 #print 'oname_rest:', oname_rest # dbg
1472 for idx, part in enumerate(oname_rest):
1467 for idx, part in enumerate(oname_rest):
1473 try:
1468 try:
1474 parent = obj
1469 parent = obj
1475 # The last part is looked up in a special way to avoid
1470 # The last part is looked up in a special way to avoid
1476 # descriptor invocation as it may raise or have side
1471 # descriptor invocation as it may raise or have side
1477 # effects.
1472 # effects.
1478 if idx == len(oname_rest) - 1:
1473 if idx == len(oname_rest) - 1:
1479 obj = self._getattr_property(obj, part)
1474 obj = self._getattr_property(obj, part)
1480 else:
1475 else:
1481 obj = getattr(obj, part)
1476 obj = getattr(obj, part)
1482 except:
1477 except:
1483 # Blanket except b/c some badly implemented objects
1478 # Blanket except b/c some badly implemented objects
1484 # allow __getattr__ to raise exceptions other than
1479 # allow __getattr__ to raise exceptions other than
1485 # AttributeError, which then crashes IPython.
1480 # AttributeError, which then crashes IPython.
1486 break
1481 break
1487 else:
1482 else:
1488 # If we finish the for loop (no break), we got all members
1483 # If we finish the for loop (no break), we got all members
1489 found = True
1484 found = True
1490 ospace = nsname
1485 ospace = nsname
1491 break # namespace loop
1486 break # namespace loop
1492
1487
1493 # Try to see if it's magic
1488 # Try to see if it's magic
1494 if not found:
1489 if not found:
1495 obj = None
1490 obj = None
1496 if oname.startswith(ESC_MAGIC2):
1491 if oname.startswith(ESC_MAGIC2):
1497 oname = oname.lstrip(ESC_MAGIC2)
1492 oname = oname.lstrip(ESC_MAGIC2)
1498 obj = self.find_cell_magic(oname)
1493 obj = self.find_cell_magic(oname)
1499 elif oname.startswith(ESC_MAGIC):
1494 elif oname.startswith(ESC_MAGIC):
1500 oname = oname.lstrip(ESC_MAGIC)
1495 oname = oname.lstrip(ESC_MAGIC)
1501 obj = self.find_line_magic(oname)
1496 obj = self.find_line_magic(oname)
1502 else:
1497 else:
1503 # search without prefix, so run? will find %run?
1498 # search without prefix, so run? will find %run?
1504 obj = self.find_line_magic(oname)
1499 obj = self.find_line_magic(oname)
1505 if obj is None:
1500 if obj is None:
1506 obj = self.find_cell_magic(oname)
1501 obj = self.find_cell_magic(oname)
1507 if obj is not None:
1502 if obj is not None:
1508 found = True
1503 found = True
1509 ospace = 'IPython internal'
1504 ospace = 'IPython internal'
1510 ismagic = True
1505 ismagic = True
1511 isalias = isinstance(obj, Alias)
1506 isalias = isinstance(obj, Alias)
1512
1507
1513 # Last try: special-case some literals like '', [], {}, etc:
1508 # Last try: special-case some literals like '', [], {}, etc:
1514 if not found and oname_head in ["''",'""','[]','{}','()']:
1509 if not found and oname_head in ["''",'""','[]','{}','()']:
1515 obj = eval(oname_head)
1510 obj = eval(oname_head)
1516 found = True
1511 found = True
1517 ospace = 'Interactive'
1512 ospace = 'Interactive'
1518
1513
1519 return {'found':found, 'obj':obj, 'namespace':ospace,
1514 return {'found':found, 'obj':obj, 'namespace':ospace,
1520 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1515 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1521
1516
1522 @staticmethod
1517 @staticmethod
1523 def _getattr_property(obj, attrname):
1518 def _getattr_property(obj, attrname):
1524 """Property-aware getattr to use in object finding.
1519 """Property-aware getattr to use in object finding.
1525
1520
1526 If attrname represents a property, return it unevaluated (in case it has
1521 If attrname represents a property, return it unevaluated (in case it has
1527 side effects or raises an error.
1522 side effects or raises an error.
1528
1523
1529 """
1524 """
1530 if not isinstance(obj, type):
1525 if not isinstance(obj, type):
1531 try:
1526 try:
1532 # `getattr(type(obj), attrname)` is not guaranteed to return
1527 # `getattr(type(obj), attrname)` is not guaranteed to return
1533 # `obj`, but does so for property:
1528 # `obj`, but does so for property:
1534 #
1529 #
1535 # property.__get__(self, None, cls) -> self
1530 # property.__get__(self, None, cls) -> self
1536 #
1531 #
1537 # The universal alternative is to traverse the mro manually
1532 # The universal alternative is to traverse the mro manually
1538 # searching for attrname in class dicts.
1533 # searching for attrname in class dicts.
1539 attr = getattr(type(obj), attrname)
1534 attr = getattr(type(obj), attrname)
1540 except AttributeError:
1535 except AttributeError:
1541 pass
1536 pass
1542 else:
1537 else:
1543 # This relies on the fact that data descriptors (with both
1538 # This relies on the fact that data descriptors (with both
1544 # __get__ & __set__ magic methods) take precedence over
1539 # __get__ & __set__ magic methods) take precedence over
1545 # instance-level attributes:
1540 # instance-level attributes:
1546 #
1541 #
1547 # class A(object):
1542 # class A(object):
1548 # @property
1543 # @property
1549 # def foobar(self): return 123
1544 # def foobar(self): return 123
1550 # a = A()
1545 # a = A()
1551 # a.__dict__['foobar'] = 345
1546 # a.__dict__['foobar'] = 345
1552 # a.foobar # == 123
1547 # a.foobar # == 123
1553 #
1548 #
1554 # So, a property may be returned right away.
1549 # So, a property may be returned right away.
1555 if isinstance(attr, property):
1550 if isinstance(attr, property):
1556 return attr
1551 return attr
1557
1552
1558 # Nothing helped, fall back.
1553 # Nothing helped, fall back.
1559 return getattr(obj, attrname)
1554 return getattr(obj, attrname)
1560
1555
1561 def _object_find(self, oname, namespaces=None):
1556 def _object_find(self, oname, namespaces=None):
1562 """Find an object and return a struct with info about it."""
1557 """Find an object and return a struct with info about it."""
1563 return Struct(self._ofind(oname, namespaces))
1558 return Struct(self._ofind(oname, namespaces))
1564
1559
1565 def _inspect(self, meth, oname, namespaces=None, **kw):
1560 def _inspect(self, meth, oname, namespaces=None, **kw):
1566 """Generic interface to the inspector system.
1561 """Generic interface to the inspector system.
1567
1562
1568 This function is meant to be called by pdef, pdoc & friends.
1563 This function is meant to be called by pdef, pdoc & friends.
1569 """
1564 """
1570 info = self._object_find(oname, namespaces)
1565 info = self._object_find(oname, namespaces)
1571 docformat = sphinxify if self.sphinxify_docstring else None
1566 docformat = sphinxify if self.sphinxify_docstring else None
1572 if info.found:
1567 if info.found:
1573 pmethod = getattr(self.inspector, meth)
1568 pmethod = getattr(self.inspector, meth)
1574 # TODO: only apply format_screen to the plain/text repr of the mime
1569 # TODO: only apply format_screen to the plain/text repr of the mime
1575 # bundle.
1570 # bundle.
1576 formatter = format_screen if info.ismagic else docformat
1571 formatter = format_screen if info.ismagic else docformat
1577 if meth == 'pdoc':
1572 if meth == 'pdoc':
1578 pmethod(info.obj, oname, formatter)
1573 pmethod(info.obj, oname, formatter)
1579 elif meth == 'pinfo':
1574 elif meth == 'pinfo':
1580 pmethod(info.obj, oname, formatter, info,
1575 pmethod(info.obj, oname, formatter, info,
1581 enable_html_pager=self.enable_html_pager, **kw)
1576 enable_html_pager=self.enable_html_pager, **kw)
1582 else:
1577 else:
1583 pmethod(info.obj, oname)
1578 pmethod(info.obj, oname)
1584 else:
1579 else:
1585 print('Object `%s` not found.' % oname)
1580 print('Object `%s` not found.' % oname)
1586 return 'not found' # so callers can take other action
1581 return 'not found' # so callers can take other action
1587
1582
1588 def object_inspect(self, oname, detail_level=0):
1583 def object_inspect(self, oname, detail_level=0):
1589 """Get object info about oname"""
1584 """Get object info about oname"""
1590 with self.builtin_trap:
1585 with self.builtin_trap:
1591 info = self._object_find(oname)
1586 info = self._object_find(oname)
1592 if info.found:
1587 if info.found:
1593 return self.inspector.info(info.obj, oname, info=info,
1588 return self.inspector.info(info.obj, oname, info=info,
1594 detail_level=detail_level
1589 detail_level=detail_level
1595 )
1590 )
1596 else:
1591 else:
1597 return oinspect.object_info(name=oname, found=False)
1592 return oinspect.object_info(name=oname, found=False)
1598
1593
1599 def object_inspect_text(self, oname, detail_level=0):
1594 def object_inspect_text(self, oname, detail_level=0):
1600 """Get object info as formatted text"""
1595 """Get object info as formatted text"""
1601 return self.object_inspect_mime(oname, detail_level)['text/plain']
1596 return self.object_inspect_mime(oname, detail_level)['text/plain']
1602
1597
1603 def object_inspect_mime(self, oname, detail_level=0):
1598 def object_inspect_mime(self, oname, detail_level=0):
1604 """Get object info as a mimebundle of formatted representations.
1599 """Get object info as a mimebundle of formatted representations.
1605
1600
1606 A mimebundle is a dictionary, keyed by mime-type.
1601 A mimebundle is a dictionary, keyed by mime-type.
1607 It must always have the key `'text/plain'`.
1602 It must always have the key `'text/plain'`.
1608 """
1603 """
1609 with self.builtin_trap:
1604 with self.builtin_trap:
1610 info = self._object_find(oname)
1605 info = self._object_find(oname)
1611 if info.found:
1606 if info.found:
1612 return self.inspector._get_info(info.obj, oname, info=info,
1607 return self.inspector._get_info(info.obj, oname, info=info,
1613 detail_level=detail_level
1608 detail_level=detail_level
1614 )
1609 )
1615 else:
1610 else:
1616 raise KeyError(oname)
1611 raise KeyError(oname)
1617
1612
1618 #-------------------------------------------------------------------------
1613 #-------------------------------------------------------------------------
1619 # Things related to history management
1614 # Things related to history management
1620 #-------------------------------------------------------------------------
1615 #-------------------------------------------------------------------------
1621
1616
1622 def init_history(self):
1617 def init_history(self):
1623 """Sets up the command history, and starts regular autosaves."""
1618 """Sets up the command history, and starts regular autosaves."""
1624 self.history_manager = HistoryManager(shell=self, parent=self)
1619 self.history_manager = HistoryManager(shell=self, parent=self)
1625 self.configurables.append(self.history_manager)
1620 self.configurables.append(self.history_manager)
1626
1621
1627 #-------------------------------------------------------------------------
1622 #-------------------------------------------------------------------------
1628 # Things related to exception handling and tracebacks (not debugging)
1623 # Things related to exception handling and tracebacks (not debugging)
1629 #-------------------------------------------------------------------------
1624 #-------------------------------------------------------------------------
1630
1625
1631 debugger_cls = Pdb
1626 debugger_cls = Pdb
1632
1627
1633 def init_traceback_handlers(self, custom_exceptions):
1628 def init_traceback_handlers(self, custom_exceptions):
1634 # Syntax error handler.
1629 # Syntax error handler.
1635 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor')
1630 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor')
1636
1631
1637 # The interactive one is initialized with an offset, meaning we always
1632 # The interactive one is initialized with an offset, meaning we always
1638 # want to remove the topmost item in the traceback, which is our own
1633 # want to remove the topmost item in the traceback, which is our own
1639 # internal code. Valid modes: ['Plain','Context','Verbose']
1634 # internal code. Valid modes: ['Plain','Context','Verbose']
1640 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1635 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1641 color_scheme='NoColor',
1636 color_scheme='NoColor',
1642 tb_offset = 1,
1637 tb_offset = 1,
1643 check_cache=check_linecache_ipython,
1638 check_cache=check_linecache_ipython,
1644 debugger_cls=self.debugger_cls)
1639 debugger_cls=self.debugger_cls)
1645
1640
1646 # The instance will store a pointer to the system-wide exception hook,
1641 # The instance will store a pointer to the system-wide exception hook,
1647 # so that runtime code (such as magics) can access it. This is because
1642 # so that runtime code (such as magics) can access it. This is because
1648 # during the read-eval loop, it may get temporarily overwritten.
1643 # during the read-eval loop, it may get temporarily overwritten.
1649 self.sys_excepthook = sys.excepthook
1644 self.sys_excepthook = sys.excepthook
1650
1645
1651 # and add any custom exception handlers the user may have specified
1646 # and add any custom exception handlers the user may have specified
1652 self.set_custom_exc(*custom_exceptions)
1647 self.set_custom_exc(*custom_exceptions)
1653
1648
1654 # Set the exception mode
1649 # Set the exception mode
1655 self.InteractiveTB.set_mode(mode=self.xmode)
1650 self.InteractiveTB.set_mode(mode=self.xmode)
1656
1651
1657 def set_custom_exc(self, exc_tuple, handler):
1652 def set_custom_exc(self, exc_tuple, handler):
1658 """set_custom_exc(exc_tuple, handler)
1653 """set_custom_exc(exc_tuple, handler)
1659
1654
1660 Set a custom exception handler, which will be called if any of the
1655 Set a custom exception handler, which will be called if any of the
1661 exceptions in exc_tuple occur in the mainloop (specifically, in the
1656 exceptions in exc_tuple occur in the mainloop (specifically, in the
1662 run_code() method).
1657 run_code() method).
1663
1658
1664 Parameters
1659 Parameters
1665 ----------
1660 ----------
1666
1661
1667 exc_tuple : tuple of exception classes
1662 exc_tuple : tuple of exception classes
1668 A *tuple* of exception classes, for which to call the defined
1663 A *tuple* of exception classes, for which to call the defined
1669 handler. It is very important that you use a tuple, and NOT A
1664 handler. It is very important that you use a tuple, and NOT A
1670 LIST here, because of the way Python's except statement works. If
1665 LIST here, because of the way Python's except statement works. If
1671 you only want to trap a single exception, use a singleton tuple::
1666 you only want to trap a single exception, use a singleton tuple::
1672
1667
1673 exc_tuple == (MyCustomException,)
1668 exc_tuple == (MyCustomException,)
1674
1669
1675 handler : callable
1670 handler : callable
1676 handler must have the following signature::
1671 handler must have the following signature::
1677
1672
1678 def my_handler(self, etype, value, tb, tb_offset=None):
1673 def my_handler(self, etype, value, tb, tb_offset=None):
1679 ...
1674 ...
1680 return structured_traceback
1675 return structured_traceback
1681
1676
1682 Your handler must return a structured traceback (a list of strings),
1677 Your handler must return a structured traceback (a list of strings),
1683 or None.
1678 or None.
1684
1679
1685 This will be made into an instance method (via types.MethodType)
1680 This will be made into an instance method (via types.MethodType)
1686 of IPython itself, and it will be called if any of the exceptions
1681 of IPython itself, and it will be called if any of the exceptions
1687 listed in the exc_tuple are caught. If the handler is None, an
1682 listed in the exc_tuple are caught. If the handler is None, an
1688 internal basic one is used, which just prints basic info.
1683 internal basic one is used, which just prints basic info.
1689
1684
1690 To protect IPython from crashes, if your handler ever raises an
1685 To protect IPython from crashes, if your handler ever raises an
1691 exception or returns an invalid result, it will be immediately
1686 exception or returns an invalid result, it will be immediately
1692 disabled.
1687 disabled.
1693
1688
1694 WARNING: by putting in your own exception handler into IPython's main
1689 WARNING: by putting in your own exception handler into IPython's main
1695 execution loop, you run a very good chance of nasty crashes. This
1690 execution loop, you run a very good chance of nasty crashes. This
1696 facility should only be used if you really know what you are doing."""
1691 facility should only be used if you really know what you are doing."""
1697
1692
1698 assert type(exc_tuple)==type(()) , \
1693 assert type(exc_tuple)==type(()) , \
1699 "The custom exceptions must be given AS A TUPLE."
1694 "The custom exceptions must be given AS A TUPLE."
1700
1695
1701 def dummy_handler(self, etype, value, tb, tb_offset=None):
1696 def dummy_handler(self, etype, value, tb, tb_offset=None):
1702 print('*** Simple custom exception handler ***')
1697 print('*** Simple custom exception handler ***')
1703 print('Exception type :',etype)
1698 print('Exception type :',etype)
1704 print('Exception value:',value)
1699 print('Exception value:',value)
1705 print('Traceback :',tb)
1700 print('Traceback :',tb)
1706 #print 'Source code :','\n'.join(self.buffer)
1701 #print 'Source code :','\n'.join(self.buffer)
1707
1702
1708 def validate_stb(stb):
1703 def validate_stb(stb):
1709 """validate structured traceback return type
1704 """validate structured traceback return type
1710
1705
1711 return type of CustomTB *should* be a list of strings, but allow
1706 return type of CustomTB *should* be a list of strings, but allow
1712 single strings or None, which are harmless.
1707 single strings or None, which are harmless.
1713
1708
1714 This function will *always* return a list of strings,
1709 This function will *always* return a list of strings,
1715 and will raise a TypeError if stb is inappropriate.
1710 and will raise a TypeError if stb is inappropriate.
1716 """
1711 """
1717 msg = "CustomTB must return list of strings, not %r" % stb
1712 msg = "CustomTB must return list of strings, not %r" % stb
1718 if stb is None:
1713 if stb is None:
1719 return []
1714 return []
1720 elif isinstance(stb, string_types):
1715 elif isinstance(stb, string_types):
1721 return [stb]
1716 return [stb]
1722 elif not isinstance(stb, list):
1717 elif not isinstance(stb, list):
1723 raise TypeError(msg)
1718 raise TypeError(msg)
1724 # it's a list
1719 # it's a list
1725 for line in stb:
1720 for line in stb:
1726 # check every element
1721 # check every element
1727 if not isinstance(line, string_types):
1722 if not isinstance(line, string_types):
1728 raise TypeError(msg)
1723 raise TypeError(msg)
1729 return stb
1724 return stb
1730
1725
1731 if handler is None:
1726 if handler is None:
1732 wrapped = dummy_handler
1727 wrapped = dummy_handler
1733 else:
1728 else:
1734 def wrapped(self,etype,value,tb,tb_offset=None):
1729 def wrapped(self,etype,value,tb,tb_offset=None):
1735 """wrap CustomTB handler, to protect IPython from user code
1730 """wrap CustomTB handler, to protect IPython from user code
1736
1731
1737 This makes it harder (but not impossible) for custom exception
1732 This makes it harder (but not impossible) for custom exception
1738 handlers to crash IPython.
1733 handlers to crash IPython.
1739 """
1734 """
1740 try:
1735 try:
1741 stb = handler(self,etype,value,tb,tb_offset=tb_offset)
1736 stb = handler(self,etype,value,tb,tb_offset=tb_offset)
1742 return validate_stb(stb)
1737 return validate_stb(stb)
1743 except:
1738 except:
1744 # clear custom handler immediately
1739 # clear custom handler immediately
1745 self.set_custom_exc((), None)
1740 self.set_custom_exc((), None)
1746 print("Custom TB Handler failed, unregistering", file=sys.stderr)
1741 print("Custom TB Handler failed, unregistering", file=sys.stderr)
1747 # show the exception in handler first
1742 # show the exception in handler first
1748 stb = self.InteractiveTB.structured_traceback(*sys.exc_info())
1743 stb = self.InteractiveTB.structured_traceback(*sys.exc_info())
1749 print(self.InteractiveTB.stb2text(stb))
1744 print(self.InteractiveTB.stb2text(stb))
1750 print("The original exception:")
1745 print("The original exception:")
1751 stb = self.InteractiveTB.structured_traceback(
1746 stb = self.InteractiveTB.structured_traceback(
1752 (etype,value,tb), tb_offset=tb_offset
1747 (etype,value,tb), tb_offset=tb_offset
1753 )
1748 )
1754 return stb
1749 return stb
1755
1750
1756 self.CustomTB = types.MethodType(wrapped,self)
1751 self.CustomTB = types.MethodType(wrapped,self)
1757 self.custom_exceptions = exc_tuple
1752 self.custom_exceptions = exc_tuple
1758
1753
1759 def excepthook(self, etype, value, tb):
1754 def excepthook(self, etype, value, tb):
1760 """One more defense for GUI apps that call sys.excepthook.
1755 """One more defense for GUI apps that call sys.excepthook.
1761
1756
1762 GUI frameworks like wxPython trap exceptions and call
1757 GUI frameworks like wxPython trap exceptions and call
1763 sys.excepthook themselves. I guess this is a feature that
1758 sys.excepthook themselves. I guess this is a feature that
1764 enables them to keep running after exceptions that would
1759 enables them to keep running after exceptions that would
1765 otherwise kill their mainloop. This is a bother for IPython
1760 otherwise kill their mainloop. This is a bother for IPython
1766 which excepts to catch all of the program exceptions with a try:
1761 which excepts to catch all of the program exceptions with a try:
1767 except: statement.
1762 except: statement.
1768
1763
1769 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1764 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1770 any app directly invokes sys.excepthook, it will look to the user like
1765 any app directly invokes sys.excepthook, it will look to the user like
1771 IPython crashed. In order to work around this, we can disable the
1766 IPython crashed. In order to work around this, we can disable the
1772 CrashHandler and replace it with this excepthook instead, which prints a
1767 CrashHandler and replace it with this excepthook instead, which prints a
1773 regular traceback using our InteractiveTB. In this fashion, apps which
1768 regular traceback using our InteractiveTB. In this fashion, apps which
1774 call sys.excepthook will generate a regular-looking exception from
1769 call sys.excepthook will generate a regular-looking exception from
1775 IPython, and the CrashHandler will only be triggered by real IPython
1770 IPython, and the CrashHandler will only be triggered by real IPython
1776 crashes.
1771 crashes.
1777
1772
1778 This hook should be used sparingly, only in places which are not likely
1773 This hook should be used sparingly, only in places which are not likely
1779 to be true IPython errors.
1774 to be true IPython errors.
1780 """
1775 """
1781 self.showtraceback((etype, value, tb), tb_offset=0)
1776 self.showtraceback((etype, value, tb), tb_offset=0)
1782
1777
1783 def _get_exc_info(self, exc_tuple=None):
1778 def _get_exc_info(self, exc_tuple=None):
1784 """get exc_info from a given tuple, sys.exc_info() or sys.last_type etc.
1779 """get exc_info from a given tuple, sys.exc_info() or sys.last_type etc.
1785
1780
1786 Ensures sys.last_type,value,traceback hold the exc_info we found,
1781 Ensures sys.last_type,value,traceback hold the exc_info we found,
1787 from whichever source.
1782 from whichever source.
1788
1783
1789 raises ValueError if none of these contain any information
1784 raises ValueError if none of these contain any information
1790 """
1785 """
1791 if exc_tuple is None:
1786 if exc_tuple is None:
1792 etype, value, tb = sys.exc_info()
1787 etype, value, tb = sys.exc_info()
1793 else:
1788 else:
1794 etype, value, tb = exc_tuple
1789 etype, value, tb = exc_tuple
1795
1790
1796 if etype is None:
1791 if etype is None:
1797 if hasattr(sys, 'last_type'):
1792 if hasattr(sys, 'last_type'):
1798 etype, value, tb = sys.last_type, sys.last_value, \
1793 etype, value, tb = sys.last_type, sys.last_value, \
1799 sys.last_traceback
1794 sys.last_traceback
1800
1795
1801 if etype is None:
1796 if etype is None:
1802 raise ValueError("No exception to find")
1797 raise ValueError("No exception to find")
1803
1798
1804 # Now store the exception info in sys.last_type etc.
1799 # Now store the exception info in sys.last_type etc.
1805 # WARNING: these variables are somewhat deprecated and not
1800 # WARNING: these variables are somewhat deprecated and not
1806 # necessarily safe to use in a threaded environment, but tools
1801 # necessarily safe to use in a threaded environment, but tools
1807 # like pdb depend on their existence, so let's set them. If we
1802 # like pdb depend on their existence, so let's set them. If we
1808 # find problems in the field, we'll need to revisit their use.
1803 # find problems in the field, we'll need to revisit their use.
1809 sys.last_type = etype
1804 sys.last_type = etype
1810 sys.last_value = value
1805 sys.last_value = value
1811 sys.last_traceback = tb
1806 sys.last_traceback = tb
1812
1807
1813 return etype, value, tb
1808 return etype, value, tb
1814
1809
1815 def show_usage_error(self, exc):
1810 def show_usage_error(self, exc):
1816 """Show a short message for UsageErrors
1811 """Show a short message for UsageErrors
1817
1812
1818 These are special exceptions that shouldn't show a traceback.
1813 These are special exceptions that shouldn't show a traceback.
1819 """
1814 """
1820 print("UsageError: %s" % exc, file=sys.stderr)
1815 print("UsageError: %s" % exc, file=sys.stderr)
1821
1816
1822 def get_exception_only(self, exc_tuple=None):
1817 def get_exception_only(self, exc_tuple=None):
1823 """
1818 """
1824 Return as a string (ending with a newline) the exception that
1819 Return as a string (ending with a newline) the exception that
1825 just occurred, without any traceback.
1820 just occurred, without any traceback.
1826 """
1821 """
1827 etype, value, tb = self._get_exc_info(exc_tuple)
1822 etype, value, tb = self._get_exc_info(exc_tuple)
1828 msg = traceback.format_exception_only(etype, value)
1823 msg = traceback.format_exception_only(etype, value)
1829 return ''.join(msg)
1824 return ''.join(msg)
1830
1825
1831 def showtraceback(self, exc_tuple=None, filename=None, tb_offset=None,
1826 def showtraceback(self, exc_tuple=None, filename=None, tb_offset=None,
1832 exception_only=False):
1827 exception_only=False):
1833 """Display the exception that just occurred.
1828 """Display the exception that just occurred.
1834
1829
1835 If nothing is known about the exception, this is the method which
1830 If nothing is known about the exception, this is the method which
1836 should be used throughout the code for presenting user tracebacks,
1831 should be used throughout the code for presenting user tracebacks,
1837 rather than directly invoking the InteractiveTB object.
1832 rather than directly invoking the InteractiveTB object.
1838
1833
1839 A specific showsyntaxerror() also exists, but this method can take
1834 A specific showsyntaxerror() also exists, but this method can take
1840 care of calling it if needed, so unless you are explicitly catching a
1835 care of calling it if needed, so unless you are explicitly catching a
1841 SyntaxError exception, don't try to analyze the stack manually and
1836 SyntaxError exception, don't try to analyze the stack manually and
1842 simply call this method."""
1837 simply call this method."""
1843
1838
1844 try:
1839 try:
1845 try:
1840 try:
1846 etype, value, tb = self._get_exc_info(exc_tuple)
1841 etype, value, tb = self._get_exc_info(exc_tuple)
1847 except ValueError:
1842 except ValueError:
1848 print('No traceback available to show.', file=sys.stderr)
1843 print('No traceback available to show.', file=sys.stderr)
1849 return
1844 return
1850
1845
1851 if issubclass(etype, SyntaxError):
1846 if issubclass(etype, SyntaxError):
1852 # Though this won't be called by syntax errors in the input
1847 # Though this won't be called by syntax errors in the input
1853 # line, there may be SyntaxError cases with imported code.
1848 # line, there may be SyntaxError cases with imported code.
1854 self.showsyntaxerror(filename)
1849 self.showsyntaxerror(filename)
1855 elif etype is UsageError:
1850 elif etype is UsageError:
1856 self.show_usage_error(value)
1851 self.show_usage_error(value)
1857 else:
1852 else:
1858 if exception_only:
1853 if exception_only:
1859 stb = ['An exception has occurred, use %tb to see '
1854 stb = ['An exception has occurred, use %tb to see '
1860 'the full traceback.\n']
1855 'the full traceback.\n']
1861 stb.extend(self.InteractiveTB.get_exception_only(etype,
1856 stb.extend(self.InteractiveTB.get_exception_only(etype,
1862 value))
1857 value))
1863 else:
1858 else:
1864 try:
1859 try:
1865 # Exception classes can customise their traceback - we
1860 # Exception classes can customise their traceback - we
1866 # use this in IPython.parallel for exceptions occurring
1861 # use this in IPython.parallel for exceptions occurring
1867 # in the engines. This should return a list of strings.
1862 # in the engines. This should return a list of strings.
1868 stb = value._render_traceback_()
1863 stb = value._render_traceback_()
1869 except Exception:
1864 except Exception:
1870 stb = self.InteractiveTB.structured_traceback(etype,
1865 stb = self.InteractiveTB.structured_traceback(etype,
1871 value, tb, tb_offset=tb_offset)
1866 value, tb, tb_offset=tb_offset)
1872
1867
1873 self._showtraceback(etype, value, stb)
1868 self._showtraceback(etype, value, stb)
1874 if self.call_pdb:
1869 if self.call_pdb:
1875 # drop into debugger
1870 # drop into debugger
1876 self.debugger(force=True)
1871 self.debugger(force=True)
1877 return
1872 return
1878
1873
1879 # Actually show the traceback
1874 # Actually show the traceback
1880 self._showtraceback(etype, value, stb)
1875 self._showtraceback(etype, value, stb)
1881
1876
1882 except KeyboardInterrupt:
1877 except KeyboardInterrupt:
1883 print('\n' + self.get_exception_only(), file=sys.stderr)
1878 print('\n' + self.get_exception_only(), file=sys.stderr)
1884
1879
1885 def _showtraceback(self, etype, evalue, stb):
1880 def _showtraceback(self, etype, evalue, stb):
1886 """Actually show a traceback.
1881 """Actually show a traceback.
1887
1882
1888 Subclasses may override this method to put the traceback on a different
1883 Subclasses may override this method to put the traceback on a different
1889 place, like a side channel.
1884 place, like a side channel.
1890 """
1885 """
1891 print(self.InteractiveTB.stb2text(stb))
1886 print(self.InteractiveTB.stb2text(stb))
1892
1887
1893 def showsyntaxerror(self, filename=None):
1888 def showsyntaxerror(self, filename=None):
1894 """Display the syntax error that just occurred.
1889 """Display the syntax error that just occurred.
1895
1890
1896 This doesn't display a stack trace because there isn't one.
1891 This doesn't display a stack trace because there isn't one.
1897
1892
1898 If a filename is given, it is stuffed in the exception instead
1893 If a filename is given, it is stuffed in the exception instead
1899 of what was there before (because Python's parser always uses
1894 of what was there before (because Python's parser always uses
1900 "<string>" when reading from a string).
1895 "<string>" when reading from a string).
1901 """
1896 """
1902 etype, value, last_traceback = self._get_exc_info()
1897 etype, value, last_traceback = self._get_exc_info()
1903
1898
1904 if filename and issubclass(etype, SyntaxError):
1899 if filename and issubclass(etype, SyntaxError):
1905 try:
1900 try:
1906 value.filename = filename
1901 value.filename = filename
1907 except:
1902 except:
1908 # Not the format we expect; leave it alone
1903 # Not the format we expect; leave it alone
1909 pass
1904 pass
1910
1905
1911 stb = self.SyntaxTB.structured_traceback(etype, value, [])
1906 stb = self.SyntaxTB.structured_traceback(etype, value, [])
1912 self._showtraceback(etype, value, stb)
1907 self._showtraceback(etype, value, stb)
1913
1908
1914 # This is overridden in TerminalInteractiveShell to show a message about
1909 # This is overridden in TerminalInteractiveShell to show a message about
1915 # the %paste magic.
1910 # the %paste magic.
1916 def showindentationerror(self):
1911 def showindentationerror(self):
1917 """Called by run_cell when there's an IndentationError in code entered
1912 """Called by run_cell when there's an IndentationError in code entered
1918 at the prompt.
1913 at the prompt.
1919
1914
1920 This is overridden in TerminalInteractiveShell to show a message about
1915 This is overridden in TerminalInteractiveShell to show a message about
1921 the %paste magic."""
1916 the %paste magic."""
1922 self.showsyntaxerror()
1917 self.showsyntaxerror()
1923
1918
1924 #-------------------------------------------------------------------------
1919 #-------------------------------------------------------------------------
1925 # Things related to readline
1920 # Things related to readline
1926 #-------------------------------------------------------------------------
1921 #-------------------------------------------------------------------------
1927
1922
1928 def init_readline(self):
1923 def init_readline(self):
1929 """Moved to terminal subclass, here only to simplify the init logic."""
1924 """Moved to terminal subclass, here only to simplify the init logic."""
1930 self.readline = None
1925 self.readline = None
1931 # Set a number of methods that depend on readline to be no-op
1926 # Set a number of methods that depend on readline to be no-op
1932 self.readline_no_record = NoOpContext()
1927 self.readline_no_record = NoOpContext()
1933 self.set_readline_completer = no_op
1928 self.set_readline_completer = no_op
1934 self.set_custom_completer = no_op
1929 self.set_custom_completer = no_op
1935
1930
1936 @skip_doctest
1931 @skip_doctest
1937 def set_next_input(self, s, replace=False):
1932 def set_next_input(self, s, replace=False):
1938 """ Sets the 'default' input string for the next command line.
1933 """ Sets the 'default' input string for the next command line.
1939
1934
1940 Example::
1935 Example::
1941
1936
1942 In [1]: _ip.set_next_input("Hello Word")
1937 In [1]: _ip.set_next_input("Hello Word")
1943 In [2]: Hello Word_ # cursor is here
1938 In [2]: Hello Word_ # cursor is here
1944 """
1939 """
1945 self.rl_next_input = py3compat.cast_bytes_py2(s)
1940 self.rl_next_input = py3compat.cast_bytes_py2(s)
1946
1941
1947 def _indent_current_str(self):
1942 def _indent_current_str(self):
1948 """return the current level of indentation as a string"""
1943 """return the current level of indentation as a string"""
1949 return self.input_splitter.indent_spaces * ' '
1944 return self.input_splitter.indent_spaces * ' '
1950
1945
1951 #-------------------------------------------------------------------------
1946 #-------------------------------------------------------------------------
1952 # Things related to text completion
1947 # Things related to text completion
1953 #-------------------------------------------------------------------------
1948 #-------------------------------------------------------------------------
1954
1949
1955 def init_completer(self):
1950 def init_completer(self):
1956 """Initialize the completion machinery.
1951 """Initialize the completion machinery.
1957
1952
1958 This creates completion machinery that can be used by client code,
1953 This creates completion machinery that can be used by client code,
1959 either interactively in-process (typically triggered by the readline
1954 either interactively in-process (typically triggered by the readline
1960 library), programmatically (such as in test suites) or out-of-process
1955 library), programmatically (such as in test suites) or out-of-process
1961 (typically over the network by remote frontends).
1956 (typically over the network by remote frontends).
1962 """
1957 """
1963 from IPython.core.completer import IPCompleter
1958 from IPython.core.completer import IPCompleter
1964 from IPython.core.completerlib import (module_completer,
1959 from IPython.core.completerlib import (module_completer,
1965 magic_run_completer, cd_completer, reset_completer)
1960 magic_run_completer, cd_completer, reset_completer)
1966
1961
1967 self.Completer = IPCompleter(shell=self,
1962 self.Completer = IPCompleter(shell=self,
1968 namespace=self.user_ns,
1963 namespace=self.user_ns,
1969 global_namespace=self.user_global_ns,
1964 global_namespace=self.user_global_ns,
1970 use_readline=self.has_readline,
1965 use_readline=self.has_readline,
1971 parent=self,
1966 parent=self,
1972 )
1967 )
1973 self.configurables.append(self.Completer)
1968 self.configurables.append(self.Completer)
1974
1969
1975 # Add custom completers to the basic ones built into IPCompleter
1970 # Add custom completers to the basic ones built into IPCompleter
1976 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1971 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1977 self.strdispatchers['complete_command'] = sdisp
1972 self.strdispatchers['complete_command'] = sdisp
1978 self.Completer.custom_completers = sdisp
1973 self.Completer.custom_completers = sdisp
1979
1974
1980 self.set_hook('complete_command', module_completer, str_key = 'import')
1975 self.set_hook('complete_command', module_completer, str_key = 'import')
1981 self.set_hook('complete_command', module_completer, str_key = 'from')
1976 self.set_hook('complete_command', module_completer, str_key = 'from')
1982 self.set_hook('complete_command', module_completer, str_key = '%aimport')
1977 self.set_hook('complete_command', module_completer, str_key = '%aimport')
1983 self.set_hook('complete_command', magic_run_completer, str_key = '%run')
1978 self.set_hook('complete_command', magic_run_completer, str_key = '%run')
1984 self.set_hook('complete_command', cd_completer, str_key = '%cd')
1979 self.set_hook('complete_command', cd_completer, str_key = '%cd')
1985 self.set_hook('complete_command', reset_completer, str_key = '%reset')
1980 self.set_hook('complete_command', reset_completer, str_key = '%reset')
1986
1981
1987
1982
1988 @skip_doctest_py2
1983 @skip_doctest_py2
1989 def complete(self, text, line=None, cursor_pos=None):
1984 def complete(self, text, line=None, cursor_pos=None):
1990 """Return the completed text and a list of completions.
1985 """Return the completed text and a list of completions.
1991
1986
1992 Parameters
1987 Parameters
1993 ----------
1988 ----------
1994
1989
1995 text : string
1990 text : string
1996 A string of text to be completed on. It can be given as empty and
1991 A string of text to be completed on. It can be given as empty and
1997 instead a line/position pair are given. In this case, the
1992 instead a line/position pair are given. In this case, the
1998 completer itself will split the line like readline does.
1993 completer itself will split the line like readline does.
1999
1994
2000 line : string, optional
1995 line : string, optional
2001 The complete line that text is part of.
1996 The complete line that text is part of.
2002
1997
2003 cursor_pos : int, optional
1998 cursor_pos : int, optional
2004 The position of the cursor on the input line.
1999 The position of the cursor on the input line.
2005
2000
2006 Returns
2001 Returns
2007 -------
2002 -------
2008 text : string
2003 text : string
2009 The actual text that was completed.
2004 The actual text that was completed.
2010
2005
2011 matches : list
2006 matches : list
2012 A sorted list with all possible completions.
2007 A sorted list with all possible completions.
2013
2008
2014 The optional arguments allow the completion to take more context into
2009 The optional arguments allow the completion to take more context into
2015 account, and are part of the low-level completion API.
2010 account, and are part of the low-level completion API.
2016
2011
2017 This is a wrapper around the completion mechanism, similar to what
2012 This is a wrapper around the completion mechanism, similar to what
2018 readline does at the command line when the TAB key is hit. By
2013 readline does at the command line when the TAB key is hit. By
2019 exposing it as a method, it can be used by other non-readline
2014 exposing it as a method, it can be used by other non-readline
2020 environments (such as GUIs) for text completion.
2015 environments (such as GUIs) for text completion.
2021
2016
2022 Simple usage example:
2017 Simple usage example:
2023
2018
2024 In [1]: x = 'hello'
2019 In [1]: x = 'hello'
2025
2020
2026 In [2]: _ip.complete('x.l')
2021 In [2]: _ip.complete('x.l')
2027 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
2022 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
2028 """
2023 """
2029
2024
2030 # Inject names into __builtin__ so we can complete on the added names.
2025 # Inject names into __builtin__ so we can complete on the added names.
2031 with self.builtin_trap:
2026 with self.builtin_trap:
2032 return self.Completer.complete(text, line, cursor_pos)
2027 return self.Completer.complete(text, line, cursor_pos)
2033
2028
2034 def set_custom_completer(self, completer, pos=0):
2029 def set_custom_completer(self, completer, pos=0):
2035 """Adds a new custom completer function.
2030 """Adds a new custom completer function.
2036
2031
2037 The position argument (defaults to 0) is the index in the completers
2032 The position argument (defaults to 0) is the index in the completers
2038 list where you want the completer to be inserted."""
2033 list where you want the completer to be inserted."""
2039
2034
2040 newcomp = types.MethodType(completer,self.Completer)
2035 newcomp = types.MethodType(completer,self.Completer)
2041 self.Completer.matchers.insert(pos,newcomp)
2036 self.Completer.matchers.insert(pos,newcomp)
2042
2037
2043 def set_completer_frame(self, frame=None):
2038 def set_completer_frame(self, frame=None):
2044 """Set the frame of the completer."""
2039 """Set the frame of the completer."""
2045 if frame:
2040 if frame:
2046 self.Completer.namespace = frame.f_locals
2041 self.Completer.namespace = frame.f_locals
2047 self.Completer.global_namespace = frame.f_globals
2042 self.Completer.global_namespace = frame.f_globals
2048 else:
2043 else:
2049 self.Completer.namespace = self.user_ns
2044 self.Completer.namespace = self.user_ns
2050 self.Completer.global_namespace = self.user_global_ns
2045 self.Completer.global_namespace = self.user_global_ns
2051
2046
2052 #-------------------------------------------------------------------------
2047 #-------------------------------------------------------------------------
2053 # Things related to magics
2048 # Things related to magics
2054 #-------------------------------------------------------------------------
2049 #-------------------------------------------------------------------------
2055
2050
2056 def init_magics(self):
2051 def init_magics(self):
2057 from IPython.core import magics as m
2052 from IPython.core import magics as m
2058 self.magics_manager = magic.MagicsManager(shell=self,
2053 self.magics_manager = magic.MagicsManager(shell=self,
2059 parent=self,
2054 parent=self,
2060 user_magics=m.UserMagics(self))
2055 user_magics=m.UserMagics(self))
2061 self.configurables.append(self.magics_manager)
2056 self.configurables.append(self.magics_manager)
2062
2057
2063 # Expose as public API from the magics manager
2058 # Expose as public API from the magics manager
2064 self.register_magics = self.magics_manager.register
2059 self.register_magics = self.magics_manager.register
2065
2060
2066 self.register_magics(m.AutoMagics, m.BasicMagics, m.CodeMagics,
2061 self.register_magics(m.AutoMagics, m.BasicMagics, m.CodeMagics,
2067 m.ConfigMagics, m.DisplayMagics, m.ExecutionMagics,
2062 m.ConfigMagics, m.DisplayMagics, m.ExecutionMagics,
2068 m.ExtensionMagics, m.HistoryMagics, m.LoggingMagics,
2063 m.ExtensionMagics, m.HistoryMagics, m.LoggingMagics,
2069 m.NamespaceMagics, m.OSMagics, m.PylabMagics, m.ScriptMagics,
2064 m.NamespaceMagics, m.OSMagics, m.PylabMagics, m.ScriptMagics,
2070 )
2065 )
2071
2066
2072 # Register Magic Aliases
2067 # Register Magic Aliases
2073 mman = self.magics_manager
2068 mman = self.magics_manager
2074 # FIXME: magic aliases should be defined by the Magics classes
2069 # FIXME: magic aliases should be defined by the Magics classes
2075 # or in MagicsManager, not here
2070 # or in MagicsManager, not here
2076 mman.register_alias('ed', 'edit')
2071 mman.register_alias('ed', 'edit')
2077 mman.register_alias('hist', 'history')
2072 mman.register_alias('hist', 'history')
2078 mman.register_alias('rep', 'recall')
2073 mman.register_alias('rep', 'recall')
2079 mman.register_alias('SVG', 'svg', 'cell')
2074 mman.register_alias('SVG', 'svg', 'cell')
2080 mman.register_alias('HTML', 'html', 'cell')
2075 mman.register_alias('HTML', 'html', 'cell')
2081 mman.register_alias('file', 'writefile', 'cell')
2076 mman.register_alias('file', 'writefile', 'cell')
2082
2077
2083 # FIXME: Move the color initialization to the DisplayHook, which
2078 # FIXME: Move the color initialization to the DisplayHook, which
2084 # should be split into a prompt manager and displayhook. We probably
2079 # should be split into a prompt manager and displayhook. We probably
2085 # even need a centralize colors management object.
2080 # even need a centralize colors management object.
2086 self.magic('colors %s' % self.colors)
2081 self.magic('colors %s' % self.colors)
2087
2082
2088 # Defined here so that it's included in the documentation
2083 # Defined here so that it's included in the documentation
2089 @functools.wraps(magic.MagicsManager.register_function)
2084 @functools.wraps(magic.MagicsManager.register_function)
2090 def register_magic_function(self, func, magic_kind='line', magic_name=None):
2085 def register_magic_function(self, func, magic_kind='line', magic_name=None):
2091 self.magics_manager.register_function(func,
2086 self.magics_manager.register_function(func,
2092 magic_kind=magic_kind, magic_name=magic_name)
2087 magic_kind=magic_kind, magic_name=magic_name)
2093
2088
2094 def run_line_magic(self, magic_name, line):
2089 def run_line_magic(self, magic_name, line):
2095 """Execute the given line magic.
2090 """Execute the given line magic.
2096
2091
2097 Parameters
2092 Parameters
2098 ----------
2093 ----------
2099 magic_name : str
2094 magic_name : str
2100 Name of the desired magic function, without '%' prefix.
2095 Name of the desired magic function, without '%' prefix.
2101
2096
2102 line : str
2097 line : str
2103 The rest of the input line as a single string.
2098 The rest of the input line as a single string.
2104 """
2099 """
2105 fn = self.find_line_magic(magic_name)
2100 fn = self.find_line_magic(magic_name)
2106 if fn is None:
2101 if fn is None:
2107 cm = self.find_cell_magic(magic_name)
2102 cm = self.find_cell_magic(magic_name)
2108 etpl = "Line magic function `%%%s` not found%s."
2103 etpl = "Line magic function `%%%s` not found%s."
2109 extra = '' if cm is None else (' (But cell magic `%%%%%s` exists, '
2104 extra = '' if cm is None else (' (But cell magic `%%%%%s` exists, '
2110 'did you mean that instead?)' % magic_name )
2105 'did you mean that instead?)' % magic_name )
2111 error(etpl % (magic_name, extra))
2106 error(etpl % (magic_name, extra))
2112 else:
2107 else:
2113 # Note: this is the distance in the stack to the user's frame.
2108 # Note: this is the distance in the stack to the user's frame.
2114 # This will need to be updated if the internal calling logic gets
2109 # This will need to be updated if the internal calling logic gets
2115 # refactored, or else we'll be expanding the wrong variables.
2110 # refactored, or else we'll be expanding the wrong variables.
2116 stack_depth = 2
2111 stack_depth = 2
2117 magic_arg_s = self.var_expand(line, stack_depth)
2112 magic_arg_s = self.var_expand(line, stack_depth)
2118 # Put magic args in a list so we can call with f(*a) syntax
2113 # Put magic args in a list so we can call with f(*a) syntax
2119 args = [magic_arg_s]
2114 args = [magic_arg_s]
2120 kwargs = {}
2115 kwargs = {}
2121 # Grab local namespace if we need it:
2116 # Grab local namespace if we need it:
2122 if getattr(fn, "needs_local_scope", False):
2117 if getattr(fn, "needs_local_scope", False):
2123 kwargs['local_ns'] = sys._getframe(stack_depth).f_locals
2118 kwargs['local_ns'] = sys._getframe(stack_depth).f_locals
2124 with self.builtin_trap:
2119 with self.builtin_trap:
2125 result = fn(*args,**kwargs)
2120 result = fn(*args,**kwargs)
2126 return result
2121 return result
2127
2122
2128 def run_cell_magic(self, magic_name, line, cell):
2123 def run_cell_magic(self, magic_name, line, cell):
2129 """Execute the given cell magic.
2124 """Execute the given cell magic.
2130
2125
2131 Parameters
2126 Parameters
2132 ----------
2127 ----------
2133 magic_name : str
2128 magic_name : str
2134 Name of the desired magic function, without '%' prefix.
2129 Name of the desired magic function, without '%' prefix.
2135
2130
2136 line : str
2131 line : str
2137 The rest of the first input line as a single string.
2132 The rest of the first input line as a single string.
2138
2133
2139 cell : str
2134 cell : str
2140 The body of the cell as a (possibly multiline) string.
2135 The body of the cell as a (possibly multiline) string.
2141 """
2136 """
2142 fn = self.find_cell_magic(magic_name)
2137 fn = self.find_cell_magic(magic_name)
2143 if fn is None:
2138 if fn is None:
2144 lm = self.find_line_magic(magic_name)
2139 lm = self.find_line_magic(magic_name)
2145 etpl = "Cell magic `%%{0}` not found{1}."
2140 etpl = "Cell magic `%%{0}` not found{1}."
2146 extra = '' if lm is None else (' (But line magic `%{0}` exists, '
2141 extra = '' if lm is None else (' (But line magic `%{0}` exists, '
2147 'did you mean that instead?)'.format(magic_name))
2142 'did you mean that instead?)'.format(magic_name))
2148 error(etpl.format(magic_name, extra))
2143 error(etpl.format(magic_name, extra))
2149 elif cell == '':
2144 elif cell == '':
2150 message = '%%{0} is a cell magic, but the cell body is empty.'.format(magic_name)
2145 message = '%%{0} is a cell magic, but the cell body is empty.'.format(magic_name)
2151 if self.find_line_magic(magic_name) is not None:
2146 if self.find_line_magic(magic_name) is not None:
2152 message += ' Did you mean the line magic %{0} (single %)?'.format(magic_name)
2147 message += ' Did you mean the line magic %{0} (single %)?'.format(magic_name)
2153 raise UsageError(message)
2148 raise UsageError(message)
2154 else:
2149 else:
2155 # Note: this is the distance in the stack to the user's frame.
2150 # Note: this is the distance in the stack to the user's frame.
2156 # This will need to be updated if the internal calling logic gets
2151 # This will need to be updated if the internal calling logic gets
2157 # refactored, or else we'll be expanding the wrong variables.
2152 # refactored, or else we'll be expanding the wrong variables.
2158 stack_depth = 2
2153 stack_depth = 2
2159 magic_arg_s = self.var_expand(line, stack_depth)
2154 magic_arg_s = self.var_expand(line, stack_depth)
2160 with self.builtin_trap:
2155 with self.builtin_trap:
2161 result = fn(magic_arg_s, cell)
2156 result = fn(magic_arg_s, cell)
2162 return result
2157 return result
2163
2158
2164 def find_line_magic(self, magic_name):
2159 def find_line_magic(self, magic_name):
2165 """Find and return a line magic by name.
2160 """Find and return a line magic by name.
2166
2161
2167 Returns None if the magic isn't found."""
2162 Returns None if the magic isn't found."""
2168 return self.magics_manager.magics['line'].get(magic_name)
2163 return self.magics_manager.magics['line'].get(magic_name)
2169
2164
2170 def find_cell_magic(self, magic_name):
2165 def find_cell_magic(self, magic_name):
2171 """Find and return a cell magic by name.
2166 """Find and return a cell magic by name.
2172
2167
2173 Returns None if the magic isn't found."""
2168 Returns None if the magic isn't found."""
2174 return self.magics_manager.magics['cell'].get(magic_name)
2169 return self.magics_manager.magics['cell'].get(magic_name)
2175
2170
2176 def find_magic(self, magic_name, magic_kind='line'):
2171 def find_magic(self, magic_name, magic_kind='line'):
2177 """Find and return a magic of the given type by name.
2172 """Find and return a magic of the given type by name.
2178
2173
2179 Returns None if the magic isn't found."""
2174 Returns None if the magic isn't found."""
2180 return self.magics_manager.magics[magic_kind].get(magic_name)
2175 return self.magics_manager.magics[magic_kind].get(magic_name)
2181
2176
2182 def magic(self, arg_s):
2177 def magic(self, arg_s):
2183 """DEPRECATED. Use run_line_magic() instead.
2178 """DEPRECATED. Use run_line_magic() instead.
2184
2179
2185 Call a magic function by name.
2180 Call a magic function by name.
2186
2181
2187 Input: a string containing the name of the magic function to call and
2182 Input: a string containing the name of the magic function to call and
2188 any additional arguments to be passed to the magic.
2183 any additional arguments to be passed to the magic.
2189
2184
2190 magic('name -opt foo bar') is equivalent to typing at the ipython
2185 magic('name -opt foo bar') is equivalent to typing at the ipython
2191 prompt:
2186 prompt:
2192
2187
2193 In[1]: %name -opt foo bar
2188 In[1]: %name -opt foo bar
2194
2189
2195 To call a magic without arguments, simply use magic('name').
2190 To call a magic without arguments, simply use magic('name').
2196
2191
2197 This provides a proper Python function to call IPython's magics in any
2192 This provides a proper Python function to call IPython's magics in any
2198 valid Python code you can type at the interpreter, including loops and
2193 valid Python code you can type at the interpreter, including loops and
2199 compound statements.
2194 compound statements.
2200 """
2195 """
2201 # TODO: should we issue a loud deprecation warning here?
2196 # TODO: should we issue a loud deprecation warning here?
2202 magic_name, _, magic_arg_s = arg_s.partition(' ')
2197 magic_name, _, magic_arg_s = arg_s.partition(' ')
2203 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
2198 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
2204 return self.run_line_magic(magic_name, magic_arg_s)
2199 return self.run_line_magic(magic_name, magic_arg_s)
2205
2200
2206 #-------------------------------------------------------------------------
2201 #-------------------------------------------------------------------------
2207 # Things related to macros
2202 # Things related to macros
2208 #-------------------------------------------------------------------------
2203 #-------------------------------------------------------------------------
2209
2204
2210 def define_macro(self, name, themacro):
2205 def define_macro(self, name, themacro):
2211 """Define a new macro
2206 """Define a new macro
2212
2207
2213 Parameters
2208 Parameters
2214 ----------
2209 ----------
2215 name : str
2210 name : str
2216 The name of the macro.
2211 The name of the macro.
2217 themacro : str or Macro
2212 themacro : str or Macro
2218 The action to do upon invoking the macro. If a string, a new
2213 The action to do upon invoking the macro. If a string, a new
2219 Macro object is created by passing the string to it.
2214 Macro object is created by passing the string to it.
2220 """
2215 """
2221
2216
2222 from IPython.core import macro
2217 from IPython.core import macro
2223
2218
2224 if isinstance(themacro, string_types):
2219 if isinstance(themacro, string_types):
2225 themacro = macro.Macro(themacro)
2220 themacro = macro.Macro(themacro)
2226 if not isinstance(themacro, macro.Macro):
2221 if not isinstance(themacro, macro.Macro):
2227 raise ValueError('A macro must be a string or a Macro instance.')
2222 raise ValueError('A macro must be a string or a Macro instance.')
2228 self.user_ns[name] = themacro
2223 self.user_ns[name] = themacro
2229
2224
2230 #-------------------------------------------------------------------------
2225 #-------------------------------------------------------------------------
2231 # Things related to the running of system commands
2226 # Things related to the running of system commands
2232 #-------------------------------------------------------------------------
2227 #-------------------------------------------------------------------------
2233
2228
2234 def system_piped(self, cmd):
2229 def system_piped(self, cmd):
2235 """Call the given cmd in a subprocess, piping stdout/err
2230 """Call the given cmd in a subprocess, piping stdout/err
2236
2231
2237 Parameters
2232 Parameters
2238 ----------
2233 ----------
2239 cmd : str
2234 cmd : str
2240 Command to execute (can not end in '&', as background processes are
2235 Command to execute (can not end in '&', as background processes are
2241 not supported. Should not be a command that expects input
2236 not supported. Should not be a command that expects input
2242 other than simple text.
2237 other than simple text.
2243 """
2238 """
2244 if cmd.rstrip().endswith('&'):
2239 if cmd.rstrip().endswith('&'):
2245 # this is *far* from a rigorous test
2240 # this is *far* from a rigorous test
2246 # We do not support backgrounding processes because we either use
2241 # We do not support backgrounding processes because we either use
2247 # pexpect or pipes to read from. Users can always just call
2242 # pexpect or pipes to read from. Users can always just call
2248 # os.system() or use ip.system=ip.system_raw
2243 # os.system() or use ip.system=ip.system_raw
2249 # if they really want a background process.
2244 # if they really want a background process.
2250 raise OSError("Background processes not supported.")
2245 raise OSError("Background processes not supported.")
2251
2246
2252 # we explicitly do NOT return the subprocess status code, because
2247 # we explicitly do NOT return the subprocess status code, because
2253 # a non-None value would trigger :func:`sys.displayhook` calls.
2248 # a non-None value would trigger :func:`sys.displayhook` calls.
2254 # Instead, we store the exit_code in user_ns.
2249 # Instead, we store the exit_code in user_ns.
2255 self.user_ns['_exit_code'] = system(self.var_expand(cmd, depth=1))
2250 self.user_ns['_exit_code'] = system(self.var_expand(cmd, depth=1))
2256
2251
2257 def system_raw(self, cmd):
2252 def system_raw(self, cmd):
2258 """Call the given cmd in a subprocess using os.system on Windows or
2253 """Call the given cmd in a subprocess using os.system on Windows or
2259 subprocess.call using the system shell on other platforms.
2254 subprocess.call using the system shell on other platforms.
2260
2255
2261 Parameters
2256 Parameters
2262 ----------
2257 ----------
2263 cmd : str
2258 cmd : str
2264 Command to execute.
2259 Command to execute.
2265 """
2260 """
2266 cmd = self.var_expand(cmd, depth=1)
2261 cmd = self.var_expand(cmd, depth=1)
2267 # protect os.system from UNC paths on Windows, which it can't handle:
2262 # protect os.system from UNC paths on Windows, which it can't handle:
2268 if sys.platform == 'win32':
2263 if sys.platform == 'win32':
2269 from IPython.utils._process_win32 import AvoidUNCPath
2264 from IPython.utils._process_win32 import AvoidUNCPath
2270 with AvoidUNCPath() as path:
2265 with AvoidUNCPath() as path:
2271 if path is not None:
2266 if path is not None:
2272 cmd = '"pushd %s &&"%s' % (path, cmd)
2267 cmd = '"pushd %s &&"%s' % (path, cmd)
2273 cmd = py3compat.unicode_to_str(cmd)
2268 cmd = py3compat.unicode_to_str(cmd)
2274 try:
2269 try:
2275 ec = os.system(cmd)
2270 ec = os.system(cmd)
2276 except KeyboardInterrupt:
2271 except KeyboardInterrupt:
2277 print('\n' + self.get_exception_only(), file=sys.stderr)
2272 print('\n' + self.get_exception_only(), file=sys.stderr)
2278 ec = -2
2273 ec = -2
2279 else:
2274 else:
2280 cmd = py3compat.unicode_to_str(cmd)
2275 cmd = py3compat.unicode_to_str(cmd)
2281 # For posix the result of the subprocess.call() below is an exit
2276 # For posix the result of the subprocess.call() below is an exit
2282 # code, which by convention is zero for success, positive for
2277 # code, which by convention is zero for success, positive for
2283 # program failure. Exit codes above 128 are reserved for signals,
2278 # program failure. Exit codes above 128 are reserved for signals,
2284 # and the formula for converting a signal to an exit code is usually
2279 # and the formula for converting a signal to an exit code is usually
2285 # signal_number+128. To more easily differentiate between exit
2280 # signal_number+128. To more easily differentiate between exit
2286 # codes and signals, ipython uses negative numbers. For instance
2281 # codes and signals, ipython uses negative numbers. For instance
2287 # since control-c is signal 2 but exit code 130, ipython's
2282 # since control-c is signal 2 but exit code 130, ipython's
2288 # _exit_code variable will read -2. Note that some shells like
2283 # _exit_code variable will read -2. Note that some shells like
2289 # csh and fish don't follow sh/bash conventions for exit codes.
2284 # csh and fish don't follow sh/bash conventions for exit codes.
2290 executable = os.environ.get('SHELL', None)
2285 executable = os.environ.get('SHELL', None)
2291 try:
2286 try:
2292 # Use env shell instead of default /bin/sh
2287 # Use env shell instead of default /bin/sh
2293 ec = subprocess.call(cmd, shell=True, executable=executable)
2288 ec = subprocess.call(cmd, shell=True, executable=executable)
2294 except KeyboardInterrupt:
2289 except KeyboardInterrupt:
2295 # intercept control-C; a long traceback is not useful here
2290 # intercept control-C; a long traceback is not useful here
2296 print('\n' + self.get_exception_only(), file=sys.stderr)
2291 print('\n' + self.get_exception_only(), file=sys.stderr)
2297 ec = 130
2292 ec = 130
2298 if ec > 128:
2293 if ec > 128:
2299 ec = -(ec - 128)
2294 ec = -(ec - 128)
2300
2295
2301 # We explicitly do NOT return the subprocess status code, because
2296 # We explicitly do NOT return the subprocess status code, because
2302 # a non-None value would trigger :func:`sys.displayhook` calls.
2297 # a non-None value would trigger :func:`sys.displayhook` calls.
2303 # Instead, we store the exit_code in user_ns. Note the semantics
2298 # Instead, we store the exit_code in user_ns. Note the semantics
2304 # of _exit_code: for control-c, _exit_code == -signal.SIGNIT,
2299 # of _exit_code: for control-c, _exit_code == -signal.SIGNIT,
2305 # but raising SystemExit(_exit_code) will give status 254!
2300 # but raising SystemExit(_exit_code) will give status 254!
2306 self.user_ns['_exit_code'] = ec
2301 self.user_ns['_exit_code'] = ec
2307
2302
2308 # use piped system by default, because it is better behaved
2303 # use piped system by default, because it is better behaved
2309 system = system_piped
2304 system = system_piped
2310
2305
2311 def getoutput(self, cmd, split=True, depth=0):
2306 def getoutput(self, cmd, split=True, depth=0):
2312 """Get output (possibly including stderr) from a subprocess.
2307 """Get output (possibly including stderr) from a subprocess.
2313
2308
2314 Parameters
2309 Parameters
2315 ----------
2310 ----------
2316 cmd : str
2311 cmd : str
2317 Command to execute (can not end in '&', as background processes are
2312 Command to execute (can not end in '&', as background processes are
2318 not supported.
2313 not supported.
2319 split : bool, optional
2314 split : bool, optional
2320 If True, split the output into an IPython SList. Otherwise, an
2315 If True, split the output into an IPython SList. Otherwise, an
2321 IPython LSString is returned. These are objects similar to normal
2316 IPython LSString is returned. These are objects similar to normal
2322 lists and strings, with a few convenience attributes for easier
2317 lists and strings, with a few convenience attributes for easier
2323 manipulation of line-based output. You can use '?' on them for
2318 manipulation of line-based output. You can use '?' on them for
2324 details.
2319 details.
2325 depth : int, optional
2320 depth : int, optional
2326 How many frames above the caller are the local variables which should
2321 How many frames above the caller are the local variables which should
2327 be expanded in the command string? The default (0) assumes that the
2322 be expanded in the command string? The default (0) assumes that the
2328 expansion variables are in the stack frame calling this function.
2323 expansion variables are in the stack frame calling this function.
2329 """
2324 """
2330 if cmd.rstrip().endswith('&'):
2325 if cmd.rstrip().endswith('&'):
2331 # this is *far* from a rigorous test
2326 # this is *far* from a rigorous test
2332 raise OSError("Background processes not supported.")
2327 raise OSError("Background processes not supported.")
2333 out = getoutput(self.var_expand(cmd, depth=depth+1))
2328 out = getoutput(self.var_expand(cmd, depth=depth+1))
2334 if split:
2329 if split:
2335 out = SList(out.splitlines())
2330 out = SList(out.splitlines())
2336 else:
2331 else:
2337 out = LSString(out)
2332 out = LSString(out)
2338 return out
2333 return out
2339
2334
2340 #-------------------------------------------------------------------------
2335 #-------------------------------------------------------------------------
2341 # Things related to aliases
2336 # Things related to aliases
2342 #-------------------------------------------------------------------------
2337 #-------------------------------------------------------------------------
2343
2338
2344 def init_alias(self):
2339 def init_alias(self):
2345 self.alias_manager = AliasManager(shell=self, parent=self)
2340 self.alias_manager = AliasManager(shell=self, parent=self)
2346 self.configurables.append(self.alias_manager)
2341 self.configurables.append(self.alias_manager)
2347
2342
2348 #-------------------------------------------------------------------------
2343 #-------------------------------------------------------------------------
2349 # Things related to extensions
2344 # Things related to extensions
2350 #-------------------------------------------------------------------------
2345 #-------------------------------------------------------------------------
2351
2346
2352 def init_extension_manager(self):
2347 def init_extension_manager(self):
2353 self.extension_manager = ExtensionManager(shell=self, parent=self)
2348 self.extension_manager = ExtensionManager(shell=self, parent=self)
2354 self.configurables.append(self.extension_manager)
2349 self.configurables.append(self.extension_manager)
2355
2350
2356 #-------------------------------------------------------------------------
2351 #-------------------------------------------------------------------------
2357 # Things related to payloads
2352 # Things related to payloads
2358 #-------------------------------------------------------------------------
2353 #-------------------------------------------------------------------------
2359
2354
2360 def init_payload(self):
2355 def init_payload(self):
2361 self.payload_manager = PayloadManager(parent=self)
2356 self.payload_manager = PayloadManager(parent=self)
2362 self.configurables.append(self.payload_manager)
2357 self.configurables.append(self.payload_manager)
2363
2358
2364 #-------------------------------------------------------------------------
2359 #-------------------------------------------------------------------------
2365 # Things related to the prefilter
2360 # Things related to the prefilter
2366 #-------------------------------------------------------------------------
2361 #-------------------------------------------------------------------------
2367
2362
2368 def init_prefilter(self):
2363 def init_prefilter(self):
2369 self.prefilter_manager = PrefilterManager(shell=self, parent=self)
2364 self.prefilter_manager = PrefilterManager(shell=self, parent=self)
2370 self.configurables.append(self.prefilter_manager)
2365 self.configurables.append(self.prefilter_manager)
2371 # Ultimately this will be refactored in the new interpreter code, but
2366 # Ultimately this will be refactored in the new interpreter code, but
2372 # for now, we should expose the main prefilter method (there's legacy
2367 # for now, we should expose the main prefilter method (there's legacy
2373 # code out there that may rely on this).
2368 # code out there that may rely on this).
2374 self.prefilter = self.prefilter_manager.prefilter_lines
2369 self.prefilter = self.prefilter_manager.prefilter_lines
2375
2370
2376 def auto_rewrite_input(self, cmd):
2371 def auto_rewrite_input(self, cmd):
2377 """Print to the screen the rewritten form of the user's command.
2372 """Print to the screen the rewritten form of the user's command.
2378
2373
2379 This shows visual feedback by rewriting input lines that cause
2374 This shows visual feedback by rewriting input lines that cause
2380 automatic calling to kick in, like::
2375 automatic calling to kick in, like::
2381
2376
2382 /f x
2377 /f x
2383
2378
2384 into::
2379 into::
2385
2380
2386 ------> f(x)
2381 ------> f(x)
2387
2382
2388 after the user's input prompt. This helps the user understand that the
2383 after the user's input prompt. This helps the user understand that the
2389 input line was transformed automatically by IPython.
2384 input line was transformed automatically by IPython.
2390 """
2385 """
2391 if not self.show_rewritten_input:
2386 if not self.show_rewritten_input:
2392 return
2387 return
2393
2388
2394 # This is overridden in TerminalInteractiveShell to use fancy prompts
2389 # This is overridden in TerminalInteractiveShell to use fancy prompts
2395 print("------> " + cmd)
2390 print("------> " + cmd)
2396
2391
2397 #-------------------------------------------------------------------------
2392 #-------------------------------------------------------------------------
2398 # Things related to extracting values/expressions from kernel and user_ns
2393 # Things related to extracting values/expressions from kernel and user_ns
2399 #-------------------------------------------------------------------------
2394 #-------------------------------------------------------------------------
2400
2395
2401 def _user_obj_error(self):
2396 def _user_obj_error(self):
2402 """return simple exception dict
2397 """return simple exception dict
2403
2398
2404 for use in user_expressions
2399 for use in user_expressions
2405 """
2400 """
2406
2401
2407 etype, evalue, tb = self._get_exc_info()
2402 etype, evalue, tb = self._get_exc_info()
2408 stb = self.InteractiveTB.get_exception_only(etype, evalue)
2403 stb = self.InteractiveTB.get_exception_only(etype, evalue)
2409
2404
2410 exc_info = {
2405 exc_info = {
2411 u'status' : 'error',
2406 u'status' : 'error',
2412 u'traceback' : stb,
2407 u'traceback' : stb,
2413 u'ename' : unicode_type(etype.__name__),
2408 u'ename' : unicode_type(etype.__name__),
2414 u'evalue' : py3compat.safe_unicode(evalue),
2409 u'evalue' : py3compat.safe_unicode(evalue),
2415 }
2410 }
2416
2411
2417 return exc_info
2412 return exc_info
2418
2413
2419 def _format_user_obj(self, obj):
2414 def _format_user_obj(self, obj):
2420 """format a user object to display dict
2415 """format a user object to display dict
2421
2416
2422 for use in user_expressions
2417 for use in user_expressions
2423 """
2418 """
2424
2419
2425 data, md = self.display_formatter.format(obj)
2420 data, md = self.display_formatter.format(obj)
2426 value = {
2421 value = {
2427 'status' : 'ok',
2422 'status' : 'ok',
2428 'data' : data,
2423 'data' : data,
2429 'metadata' : md,
2424 'metadata' : md,
2430 }
2425 }
2431 return value
2426 return value
2432
2427
2433 def user_expressions(self, expressions):
2428 def user_expressions(self, expressions):
2434 """Evaluate a dict of expressions in the user's namespace.
2429 """Evaluate a dict of expressions in the user's namespace.
2435
2430
2436 Parameters
2431 Parameters
2437 ----------
2432 ----------
2438 expressions : dict
2433 expressions : dict
2439 A dict with string keys and string values. The expression values
2434 A dict with string keys and string values. The expression values
2440 should be valid Python expressions, each of which will be evaluated
2435 should be valid Python expressions, each of which will be evaluated
2441 in the user namespace.
2436 in the user namespace.
2442
2437
2443 Returns
2438 Returns
2444 -------
2439 -------
2445 A dict, keyed like the input expressions dict, with the rich mime-typed
2440 A dict, keyed like the input expressions dict, with the rich mime-typed
2446 display_data of each value.
2441 display_data of each value.
2447 """
2442 """
2448 out = {}
2443 out = {}
2449 user_ns = self.user_ns
2444 user_ns = self.user_ns
2450 global_ns = self.user_global_ns
2445 global_ns = self.user_global_ns
2451
2446
2452 for key, expr in iteritems(expressions):
2447 for key, expr in iteritems(expressions):
2453 try:
2448 try:
2454 value = self._format_user_obj(eval(expr, global_ns, user_ns))
2449 value = self._format_user_obj(eval(expr, global_ns, user_ns))
2455 except:
2450 except:
2456 value = self._user_obj_error()
2451 value = self._user_obj_error()
2457 out[key] = value
2452 out[key] = value
2458 return out
2453 return out
2459
2454
2460 #-------------------------------------------------------------------------
2455 #-------------------------------------------------------------------------
2461 # Things related to the running of code
2456 # Things related to the running of code
2462 #-------------------------------------------------------------------------
2457 #-------------------------------------------------------------------------
2463
2458
2464 def ex(self, cmd):
2459 def ex(self, cmd):
2465 """Execute a normal python statement in user namespace."""
2460 """Execute a normal python statement in user namespace."""
2466 with self.builtin_trap:
2461 with self.builtin_trap:
2467 exec(cmd, self.user_global_ns, self.user_ns)
2462 exec(cmd, self.user_global_ns, self.user_ns)
2468
2463
2469 def ev(self, expr):
2464 def ev(self, expr):
2470 """Evaluate python expression expr in user namespace.
2465 """Evaluate python expression expr in user namespace.
2471
2466
2472 Returns the result of evaluation
2467 Returns the result of evaluation
2473 """
2468 """
2474 with self.builtin_trap:
2469 with self.builtin_trap:
2475 return eval(expr, self.user_global_ns, self.user_ns)
2470 return eval(expr, self.user_global_ns, self.user_ns)
2476
2471
2477 def safe_execfile(self, fname, *where, **kw):
2472 def safe_execfile(self, fname, *where, **kw):
2478 """A safe version of the builtin execfile().
2473 """A safe version of the builtin execfile().
2479
2474
2480 This version will never throw an exception, but instead print
2475 This version will never throw an exception, but instead print
2481 helpful error messages to the screen. This only works on pure
2476 helpful error messages to the screen. This only works on pure
2482 Python files with the .py extension.
2477 Python files with the .py extension.
2483
2478
2484 Parameters
2479 Parameters
2485 ----------
2480 ----------
2486 fname : string
2481 fname : string
2487 The name of the file to be executed.
2482 The name of the file to be executed.
2488 where : tuple
2483 where : tuple
2489 One or two namespaces, passed to execfile() as (globals,locals).
2484 One or two namespaces, passed to execfile() as (globals,locals).
2490 If only one is given, it is passed as both.
2485 If only one is given, it is passed as both.
2491 exit_ignore : bool (False)
2486 exit_ignore : bool (False)
2492 If True, then silence SystemExit for non-zero status (it is always
2487 If True, then silence SystemExit for non-zero status (it is always
2493 silenced for zero status, as it is so common).
2488 silenced for zero status, as it is so common).
2494 raise_exceptions : bool (False)
2489 raise_exceptions : bool (False)
2495 If True raise exceptions everywhere. Meant for testing.
2490 If True raise exceptions everywhere. Meant for testing.
2496 shell_futures : bool (False)
2491 shell_futures : bool (False)
2497 If True, the code will share future statements with the interactive
2492 If True, the code will share future statements with the interactive
2498 shell. It will both be affected by previous __future__ imports, and
2493 shell. It will both be affected by previous __future__ imports, and
2499 any __future__ imports in the code will affect the shell. If False,
2494 any __future__ imports in the code will affect the shell. If False,
2500 __future__ imports are not shared in either direction.
2495 __future__ imports are not shared in either direction.
2501
2496
2502 """
2497 """
2503 kw.setdefault('exit_ignore', False)
2498 kw.setdefault('exit_ignore', False)
2504 kw.setdefault('raise_exceptions', False)
2499 kw.setdefault('raise_exceptions', False)
2505 kw.setdefault('shell_futures', False)
2500 kw.setdefault('shell_futures', False)
2506
2501
2507 fname = os.path.abspath(os.path.expanduser(fname))
2502 fname = os.path.abspath(os.path.expanduser(fname))
2508
2503
2509 # Make sure we can open the file
2504 # Make sure we can open the file
2510 try:
2505 try:
2511 with open(fname):
2506 with open(fname):
2512 pass
2507 pass
2513 except:
2508 except:
2514 warn('Could not open file <%s> for safe execution.' % fname)
2509 warn('Could not open file <%s> for safe execution.' % fname)
2515 return
2510 return
2516
2511
2517 # Find things also in current directory. This is needed to mimic the
2512 # Find things also in current directory. This is needed to mimic the
2518 # behavior of running a script from the system command line, where
2513 # behavior of running a script from the system command line, where
2519 # Python inserts the script's directory into sys.path
2514 # Python inserts the script's directory into sys.path
2520 dname = os.path.dirname(fname)
2515 dname = os.path.dirname(fname)
2521
2516
2522 with prepended_to_syspath(dname):
2517 with prepended_to_syspath(dname):
2523 try:
2518 try:
2524 glob, loc = (where + (None, ))[:2]
2519 glob, loc = (where + (None, ))[:2]
2525 py3compat.execfile(
2520 py3compat.execfile(
2526 fname, glob, loc,
2521 fname, glob, loc,
2527 self.compile if kw['shell_futures'] else None)
2522 self.compile if kw['shell_futures'] else None)
2528 except SystemExit as status:
2523 except SystemExit as status:
2529 # If the call was made with 0 or None exit status (sys.exit(0)
2524 # If the call was made with 0 or None exit status (sys.exit(0)
2530 # or sys.exit() ), don't bother showing a traceback, as both of
2525 # or sys.exit() ), don't bother showing a traceback, as both of
2531 # these are considered normal by the OS:
2526 # these are considered normal by the OS:
2532 # > python -c'import sys;sys.exit(0)'; echo $?
2527 # > python -c'import sys;sys.exit(0)'; echo $?
2533 # 0
2528 # 0
2534 # > python -c'import sys;sys.exit()'; echo $?
2529 # > python -c'import sys;sys.exit()'; echo $?
2535 # 0
2530 # 0
2536 # For other exit status, we show the exception unless
2531 # For other exit status, we show the exception unless
2537 # explicitly silenced, but only in short form.
2532 # explicitly silenced, but only in short form.
2538 if status.code:
2533 if status.code:
2539 if kw['raise_exceptions']:
2534 if kw['raise_exceptions']:
2540 raise
2535 raise
2541 if not kw['exit_ignore']:
2536 if not kw['exit_ignore']:
2542 self.showtraceback(exception_only=True)
2537 self.showtraceback(exception_only=True)
2543 except:
2538 except:
2544 if kw['raise_exceptions']:
2539 if kw['raise_exceptions']:
2545 raise
2540 raise
2546 # tb offset is 2 because we wrap execfile
2541 # tb offset is 2 because we wrap execfile
2547 self.showtraceback(tb_offset=2)
2542 self.showtraceback(tb_offset=2)
2548
2543
2549 def safe_execfile_ipy(self, fname, shell_futures=False, raise_exceptions=False):
2544 def safe_execfile_ipy(self, fname, shell_futures=False, raise_exceptions=False):
2550 """Like safe_execfile, but for .ipy or .ipynb files with IPython syntax.
2545 """Like safe_execfile, but for .ipy or .ipynb files with IPython syntax.
2551
2546
2552 Parameters
2547 Parameters
2553 ----------
2548 ----------
2554 fname : str
2549 fname : str
2555 The name of the file to execute. The filename must have a
2550 The name of the file to execute. The filename must have a
2556 .ipy or .ipynb extension.
2551 .ipy or .ipynb extension.
2557 shell_futures : bool (False)
2552 shell_futures : bool (False)
2558 If True, the code will share future statements with the interactive
2553 If True, the code will share future statements with the interactive
2559 shell. It will both be affected by previous __future__ imports, and
2554 shell. It will both be affected by previous __future__ imports, and
2560 any __future__ imports in the code will affect the shell. If False,
2555 any __future__ imports in the code will affect the shell. If False,
2561 __future__ imports are not shared in either direction.
2556 __future__ imports are not shared in either direction.
2562 raise_exceptions : bool (False)
2557 raise_exceptions : bool (False)
2563 If True raise exceptions everywhere. Meant for testing.
2558 If True raise exceptions everywhere. Meant for testing.
2564 """
2559 """
2565 fname = os.path.abspath(os.path.expanduser(fname))
2560 fname = os.path.abspath(os.path.expanduser(fname))
2566
2561
2567 # Make sure we can open the file
2562 # Make sure we can open the file
2568 try:
2563 try:
2569 with open(fname):
2564 with open(fname):
2570 pass
2565 pass
2571 except:
2566 except:
2572 warn('Could not open file <%s> for safe execution.' % fname)
2567 warn('Could not open file <%s> for safe execution.' % fname)
2573 return
2568 return
2574
2569
2575 # Find things also in current directory. This is needed to mimic the
2570 # Find things also in current directory. This is needed to mimic the
2576 # behavior of running a script from the system command line, where
2571 # behavior of running a script from the system command line, where
2577 # Python inserts the script's directory into sys.path
2572 # Python inserts the script's directory into sys.path
2578 dname = os.path.dirname(fname)
2573 dname = os.path.dirname(fname)
2579
2574
2580 def get_cells():
2575 def get_cells():
2581 """generator for sequence of code blocks to run"""
2576 """generator for sequence of code blocks to run"""
2582 if fname.endswith('.ipynb'):
2577 if fname.endswith('.ipynb'):
2583 from nbformat import read
2578 from nbformat import read
2584 with io_open(fname) as f:
2579 with io_open(fname) as f:
2585 nb = read(f, as_version=4)
2580 nb = read(f, as_version=4)
2586 if not nb.cells:
2581 if not nb.cells:
2587 return
2582 return
2588 for cell in nb.cells:
2583 for cell in nb.cells:
2589 if cell.cell_type == 'code':
2584 if cell.cell_type == 'code':
2590 yield cell.source
2585 yield cell.source
2591 else:
2586 else:
2592 with open(fname) as f:
2587 with open(fname) as f:
2593 yield f.read()
2588 yield f.read()
2594
2589
2595 with prepended_to_syspath(dname):
2590 with prepended_to_syspath(dname):
2596 try:
2591 try:
2597 for cell in get_cells():
2592 for cell in get_cells():
2598 result = self.run_cell(cell, silent=True, shell_futures=shell_futures)
2593 result = self.run_cell(cell, silent=True, shell_futures=shell_futures)
2599 if raise_exceptions:
2594 if raise_exceptions:
2600 result.raise_error()
2595 result.raise_error()
2601 elif not result.success:
2596 elif not result.success:
2602 break
2597 break
2603 except:
2598 except:
2604 if raise_exceptions:
2599 if raise_exceptions:
2605 raise
2600 raise
2606 self.showtraceback()
2601 self.showtraceback()
2607 warn('Unknown failure executing file: <%s>' % fname)
2602 warn('Unknown failure executing file: <%s>' % fname)
2608
2603
2609 def safe_run_module(self, mod_name, where):
2604 def safe_run_module(self, mod_name, where):
2610 """A safe version of runpy.run_module().
2605 """A safe version of runpy.run_module().
2611
2606
2612 This version will never throw an exception, but instead print
2607 This version will never throw an exception, but instead print
2613 helpful error messages to the screen.
2608 helpful error messages to the screen.
2614
2609
2615 `SystemExit` exceptions with status code 0 or None are ignored.
2610 `SystemExit` exceptions with status code 0 or None are ignored.
2616
2611
2617 Parameters
2612 Parameters
2618 ----------
2613 ----------
2619 mod_name : string
2614 mod_name : string
2620 The name of the module to be executed.
2615 The name of the module to be executed.
2621 where : dict
2616 where : dict
2622 The globals namespace.
2617 The globals namespace.
2623 """
2618 """
2624 try:
2619 try:
2625 try:
2620 try:
2626 where.update(
2621 where.update(
2627 runpy.run_module(str(mod_name), run_name="__main__",
2622 runpy.run_module(str(mod_name), run_name="__main__",
2628 alter_sys=True)
2623 alter_sys=True)
2629 )
2624 )
2630 except SystemExit as status:
2625 except SystemExit as status:
2631 if status.code:
2626 if status.code:
2632 raise
2627 raise
2633 except:
2628 except:
2634 self.showtraceback()
2629 self.showtraceback()
2635 warn('Unknown failure executing module: <%s>' % mod_name)
2630 warn('Unknown failure executing module: <%s>' % mod_name)
2636
2631
2637 def run_cell(self, raw_cell, store_history=False, silent=False, shell_futures=True):
2632 def run_cell(self, raw_cell, store_history=False, silent=False, shell_futures=True):
2638 """Run a complete IPython cell.
2633 """Run a complete IPython cell.
2639
2634
2640 Parameters
2635 Parameters
2641 ----------
2636 ----------
2642 raw_cell : str
2637 raw_cell : str
2643 The code (including IPython code such as %magic functions) to run.
2638 The code (including IPython code such as %magic functions) to run.
2644 store_history : bool
2639 store_history : bool
2645 If True, the raw and translated cell will be stored in IPython's
2640 If True, the raw and translated cell will be stored in IPython's
2646 history. For user code calling back into IPython's machinery, this
2641 history. For user code calling back into IPython's machinery, this
2647 should be set to False.
2642 should be set to False.
2648 silent : bool
2643 silent : bool
2649 If True, avoid side-effects, such as implicit displayhooks and
2644 If True, avoid side-effects, such as implicit displayhooks and
2650 and logging. silent=True forces store_history=False.
2645 and logging. silent=True forces store_history=False.
2651 shell_futures : bool
2646 shell_futures : bool
2652 If True, the code will share future statements with the interactive
2647 If True, the code will share future statements with the interactive
2653 shell. It will both be affected by previous __future__ imports, and
2648 shell. It will both be affected by previous __future__ imports, and
2654 any __future__ imports in the code will affect the shell. If False,
2649 any __future__ imports in the code will affect the shell. If False,
2655 __future__ imports are not shared in either direction.
2650 __future__ imports are not shared in either direction.
2656
2651
2657 Returns
2652 Returns
2658 -------
2653 -------
2659 result : :class:`ExecutionResult`
2654 result : :class:`ExecutionResult`
2660 """
2655 """
2661 result = ExecutionResult()
2656 result = ExecutionResult()
2662
2657
2663 if (not raw_cell) or raw_cell.isspace():
2658 if (not raw_cell) or raw_cell.isspace():
2664 self.last_execution_succeeded = True
2659 self.last_execution_succeeded = True
2665 return result
2660 return result
2666
2661
2667 if silent:
2662 if silent:
2668 store_history = False
2663 store_history = False
2669
2664
2670 if store_history:
2665 if store_history:
2671 result.execution_count = self.execution_count
2666 result.execution_count = self.execution_count
2672
2667
2673 def error_before_exec(value):
2668 def error_before_exec(value):
2674 result.error_before_exec = value
2669 result.error_before_exec = value
2675 self.last_execution_succeeded = False
2670 self.last_execution_succeeded = False
2676 return result
2671 return result
2677
2672
2678 self.events.trigger('pre_execute')
2673 self.events.trigger('pre_execute')
2679 if not silent:
2674 if not silent:
2680 self.events.trigger('pre_run_cell')
2675 self.events.trigger('pre_run_cell')
2681
2676
2682 # If any of our input transformation (input_transformer_manager or
2677 # If any of our input transformation (input_transformer_manager or
2683 # prefilter_manager) raises an exception, we store it in this variable
2678 # prefilter_manager) raises an exception, we store it in this variable
2684 # so that we can display the error after logging the input and storing
2679 # so that we can display the error after logging the input and storing
2685 # it in the history.
2680 # it in the history.
2686 preprocessing_exc_tuple = None
2681 preprocessing_exc_tuple = None
2687 try:
2682 try:
2688 # Static input transformations
2683 # Static input transformations
2689 cell = self.input_transformer_manager.transform_cell(raw_cell)
2684 cell = self.input_transformer_manager.transform_cell(raw_cell)
2690 except SyntaxError:
2685 except SyntaxError:
2691 preprocessing_exc_tuple = sys.exc_info()
2686 preprocessing_exc_tuple = sys.exc_info()
2692 cell = raw_cell # cell has to exist so it can be stored/logged
2687 cell = raw_cell # cell has to exist so it can be stored/logged
2693 else:
2688 else:
2694 if len(cell.splitlines()) == 1:
2689 if len(cell.splitlines()) == 1:
2695 # Dynamic transformations - only applied for single line commands
2690 # Dynamic transformations - only applied for single line commands
2696 with self.builtin_trap:
2691 with self.builtin_trap:
2697 try:
2692 try:
2698 # use prefilter_lines to handle trailing newlines
2693 # use prefilter_lines to handle trailing newlines
2699 # restore trailing newline for ast.parse
2694 # restore trailing newline for ast.parse
2700 cell = self.prefilter_manager.prefilter_lines(cell) + '\n'
2695 cell = self.prefilter_manager.prefilter_lines(cell) + '\n'
2701 except Exception:
2696 except Exception:
2702 # don't allow prefilter errors to crash IPython
2697 # don't allow prefilter errors to crash IPython
2703 preprocessing_exc_tuple = sys.exc_info()
2698 preprocessing_exc_tuple = sys.exc_info()
2704
2699
2705 # Store raw and processed history
2700 # Store raw and processed history
2706 if store_history:
2701 if store_history:
2707 self.history_manager.store_inputs(self.execution_count,
2702 self.history_manager.store_inputs(self.execution_count,
2708 cell, raw_cell)
2703 cell, raw_cell)
2709 if not silent:
2704 if not silent:
2710 self.logger.log(cell, raw_cell)
2705 self.logger.log(cell, raw_cell)
2711
2706
2712 # Display the exception if input processing failed.
2707 # Display the exception if input processing failed.
2713 if preprocessing_exc_tuple is not None:
2708 if preprocessing_exc_tuple is not None:
2714 self.showtraceback(preprocessing_exc_tuple)
2709 self.showtraceback(preprocessing_exc_tuple)
2715 if store_history:
2710 if store_history:
2716 self.execution_count += 1
2711 self.execution_count += 1
2717 return error_before_exec(preprocessing_exc_tuple[2])
2712 return error_before_exec(preprocessing_exc_tuple[2])
2718
2713
2719 # Our own compiler remembers the __future__ environment. If we want to
2714 # Our own compiler remembers the __future__ environment. If we want to
2720 # run code with a separate __future__ environment, use the default
2715 # run code with a separate __future__ environment, use the default
2721 # compiler
2716 # compiler
2722 compiler = self.compile if shell_futures else CachingCompiler()
2717 compiler = self.compile if shell_futures else CachingCompiler()
2723
2718
2724 with self.builtin_trap:
2719 with self.builtin_trap:
2725 cell_name = self.compile.cache(cell, self.execution_count)
2720 cell_name = self.compile.cache(cell, self.execution_count)
2726
2721
2727 with self.display_trap:
2722 with self.display_trap:
2728 # Compile to bytecode
2723 # Compile to bytecode
2729 try:
2724 try:
2730 code_ast = compiler.ast_parse(cell, filename=cell_name)
2725 code_ast = compiler.ast_parse(cell, filename=cell_name)
2731 except self.custom_exceptions as e:
2726 except self.custom_exceptions as e:
2732 etype, value, tb = sys.exc_info()
2727 etype, value, tb = sys.exc_info()
2733 self.CustomTB(etype, value, tb)
2728 self.CustomTB(etype, value, tb)
2734 return error_before_exec(e)
2729 return error_before_exec(e)
2735 except IndentationError as e:
2730 except IndentationError as e:
2736 self.showindentationerror()
2731 self.showindentationerror()
2737 if store_history:
2732 if store_history:
2738 self.execution_count += 1
2733 self.execution_count += 1
2739 return error_before_exec(e)
2734 return error_before_exec(e)
2740 except (OverflowError, SyntaxError, ValueError, TypeError,
2735 except (OverflowError, SyntaxError, ValueError, TypeError,
2741 MemoryError) as e:
2736 MemoryError) as e:
2742 self.showsyntaxerror()
2737 self.showsyntaxerror()
2743 if store_history:
2738 if store_history:
2744 self.execution_count += 1
2739 self.execution_count += 1
2745 return error_before_exec(e)
2740 return error_before_exec(e)
2746
2741
2747 # Apply AST transformations
2742 # Apply AST transformations
2748 try:
2743 try:
2749 code_ast = self.transform_ast(code_ast)
2744 code_ast = self.transform_ast(code_ast)
2750 except InputRejected as e:
2745 except InputRejected as e:
2751 self.showtraceback()
2746 self.showtraceback()
2752 if store_history:
2747 if store_history:
2753 self.execution_count += 1
2748 self.execution_count += 1
2754 return error_before_exec(e)
2749 return error_before_exec(e)
2755
2750
2756 # Give the displayhook a reference to our ExecutionResult so it
2751 # Give the displayhook a reference to our ExecutionResult so it
2757 # can fill in the output value.
2752 # can fill in the output value.
2758 self.displayhook.exec_result = result
2753 self.displayhook.exec_result = result
2759
2754
2760 # Execute the user code
2755 # Execute the user code
2761 interactivity = "none" if silent else self.ast_node_interactivity
2756 interactivity = "none" if silent else self.ast_node_interactivity
2762 has_raised = self.run_ast_nodes(code_ast.body, cell_name,
2757 has_raised = self.run_ast_nodes(code_ast.body, cell_name,
2763 interactivity=interactivity, compiler=compiler, result=result)
2758 interactivity=interactivity, compiler=compiler, result=result)
2764
2759
2765 self.last_execution_succeeded = not has_raised
2760 self.last_execution_succeeded = not has_raised
2766
2761
2767 # Reset this so later displayed values do not modify the
2762 # Reset this so later displayed values do not modify the
2768 # ExecutionResult
2763 # ExecutionResult
2769 self.displayhook.exec_result = None
2764 self.displayhook.exec_result = None
2770
2765
2771 self.events.trigger('post_execute')
2766 self.events.trigger('post_execute')
2772 if not silent:
2767 if not silent:
2773 self.events.trigger('post_run_cell')
2768 self.events.trigger('post_run_cell')
2774
2769
2775 if store_history:
2770 if store_history:
2776 # Write output to the database. Does nothing unless
2771 # Write output to the database. Does nothing unless
2777 # history output logging is enabled.
2772 # history output logging is enabled.
2778 self.history_manager.store_output(self.execution_count)
2773 self.history_manager.store_output(self.execution_count)
2779 # Each cell is a *single* input, regardless of how many lines it has
2774 # Each cell is a *single* input, regardless of how many lines it has
2780 self.execution_count += 1
2775 self.execution_count += 1
2781
2776
2782 return result
2777 return result
2783
2778
2784 def transform_ast(self, node):
2779 def transform_ast(self, node):
2785 """Apply the AST transformations from self.ast_transformers
2780 """Apply the AST transformations from self.ast_transformers
2786
2781
2787 Parameters
2782 Parameters
2788 ----------
2783 ----------
2789 node : ast.Node
2784 node : ast.Node
2790 The root node to be transformed. Typically called with the ast.Module
2785 The root node to be transformed. Typically called with the ast.Module
2791 produced by parsing user input.
2786 produced by parsing user input.
2792
2787
2793 Returns
2788 Returns
2794 -------
2789 -------
2795 An ast.Node corresponding to the node it was called with. Note that it
2790 An ast.Node corresponding to the node it was called with. Note that it
2796 may also modify the passed object, so don't rely on references to the
2791 may also modify the passed object, so don't rely on references to the
2797 original AST.
2792 original AST.
2798 """
2793 """
2799 for transformer in self.ast_transformers:
2794 for transformer in self.ast_transformers:
2800 try:
2795 try:
2801 node = transformer.visit(node)
2796 node = transformer.visit(node)
2802 except InputRejected:
2797 except InputRejected:
2803 # User-supplied AST transformers can reject an input by raising
2798 # User-supplied AST transformers can reject an input by raising
2804 # an InputRejected. Short-circuit in this case so that we
2799 # an InputRejected. Short-circuit in this case so that we
2805 # don't unregister the transform.
2800 # don't unregister the transform.
2806 raise
2801 raise
2807 except Exception:
2802 except Exception:
2808 warn("AST transformer %r threw an error. It will be unregistered." % transformer)
2803 warn("AST transformer %r threw an error. It will be unregistered." % transformer)
2809 self.ast_transformers.remove(transformer)
2804 self.ast_transformers.remove(transformer)
2810
2805
2811 if self.ast_transformers:
2806 if self.ast_transformers:
2812 ast.fix_missing_locations(node)
2807 ast.fix_missing_locations(node)
2813 return node
2808 return node
2814
2809
2815
2810
2816 def run_ast_nodes(self, nodelist, cell_name, interactivity='last_expr',
2811 def run_ast_nodes(self, nodelist, cell_name, interactivity='last_expr',
2817 compiler=compile, result=None):
2812 compiler=compile, result=None):
2818 """Run a sequence of AST nodes. The execution mode depends on the
2813 """Run a sequence of AST nodes. The execution mode depends on the
2819 interactivity parameter.
2814 interactivity parameter.
2820
2815
2821 Parameters
2816 Parameters
2822 ----------
2817 ----------
2823 nodelist : list
2818 nodelist : list
2824 A sequence of AST nodes to run.
2819 A sequence of AST nodes to run.
2825 cell_name : str
2820 cell_name : str
2826 Will be passed to the compiler as the filename of the cell. Typically
2821 Will be passed to the compiler as the filename of the cell. Typically
2827 the value returned by ip.compile.cache(cell).
2822 the value returned by ip.compile.cache(cell).
2828 interactivity : str
2823 interactivity : str
2829 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
2824 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
2830 run interactively (displaying output from expressions). 'last_expr'
2825 run interactively (displaying output from expressions). 'last_expr'
2831 will run the last node interactively only if it is an expression (i.e.
2826 will run the last node interactively only if it is an expression (i.e.
2832 expressions in loops or other blocks are not displayed. Other values
2827 expressions in loops or other blocks are not displayed. Other values
2833 for this parameter will raise a ValueError.
2828 for this parameter will raise a ValueError.
2834 compiler : callable
2829 compiler : callable
2835 A function with the same interface as the built-in compile(), to turn
2830 A function with the same interface as the built-in compile(), to turn
2836 the AST nodes into code objects. Default is the built-in compile().
2831 the AST nodes into code objects. Default is the built-in compile().
2837 result : ExecutionResult, optional
2832 result : ExecutionResult, optional
2838 An object to store exceptions that occur during execution.
2833 An object to store exceptions that occur during execution.
2839
2834
2840 Returns
2835 Returns
2841 -------
2836 -------
2842 True if an exception occurred while running code, False if it finished
2837 True if an exception occurred while running code, False if it finished
2843 running.
2838 running.
2844 """
2839 """
2845 if not nodelist:
2840 if not nodelist:
2846 return
2841 return
2847
2842
2848 if interactivity == 'last_expr':
2843 if interactivity == 'last_expr':
2849 if isinstance(nodelist[-1], ast.Expr):
2844 if isinstance(nodelist[-1], ast.Expr):
2850 interactivity = "last"
2845 interactivity = "last"
2851 else:
2846 else:
2852 interactivity = "none"
2847 interactivity = "none"
2853
2848
2854 if interactivity == 'none':
2849 if interactivity == 'none':
2855 to_run_exec, to_run_interactive = nodelist, []
2850 to_run_exec, to_run_interactive = nodelist, []
2856 elif interactivity == 'last':
2851 elif interactivity == 'last':
2857 to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:]
2852 to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:]
2858 elif interactivity == 'all':
2853 elif interactivity == 'all':
2859 to_run_exec, to_run_interactive = [], nodelist
2854 to_run_exec, to_run_interactive = [], nodelist
2860 else:
2855 else:
2861 raise ValueError("Interactivity was %r" % interactivity)
2856 raise ValueError("Interactivity was %r" % interactivity)
2862
2857
2863 try:
2858 try:
2864 for i, node in enumerate(to_run_exec):
2859 for i, node in enumerate(to_run_exec):
2865 mod = ast.Module([node])
2860 mod = ast.Module([node])
2866 code = compiler(mod, cell_name, "exec")
2861 code = compiler(mod, cell_name, "exec")
2867 if self.run_code(code, result):
2862 if self.run_code(code, result):
2868 return True
2863 return True
2869
2864
2870 for i, node in enumerate(to_run_interactive):
2865 for i, node in enumerate(to_run_interactive):
2871 mod = ast.Interactive([node])
2866 mod = ast.Interactive([node])
2872 code = compiler(mod, cell_name, "single")
2867 code = compiler(mod, cell_name, "single")
2873 if self.run_code(code, result):
2868 if self.run_code(code, result):
2874 return True
2869 return True
2875
2870
2876 # Flush softspace
2871 # Flush softspace
2877 if softspace(sys.stdout, 0):
2872 if softspace(sys.stdout, 0):
2878 print()
2873 print()
2879
2874
2880 except:
2875 except:
2881 # It's possible to have exceptions raised here, typically by
2876 # It's possible to have exceptions raised here, typically by
2882 # compilation of odd code (such as a naked 'return' outside a
2877 # compilation of odd code (such as a naked 'return' outside a
2883 # function) that did parse but isn't valid. Typically the exception
2878 # function) that did parse but isn't valid. Typically the exception
2884 # is a SyntaxError, but it's safest just to catch anything and show
2879 # is a SyntaxError, but it's safest just to catch anything and show
2885 # the user a traceback.
2880 # the user a traceback.
2886
2881
2887 # We do only one try/except outside the loop to minimize the impact
2882 # We do only one try/except outside the loop to minimize the impact
2888 # on runtime, and also because if any node in the node list is
2883 # on runtime, and also because if any node in the node list is
2889 # broken, we should stop execution completely.
2884 # broken, we should stop execution completely.
2890 if result:
2885 if result:
2891 result.error_before_exec = sys.exc_info()[1]
2886 result.error_before_exec = sys.exc_info()[1]
2892 self.showtraceback()
2887 self.showtraceback()
2893 return True
2888 return True
2894
2889
2895 return False
2890 return False
2896
2891
2897 def run_code(self, code_obj, result=None):
2892 def run_code(self, code_obj, result=None):
2898 """Execute a code object.
2893 """Execute a code object.
2899
2894
2900 When an exception occurs, self.showtraceback() is called to display a
2895 When an exception occurs, self.showtraceback() is called to display a
2901 traceback.
2896 traceback.
2902
2897
2903 Parameters
2898 Parameters
2904 ----------
2899 ----------
2905 code_obj : code object
2900 code_obj : code object
2906 A compiled code object, to be executed
2901 A compiled code object, to be executed
2907 result : ExecutionResult, optional
2902 result : ExecutionResult, optional
2908 An object to store exceptions that occur during execution.
2903 An object to store exceptions that occur during execution.
2909
2904
2910 Returns
2905 Returns
2911 -------
2906 -------
2912 False : successful execution.
2907 False : successful execution.
2913 True : an error occurred.
2908 True : an error occurred.
2914 """
2909 """
2915 # Set our own excepthook in case the user code tries to call it
2910 # Set our own excepthook in case the user code tries to call it
2916 # directly, so that the IPython crash handler doesn't get triggered
2911 # directly, so that the IPython crash handler doesn't get triggered
2917 old_excepthook, sys.excepthook = sys.excepthook, self.excepthook
2912 old_excepthook, sys.excepthook = sys.excepthook, self.excepthook
2918
2913
2919 # we save the original sys.excepthook in the instance, in case config
2914 # we save the original sys.excepthook in the instance, in case config
2920 # code (such as magics) needs access to it.
2915 # code (such as magics) needs access to it.
2921 self.sys_excepthook = old_excepthook
2916 self.sys_excepthook = old_excepthook
2922 outflag = 1 # happens in more places, so it's easier as default
2917 outflag = 1 # happens in more places, so it's easier as default
2923 try:
2918 try:
2924 try:
2919 try:
2925 self.hooks.pre_run_code_hook()
2920 self.hooks.pre_run_code_hook()
2926 #rprint('Running code', repr(code_obj)) # dbg
2921 #rprint('Running code', repr(code_obj)) # dbg
2927 exec(code_obj, self.user_global_ns, self.user_ns)
2922 exec(code_obj, self.user_global_ns, self.user_ns)
2928 finally:
2923 finally:
2929 # Reset our crash handler in place
2924 # Reset our crash handler in place
2930 sys.excepthook = old_excepthook
2925 sys.excepthook = old_excepthook
2931 except SystemExit as e:
2926 except SystemExit as e:
2932 if result is not None:
2927 if result is not None:
2933 result.error_in_exec = e
2928 result.error_in_exec = e
2934 self.showtraceback(exception_only=True)
2929 self.showtraceback(exception_only=True)
2935 warn("To exit: use 'exit', 'quit', or Ctrl-D.", level=1)
2930 warn("To exit: use 'exit', 'quit', or Ctrl-D.", level=1)
2936 except self.custom_exceptions:
2931 except self.custom_exceptions:
2937 etype, value, tb = sys.exc_info()
2932 etype, value, tb = sys.exc_info()
2938 if result is not None:
2933 if result is not None:
2939 result.error_in_exec = value
2934 result.error_in_exec = value
2940 self.CustomTB(etype, value, tb)
2935 self.CustomTB(etype, value, tb)
2941 except:
2936 except:
2942 if result is not None:
2937 if result is not None:
2943 result.error_in_exec = sys.exc_info()[1]
2938 result.error_in_exec = sys.exc_info()[1]
2944 self.showtraceback()
2939 self.showtraceback()
2945 else:
2940 else:
2946 outflag = 0
2941 outflag = 0
2947 return outflag
2942 return outflag
2948
2943
2949 # For backwards compatibility
2944 # For backwards compatibility
2950 runcode = run_code
2945 runcode = run_code
2951
2946
2952 #-------------------------------------------------------------------------
2947 #-------------------------------------------------------------------------
2953 # Things related to GUI support and pylab
2948 # Things related to GUI support and pylab
2954 #-------------------------------------------------------------------------
2949 #-------------------------------------------------------------------------
2955
2950
2956 def enable_gui(self, gui=None):
2951 def enable_gui(self, gui=None):
2957 raise NotImplementedError('Implement enable_gui in a subclass')
2952 raise NotImplementedError('Implement enable_gui in a subclass')
2958
2953
2959 def enable_matplotlib(self, gui=None):
2954 def enable_matplotlib(self, gui=None):
2960 """Enable interactive matplotlib and inline figure support.
2955 """Enable interactive matplotlib and inline figure support.
2961
2956
2962 This takes the following steps:
2957 This takes the following steps:
2963
2958
2964 1. select the appropriate eventloop and matplotlib backend
2959 1. select the appropriate eventloop and matplotlib backend
2965 2. set up matplotlib for interactive use with that backend
2960 2. set up matplotlib for interactive use with that backend
2966 3. configure formatters for inline figure display
2961 3. configure formatters for inline figure display
2967 4. enable the selected gui eventloop
2962 4. enable the selected gui eventloop
2968
2963
2969 Parameters
2964 Parameters
2970 ----------
2965 ----------
2971 gui : optional, string
2966 gui : optional, string
2972 If given, dictates the choice of matplotlib GUI backend to use
2967 If given, dictates the choice of matplotlib GUI backend to use
2973 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
2968 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
2974 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
2969 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
2975 matplotlib (as dictated by the matplotlib build-time options plus the
2970 matplotlib (as dictated by the matplotlib build-time options plus the
2976 user's matplotlibrc configuration file). Note that not all backends
2971 user's matplotlibrc configuration file). Note that not all backends
2977 make sense in all contexts, for example a terminal ipython can't
2972 make sense in all contexts, for example a terminal ipython can't
2978 display figures inline.
2973 display figures inline.
2979 """
2974 """
2980 from IPython.core import pylabtools as pt
2975 from IPython.core import pylabtools as pt
2981 gui, backend = pt.find_gui_and_backend(gui, self.pylab_gui_select)
2976 gui, backend = pt.find_gui_and_backend(gui, self.pylab_gui_select)
2982
2977
2983 if gui != 'inline':
2978 if gui != 'inline':
2984 # If we have our first gui selection, store it
2979 # If we have our first gui selection, store it
2985 if self.pylab_gui_select is None:
2980 if self.pylab_gui_select is None:
2986 self.pylab_gui_select = gui
2981 self.pylab_gui_select = gui
2987 # Otherwise if they are different
2982 # Otherwise if they are different
2988 elif gui != self.pylab_gui_select:
2983 elif gui != self.pylab_gui_select:
2989 print ('Warning: Cannot change to a different GUI toolkit: %s.'
2984 print ('Warning: Cannot change to a different GUI toolkit: %s.'
2990 ' Using %s instead.' % (gui, self.pylab_gui_select))
2985 ' Using %s instead.' % (gui, self.pylab_gui_select))
2991 gui, backend = pt.find_gui_and_backend(self.pylab_gui_select)
2986 gui, backend = pt.find_gui_and_backend(self.pylab_gui_select)
2992
2987
2993 pt.activate_matplotlib(backend)
2988 pt.activate_matplotlib(backend)
2994 pt.configure_inline_support(self, backend)
2989 pt.configure_inline_support(self, backend)
2995
2990
2996 # Now we must activate the gui pylab wants to use, and fix %run to take
2991 # Now we must activate the gui pylab wants to use, and fix %run to take
2997 # plot updates into account
2992 # plot updates into account
2998 self.enable_gui(gui)
2993 self.enable_gui(gui)
2999 self.magics_manager.registry['ExecutionMagics'].default_runner = \
2994 self.magics_manager.registry['ExecutionMagics'].default_runner = \
3000 pt.mpl_runner(self.safe_execfile)
2995 pt.mpl_runner(self.safe_execfile)
3001
2996
3002 return gui, backend
2997 return gui, backend
3003
2998
3004 def enable_pylab(self, gui=None, import_all=True, welcome_message=False):
2999 def enable_pylab(self, gui=None, import_all=True, welcome_message=False):
3005 """Activate pylab support at runtime.
3000 """Activate pylab support at runtime.
3006
3001
3007 This turns on support for matplotlib, preloads into the interactive
3002 This turns on support for matplotlib, preloads into the interactive
3008 namespace all of numpy and pylab, and configures IPython to correctly
3003 namespace all of numpy and pylab, and configures IPython to correctly
3009 interact with the GUI event loop. The GUI backend to be used can be
3004 interact with the GUI event loop. The GUI backend to be used can be
3010 optionally selected with the optional ``gui`` argument.
3005 optionally selected with the optional ``gui`` argument.
3011
3006
3012 This method only adds preloading the namespace to InteractiveShell.enable_matplotlib.
3007 This method only adds preloading the namespace to InteractiveShell.enable_matplotlib.
3013
3008
3014 Parameters
3009 Parameters
3015 ----------
3010 ----------
3016 gui : optional, string
3011 gui : optional, string
3017 If given, dictates the choice of matplotlib GUI backend to use
3012 If given, dictates the choice of matplotlib GUI backend to use
3018 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
3013 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
3019 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
3014 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
3020 matplotlib (as dictated by the matplotlib build-time options plus the
3015 matplotlib (as dictated by the matplotlib build-time options plus the
3021 user's matplotlibrc configuration file). Note that not all backends
3016 user's matplotlibrc configuration file). Note that not all backends
3022 make sense in all contexts, for example a terminal ipython can't
3017 make sense in all contexts, for example a terminal ipython can't
3023 display figures inline.
3018 display figures inline.
3024 import_all : optional, bool, default: True
3019 import_all : optional, bool, default: True
3025 Whether to do `from numpy import *` and `from pylab import *`
3020 Whether to do `from numpy import *` and `from pylab import *`
3026 in addition to module imports.
3021 in addition to module imports.
3027 welcome_message : deprecated
3022 welcome_message : deprecated
3028 This argument is ignored, no welcome message will be displayed.
3023 This argument is ignored, no welcome message will be displayed.
3029 """
3024 """
3030 from IPython.core.pylabtools import import_pylab
3025 from IPython.core.pylabtools import import_pylab
3031
3026
3032 gui, backend = self.enable_matplotlib(gui)
3027 gui, backend = self.enable_matplotlib(gui)
3033
3028
3034 # We want to prevent the loading of pylab to pollute the user's
3029 # We want to prevent the loading of pylab to pollute the user's
3035 # namespace as shown by the %who* magics, so we execute the activation
3030 # namespace as shown by the %who* magics, so we execute the activation
3036 # code in an empty namespace, and we update *both* user_ns and
3031 # code in an empty namespace, and we update *both* user_ns and
3037 # user_ns_hidden with this information.
3032 # user_ns_hidden with this information.
3038 ns = {}
3033 ns = {}
3039 import_pylab(ns, import_all)
3034 import_pylab(ns, import_all)
3040 # warn about clobbered names
3035 # warn about clobbered names
3041 ignored = {"__builtins__"}
3036 ignored = {"__builtins__"}
3042 both = set(ns).intersection(self.user_ns).difference(ignored)
3037 both = set(ns).intersection(self.user_ns).difference(ignored)
3043 clobbered = [ name for name in both if self.user_ns[name] is not ns[name] ]
3038 clobbered = [ name for name in both if self.user_ns[name] is not ns[name] ]
3044 self.user_ns.update(ns)
3039 self.user_ns.update(ns)
3045 self.user_ns_hidden.update(ns)
3040 self.user_ns_hidden.update(ns)
3046 return gui, backend, clobbered
3041 return gui, backend, clobbered
3047
3042
3048 #-------------------------------------------------------------------------
3043 #-------------------------------------------------------------------------
3049 # Utilities
3044 # Utilities
3050 #-------------------------------------------------------------------------
3045 #-------------------------------------------------------------------------
3051
3046
3052 def var_expand(self, cmd, depth=0, formatter=DollarFormatter()):
3047 def var_expand(self, cmd, depth=0, formatter=DollarFormatter()):
3053 """Expand python variables in a string.
3048 """Expand python variables in a string.
3054
3049
3055 The depth argument indicates how many frames above the caller should
3050 The depth argument indicates how many frames above the caller should
3056 be walked to look for the local namespace where to expand variables.
3051 be walked to look for the local namespace where to expand variables.
3057
3052
3058 The global namespace for expansion is always the user's interactive
3053 The global namespace for expansion is always the user's interactive
3059 namespace.
3054 namespace.
3060 """
3055 """
3061 ns = self.user_ns.copy()
3056 ns = self.user_ns.copy()
3062 try:
3057 try:
3063 frame = sys._getframe(depth+1)
3058 frame = sys._getframe(depth+1)
3064 except ValueError:
3059 except ValueError:
3065 # This is thrown if there aren't that many frames on the stack,
3060 # This is thrown if there aren't that many frames on the stack,
3066 # e.g. if a script called run_line_magic() directly.
3061 # e.g. if a script called run_line_magic() directly.
3067 pass
3062 pass
3068 else:
3063 else:
3069 ns.update(frame.f_locals)
3064 ns.update(frame.f_locals)
3070
3065
3071 try:
3066 try:
3072 # We have to use .vformat() here, because 'self' is a valid and common
3067 # We have to use .vformat() here, because 'self' is a valid and common
3073 # name, and expanding **ns for .format() would make it collide with
3068 # name, and expanding **ns for .format() would make it collide with
3074 # the 'self' argument of the method.
3069 # the 'self' argument of the method.
3075 cmd = formatter.vformat(cmd, args=[], kwargs=ns)
3070 cmd = formatter.vformat(cmd, args=[], kwargs=ns)
3076 except Exception:
3071 except Exception:
3077 # if formatter couldn't format, just let it go untransformed
3072 # if formatter couldn't format, just let it go untransformed
3078 pass
3073 pass
3079 return cmd
3074 return cmd
3080
3075
3081 def mktempfile(self, data=None, prefix='ipython_edit_'):
3076 def mktempfile(self, data=None, prefix='ipython_edit_'):
3082 """Make a new tempfile and return its filename.
3077 """Make a new tempfile and return its filename.
3083
3078
3084 This makes a call to tempfile.mkstemp (created in a tempfile.mkdtemp),
3079 This makes a call to tempfile.mkstemp (created in a tempfile.mkdtemp),
3085 but it registers the created filename internally so ipython cleans it up
3080 but it registers the created filename internally so ipython cleans it up
3086 at exit time.
3081 at exit time.
3087
3082
3088 Optional inputs:
3083 Optional inputs:
3089
3084
3090 - data(None): if data is given, it gets written out to the temp file
3085 - data(None): if data is given, it gets written out to the temp file
3091 immediately, and the file is closed again."""
3086 immediately, and the file is closed again."""
3092
3087
3093 dirname = tempfile.mkdtemp(prefix=prefix)
3088 dirname = tempfile.mkdtemp(prefix=prefix)
3094 self.tempdirs.append(dirname)
3089 self.tempdirs.append(dirname)
3095
3090
3096 handle, filename = tempfile.mkstemp('.py', prefix, dir=dirname)
3091 handle, filename = tempfile.mkstemp('.py', prefix, dir=dirname)
3097 os.close(handle) # On Windows, there can only be one open handle on a file
3092 os.close(handle) # On Windows, there can only be one open handle on a file
3098 self.tempfiles.append(filename)
3093 self.tempfiles.append(filename)
3099
3094
3100 if data:
3095 if data:
3101 tmp_file = open(filename,'w')
3096 tmp_file = open(filename,'w')
3102 tmp_file.write(data)
3097 tmp_file.write(data)
3103 tmp_file.close()
3098 tmp_file.close()
3104 return filename
3099 return filename
3105
3100
3106 @undoc
3101 @undoc
3107 def write(self,data):
3102 def write(self,data):
3108 """DEPRECATED: Write a string to the default output"""
3103 """DEPRECATED: Write a string to the default output"""
3109 warn('InteractiveShell.write() is deprecated, use sys.stdout instead',
3104 warn('InteractiveShell.write() is deprecated, use sys.stdout instead',
3110 DeprecationWarning, stacklevel=2)
3105 DeprecationWarning, stacklevel=2)
3111 sys.stdout.write(data)
3106 sys.stdout.write(data)
3112
3107
3113 @undoc
3108 @undoc
3114 def write_err(self,data):
3109 def write_err(self,data):
3115 """DEPRECATED: Write a string to the default error output"""
3110 """DEPRECATED: Write a string to the default error output"""
3116 warn('InteractiveShell.write_err() is deprecated, use sys.stderr instead',
3111 warn('InteractiveShell.write_err() is deprecated, use sys.stderr instead',
3117 DeprecationWarning, stacklevel=2)
3112 DeprecationWarning, stacklevel=2)
3118 sys.stderr.write(data)
3113 sys.stderr.write(data)
3119
3114
3120 def ask_yes_no(self, prompt, default=None, interrupt=None):
3115 def ask_yes_no(self, prompt, default=None, interrupt=None):
3121 if self.quiet:
3116 if self.quiet:
3122 return True
3117 return True
3123 return ask_yes_no(prompt,default,interrupt)
3118 return ask_yes_no(prompt,default,interrupt)
3124
3119
3125 def show_usage(self):
3120 def show_usage(self):
3126 """Show a usage message"""
3121 """Show a usage message"""
3127 page.page(IPython.core.usage.interactive_usage)
3122 page.page(IPython.core.usage.interactive_usage)
3128
3123
3129 def extract_input_lines(self, range_str, raw=False):
3124 def extract_input_lines(self, range_str, raw=False):
3130 """Return as a string a set of input history slices.
3125 """Return as a string a set of input history slices.
3131
3126
3132 Parameters
3127 Parameters
3133 ----------
3128 ----------
3134 range_str : string
3129 range_str : string
3135 The set of slices is given as a string, like "~5/6-~4/2 4:8 9",
3130 The set of slices is given as a string, like "~5/6-~4/2 4:8 9",
3136 since this function is for use by magic functions which get their
3131 since this function is for use by magic functions which get their
3137 arguments as strings. The number before the / is the session
3132 arguments as strings. The number before the / is the session
3138 number: ~n goes n back from the current session.
3133 number: ~n goes n back from the current session.
3139
3134
3140 raw : bool, optional
3135 raw : bool, optional
3141 By default, the processed input is used. If this is true, the raw
3136 By default, the processed input is used. If this is true, the raw
3142 input history is used instead.
3137 input history is used instead.
3143
3138
3144 Notes
3139 Notes
3145 -----
3140 -----
3146
3141
3147 Slices can be described with two notations:
3142 Slices can be described with two notations:
3148
3143
3149 * ``N:M`` -> standard python form, means including items N...(M-1).
3144 * ``N:M`` -> standard python form, means including items N...(M-1).
3150 * ``N-M`` -> include items N..M (closed endpoint).
3145 * ``N-M`` -> include items N..M (closed endpoint).
3151 """
3146 """
3152 lines = self.history_manager.get_range_by_str(range_str, raw=raw)
3147 lines = self.history_manager.get_range_by_str(range_str, raw=raw)
3153 return "\n".join(x for _, _, x in lines)
3148 return "\n".join(x for _, _, x in lines)
3154
3149
3155 def find_user_code(self, target, raw=True, py_only=False, skip_encoding_cookie=True, search_ns=False):
3150 def find_user_code(self, target, raw=True, py_only=False, skip_encoding_cookie=True, search_ns=False):
3156 """Get a code string from history, file, url, or a string or macro.
3151 """Get a code string from history, file, url, or a string or macro.
3157
3152
3158 This is mainly used by magic functions.
3153 This is mainly used by magic functions.
3159
3154
3160 Parameters
3155 Parameters
3161 ----------
3156 ----------
3162
3157
3163 target : str
3158 target : str
3164
3159
3165 A string specifying code to retrieve. This will be tried respectively
3160 A string specifying code to retrieve. This will be tried respectively
3166 as: ranges of input history (see %history for syntax), url,
3161 as: ranges of input history (see %history for syntax), url,
3167 corresponding .py file, filename, or an expression evaluating to a
3162 corresponding .py file, filename, or an expression evaluating to a
3168 string or Macro in the user namespace.
3163 string or Macro in the user namespace.
3169
3164
3170 raw : bool
3165 raw : bool
3171 If true (default), retrieve raw history. Has no effect on the other
3166 If true (default), retrieve raw history. Has no effect on the other
3172 retrieval mechanisms.
3167 retrieval mechanisms.
3173
3168
3174 py_only : bool (default False)
3169 py_only : bool (default False)
3175 Only try to fetch python code, do not try alternative methods to decode file
3170 Only try to fetch python code, do not try alternative methods to decode file
3176 if unicode fails.
3171 if unicode fails.
3177
3172
3178 Returns
3173 Returns
3179 -------
3174 -------
3180 A string of code.
3175 A string of code.
3181
3176
3182 ValueError is raised if nothing is found, and TypeError if it evaluates
3177 ValueError is raised if nothing is found, and TypeError if it evaluates
3183 to an object of another type. In each case, .args[0] is a printable
3178 to an object of another type. In each case, .args[0] is a printable
3184 message.
3179 message.
3185 """
3180 """
3186 code = self.extract_input_lines(target, raw=raw) # Grab history
3181 code = self.extract_input_lines(target, raw=raw) # Grab history
3187 if code:
3182 if code:
3188 return code
3183 return code
3189 try:
3184 try:
3190 if target.startswith(('http://', 'https://')):
3185 if target.startswith(('http://', 'https://')):
3191 return openpy.read_py_url(target, skip_encoding_cookie=skip_encoding_cookie)
3186 return openpy.read_py_url(target, skip_encoding_cookie=skip_encoding_cookie)
3192 except UnicodeDecodeError:
3187 except UnicodeDecodeError:
3193 if not py_only :
3188 if not py_only :
3194 # Deferred import
3189 # Deferred import
3195 try:
3190 try:
3196 from urllib.request import urlopen # Py3
3191 from urllib.request import urlopen # Py3
3197 except ImportError:
3192 except ImportError:
3198 from urllib import urlopen
3193 from urllib import urlopen
3199 response = urlopen(target)
3194 response = urlopen(target)
3200 return response.read().decode('latin1')
3195 return response.read().decode('latin1')
3201 raise ValueError(("'%s' seem to be unreadable.") % target)
3196 raise ValueError(("'%s' seem to be unreadable.") % target)
3202
3197
3203 potential_target = [target]
3198 potential_target = [target]
3204 try :
3199 try :
3205 potential_target.insert(0,get_py_filename(target))
3200 potential_target.insert(0,get_py_filename(target))
3206 except IOError:
3201 except IOError:
3207 pass
3202 pass
3208
3203
3209 for tgt in potential_target :
3204 for tgt in potential_target :
3210 if os.path.isfile(tgt): # Read file
3205 if os.path.isfile(tgt): # Read file
3211 try :
3206 try :
3212 return openpy.read_py_file(tgt, skip_encoding_cookie=skip_encoding_cookie)
3207 return openpy.read_py_file(tgt, skip_encoding_cookie=skip_encoding_cookie)
3213 except UnicodeDecodeError :
3208 except UnicodeDecodeError :
3214 if not py_only :
3209 if not py_only :
3215 with io_open(tgt,'r', encoding='latin1') as f :
3210 with io_open(tgt,'r', encoding='latin1') as f :
3216 return f.read()
3211 return f.read()
3217 raise ValueError(("'%s' seem to be unreadable.") % target)
3212 raise ValueError(("'%s' seem to be unreadable.") % target)
3218 elif os.path.isdir(os.path.expanduser(tgt)):
3213 elif os.path.isdir(os.path.expanduser(tgt)):
3219 raise ValueError("'%s' is a directory, not a regular file." % target)
3214 raise ValueError("'%s' is a directory, not a regular file." % target)
3220
3215
3221 if search_ns:
3216 if search_ns:
3222 # Inspect namespace to load object source
3217 # Inspect namespace to load object source
3223 object_info = self.object_inspect(target, detail_level=1)
3218 object_info = self.object_inspect(target, detail_level=1)
3224 if object_info['found'] and object_info['source']:
3219 if object_info['found'] and object_info['source']:
3225 return object_info['source']
3220 return object_info['source']
3226
3221
3227 try: # User namespace
3222 try: # User namespace
3228 codeobj = eval(target, self.user_ns)
3223 codeobj = eval(target, self.user_ns)
3229 except Exception:
3224 except Exception:
3230 raise ValueError(("'%s' was not found in history, as a file, url, "
3225 raise ValueError(("'%s' was not found in history, as a file, url, "
3231 "nor in the user namespace.") % target)
3226 "nor in the user namespace.") % target)
3232
3227
3233 if isinstance(codeobj, string_types):
3228 if isinstance(codeobj, string_types):
3234 return codeobj
3229 return codeobj
3235 elif isinstance(codeobj, Macro):
3230 elif isinstance(codeobj, Macro):
3236 return codeobj.value
3231 return codeobj.value
3237
3232
3238 raise TypeError("%s is neither a string nor a macro." % target,
3233 raise TypeError("%s is neither a string nor a macro." % target,
3239 codeobj)
3234 codeobj)
3240
3235
3241 #-------------------------------------------------------------------------
3236 #-------------------------------------------------------------------------
3242 # Things related to IPython exiting
3237 # Things related to IPython exiting
3243 #-------------------------------------------------------------------------
3238 #-------------------------------------------------------------------------
3244 def atexit_operations(self):
3239 def atexit_operations(self):
3245 """This will be executed at the time of exit.
3240 """This will be executed at the time of exit.
3246
3241
3247 Cleanup operations and saving of persistent data that is done
3242 Cleanup operations and saving of persistent data that is done
3248 unconditionally by IPython should be performed here.
3243 unconditionally by IPython should be performed here.
3249
3244
3250 For things that may depend on startup flags or platform specifics (such
3245 For things that may depend on startup flags or platform specifics (such
3251 as having readline or not), register a separate atexit function in the
3246 as having readline or not), register a separate atexit function in the
3252 code that has the appropriate information, rather than trying to
3247 code that has the appropriate information, rather than trying to
3253 clutter
3248 clutter
3254 """
3249 """
3255 # Close the history session (this stores the end time and line count)
3250 # Close the history session (this stores the end time and line count)
3256 # this must be *before* the tempfile cleanup, in case of temporary
3251 # this must be *before* the tempfile cleanup, in case of temporary
3257 # history db
3252 # history db
3258 self.history_manager.end_session()
3253 self.history_manager.end_session()
3259
3254
3260 # Cleanup all tempfiles and folders left around
3255 # Cleanup all tempfiles and folders left around
3261 for tfile in self.tempfiles:
3256 for tfile in self.tempfiles:
3262 try:
3257 try:
3263 os.unlink(tfile)
3258 os.unlink(tfile)
3264 except OSError:
3259 except OSError:
3265 pass
3260 pass
3266
3261
3267 for tdir in self.tempdirs:
3262 for tdir in self.tempdirs:
3268 try:
3263 try:
3269 os.rmdir(tdir)
3264 os.rmdir(tdir)
3270 except OSError:
3265 except OSError:
3271 pass
3266 pass
3272
3267
3273 # Clear all user namespaces to release all references cleanly.
3268 # Clear all user namespaces to release all references cleanly.
3274 self.reset(new_session=False)
3269 self.reset(new_session=False)
3275
3270
3276 # Run user hooks
3271 # Run user hooks
3277 self.hooks.shutdown_hook()
3272 self.hooks.shutdown_hook()
3278
3273
3279 def cleanup(self):
3274 def cleanup(self):
3280 self.restore_sys_module_state()
3275 self.restore_sys_module_state()
3281
3276
3282
3277
3283 # Overridden in terminal subclass to change prompts
3278 # Overridden in terminal subclass to change prompts
3284 def switch_doctest_mode(self, mode):
3279 def switch_doctest_mode(self, mode):
3285 pass
3280 pass
3286
3281
3287
3282
3288 class InteractiveShellABC(with_metaclass(abc.ABCMeta, object)):
3283 class InteractiveShellABC(with_metaclass(abc.ABCMeta, object)):
3289 """An abstract base class for InteractiveShell."""
3284 """An abstract base class for InteractiveShell."""
3290
3285
3291 InteractiveShellABC.register(InteractiveShell)
3286 InteractiveShellABC.register(InteractiveShell)
@@ -1,599 +1,584 b''
1 """Implementation of basic magic functions."""
1 """Implementation of basic magic functions."""
2
2
3 from __future__ import print_function
3 from __future__ import print_function
4 from __future__ import absolute_import
4 from __future__ import absolute_import
5
5
6 import io
6 import io
7 import sys
7 import sys
8 from pprint import pformat
8 from pprint import pformat
9
9
10 from IPython.core import magic_arguments, page
10 from IPython.core import magic_arguments, page
11 from IPython.core.error import UsageError
11 from IPython.core.error import UsageError
12 from IPython.core.magic import Magics, magics_class, line_magic, magic_escapes
12 from IPython.core.magic import Magics, magics_class, line_magic, magic_escapes
13 from IPython.utils.text import format_screen, dedent, indent
13 from IPython.utils.text import format_screen, dedent, indent
14 from IPython.testing.skipdoctest import skip_doctest
14 from IPython.testing.skipdoctest import skip_doctest
15 from IPython.utils.ipstruct import Struct
15 from IPython.utils.ipstruct import Struct
16 from IPython.utils.py3compat import unicode_type
16 from IPython.utils.py3compat import unicode_type
17 from warnings import warn
17 from warnings import warn
18 from logging import error
18 from logging import error
19
19
20
20
21 class MagicsDisplay(object):
21 class MagicsDisplay(object):
22 def __init__(self, magics_manager):
22 def __init__(self, magics_manager):
23 self.magics_manager = magics_manager
23 self.magics_manager = magics_manager
24
24
25 def _lsmagic(self):
25 def _lsmagic(self):
26 """The main implementation of the %lsmagic"""
26 """The main implementation of the %lsmagic"""
27 mesc = magic_escapes['line']
27 mesc = magic_escapes['line']
28 cesc = magic_escapes['cell']
28 cesc = magic_escapes['cell']
29 mman = self.magics_manager
29 mman = self.magics_manager
30 magics = mman.lsmagic()
30 magics = mman.lsmagic()
31 out = ['Available line magics:',
31 out = ['Available line magics:',
32 mesc + (' '+mesc).join(sorted(magics['line'])),
32 mesc + (' '+mesc).join(sorted(magics['line'])),
33 '',
33 '',
34 'Available cell magics:',
34 'Available cell magics:',
35 cesc + (' '+cesc).join(sorted(magics['cell'])),
35 cesc + (' '+cesc).join(sorted(magics['cell'])),
36 '',
36 '',
37 mman.auto_status()]
37 mman.auto_status()]
38 return '\n'.join(out)
38 return '\n'.join(out)
39
39
40 def _repr_pretty_(self, p, cycle):
40 def _repr_pretty_(self, p, cycle):
41 p.text(self._lsmagic())
41 p.text(self._lsmagic())
42
42
43 def __str__(self):
43 def __str__(self):
44 return self._lsmagic()
44 return self._lsmagic()
45
45
46 def _jsonable(self):
46 def _jsonable(self):
47 """turn magics dict into jsonable dict of the same structure
47 """turn magics dict into jsonable dict of the same structure
48
48
49 replaces object instances with their class names as strings
49 replaces object instances with their class names as strings
50 """
50 """
51 magic_dict = {}
51 magic_dict = {}
52 mman = self.magics_manager
52 mman = self.magics_manager
53 magics = mman.lsmagic()
53 magics = mman.lsmagic()
54 for key, subdict in magics.items():
54 for key, subdict in magics.items():
55 d = {}
55 d = {}
56 magic_dict[key] = d
56 magic_dict[key] = d
57 for name, obj in subdict.items():
57 for name, obj in subdict.items():
58 try:
58 try:
59 classname = obj.__self__.__class__.__name__
59 classname = obj.__self__.__class__.__name__
60 except AttributeError:
60 except AttributeError:
61 classname = 'Other'
61 classname = 'Other'
62
62
63 d[name] = classname
63 d[name] = classname
64 return magic_dict
64 return magic_dict
65
65
66 def _repr_json_(self):
66 def _repr_json_(self):
67 return self._jsonable()
67 return self._jsonable()
68
68
69
69
70 @magics_class
70 @magics_class
71 class BasicMagics(Magics):
71 class BasicMagics(Magics):
72 """Magics that provide central IPython functionality.
72 """Magics that provide central IPython functionality.
73
73
74 These are various magics that don't fit into specific categories but that
74 These are various magics that don't fit into specific categories but that
75 are all part of the base 'IPython experience'."""
75 are all part of the base 'IPython experience'."""
76
76
77 @magic_arguments.magic_arguments()
77 @magic_arguments.magic_arguments()
78 @magic_arguments.argument(
78 @magic_arguments.argument(
79 '-l', '--line', action='store_true',
79 '-l', '--line', action='store_true',
80 help="""Create a line magic alias."""
80 help="""Create a line magic alias."""
81 )
81 )
82 @magic_arguments.argument(
82 @magic_arguments.argument(
83 '-c', '--cell', action='store_true',
83 '-c', '--cell', action='store_true',
84 help="""Create a cell magic alias."""
84 help="""Create a cell magic alias."""
85 )
85 )
86 @magic_arguments.argument(
86 @magic_arguments.argument(
87 'name',
87 'name',
88 help="""Name of the magic to be created."""
88 help="""Name of the magic to be created."""
89 )
89 )
90 @magic_arguments.argument(
90 @magic_arguments.argument(
91 'target',
91 'target',
92 help="""Name of the existing line or cell magic."""
92 help="""Name of the existing line or cell magic."""
93 )
93 )
94 @line_magic
94 @line_magic
95 def alias_magic(self, line=''):
95 def alias_magic(self, line=''):
96 """Create an alias for an existing line or cell magic.
96 """Create an alias for an existing line or cell magic.
97
97
98 Examples
98 Examples
99 --------
99 --------
100 ::
100 ::
101
101
102 In [1]: %alias_magic t timeit
102 In [1]: %alias_magic t timeit
103 Created `%t` as an alias for `%timeit`.
103 Created `%t` as an alias for `%timeit`.
104 Created `%%t` as an alias for `%%timeit`.
104 Created `%%t` as an alias for `%%timeit`.
105
105
106 In [2]: %t -n1 pass
106 In [2]: %t -n1 pass
107 1 loops, best of 3: 954 ns per loop
107 1 loops, best of 3: 954 ns per loop
108
108
109 In [3]: %%t -n1
109 In [3]: %%t -n1
110 ...: pass
110 ...: pass
111 ...:
111 ...:
112 1 loops, best of 3: 954 ns per loop
112 1 loops, best of 3: 954 ns per loop
113
113
114 In [4]: %alias_magic --cell whereami pwd
114 In [4]: %alias_magic --cell whereami pwd
115 UsageError: Cell magic function `%%pwd` not found.
115 UsageError: Cell magic function `%%pwd` not found.
116 In [5]: %alias_magic --line whereami pwd
116 In [5]: %alias_magic --line whereami pwd
117 Created `%whereami` as an alias for `%pwd`.
117 Created `%whereami` as an alias for `%pwd`.
118
118
119 In [6]: %whereami
119 In [6]: %whereami
120 Out[6]: u'/home/testuser'
120 Out[6]: u'/home/testuser'
121 """
121 """
122 args = magic_arguments.parse_argstring(self.alias_magic, line)
122 args = magic_arguments.parse_argstring(self.alias_magic, line)
123 shell = self.shell
123 shell = self.shell
124 mman = self.shell.magics_manager
124 mman = self.shell.magics_manager
125 escs = ''.join(magic_escapes.values())
125 escs = ''.join(magic_escapes.values())
126
126
127 target = args.target.lstrip(escs)
127 target = args.target.lstrip(escs)
128 name = args.name.lstrip(escs)
128 name = args.name.lstrip(escs)
129
129
130 # Find the requested magics.
130 # Find the requested magics.
131 m_line = shell.find_magic(target, 'line')
131 m_line = shell.find_magic(target, 'line')
132 m_cell = shell.find_magic(target, 'cell')
132 m_cell = shell.find_magic(target, 'cell')
133 if args.line and m_line is None:
133 if args.line and m_line is None:
134 raise UsageError('Line magic function `%s%s` not found.' %
134 raise UsageError('Line magic function `%s%s` not found.' %
135 (magic_escapes['line'], target))
135 (magic_escapes['line'], target))
136 if args.cell and m_cell is None:
136 if args.cell and m_cell is None:
137 raise UsageError('Cell magic function `%s%s` not found.' %
137 raise UsageError('Cell magic function `%s%s` not found.' %
138 (magic_escapes['cell'], target))
138 (magic_escapes['cell'], target))
139
139
140 # If --line and --cell are not specified, default to the ones
140 # If --line and --cell are not specified, default to the ones
141 # that are available.
141 # that are available.
142 if not args.line and not args.cell:
142 if not args.line and not args.cell:
143 if not m_line and not m_cell:
143 if not m_line and not m_cell:
144 raise UsageError(
144 raise UsageError(
145 'No line or cell magic with name `%s` found.' % target
145 'No line or cell magic with name `%s` found.' % target
146 )
146 )
147 args.line = bool(m_line)
147 args.line = bool(m_line)
148 args.cell = bool(m_cell)
148 args.cell = bool(m_cell)
149
149
150 if args.line:
150 if args.line:
151 mman.register_alias(name, target, 'line')
151 mman.register_alias(name, target, 'line')
152 print('Created `%s%s` as an alias for `%s%s`.' % (
152 print('Created `%s%s` as an alias for `%s%s`.' % (
153 magic_escapes['line'], name,
153 magic_escapes['line'], name,
154 magic_escapes['line'], target))
154 magic_escapes['line'], target))
155
155
156 if args.cell:
156 if args.cell:
157 mman.register_alias(name, target, 'cell')
157 mman.register_alias(name, target, 'cell')
158 print('Created `%s%s` as an alias for `%s%s`.' % (
158 print('Created `%s%s` as an alias for `%s%s`.' % (
159 magic_escapes['cell'], name,
159 magic_escapes['cell'], name,
160 magic_escapes['cell'], target))
160 magic_escapes['cell'], target))
161
161
162 @line_magic
162 @line_magic
163 def lsmagic(self, parameter_s=''):
163 def lsmagic(self, parameter_s=''):
164 """List currently available magic functions."""
164 """List currently available magic functions."""
165 return MagicsDisplay(self.shell.magics_manager)
165 return MagicsDisplay(self.shell.magics_manager)
166
166
167 def _magic_docs(self, brief=False, rest=False):
167 def _magic_docs(self, brief=False, rest=False):
168 """Return docstrings from magic functions."""
168 """Return docstrings from magic functions."""
169 mman = self.shell.magics_manager
169 mman = self.shell.magics_manager
170 docs = mman.lsmagic_docs(brief, missing='No documentation')
170 docs = mman.lsmagic_docs(brief, missing='No documentation')
171
171
172 if rest:
172 if rest:
173 format_string = '**%s%s**::\n\n%s\n\n'
173 format_string = '**%s%s**::\n\n%s\n\n'
174 else:
174 else:
175 format_string = '%s%s:\n%s\n'
175 format_string = '%s%s:\n%s\n'
176
176
177 return ''.join(
177 return ''.join(
178 [format_string % (magic_escapes['line'], fname,
178 [format_string % (magic_escapes['line'], fname,
179 indent(dedent(fndoc)))
179 indent(dedent(fndoc)))
180 for fname, fndoc in sorted(docs['line'].items())]
180 for fname, fndoc in sorted(docs['line'].items())]
181 +
181 +
182 [format_string % (magic_escapes['cell'], fname,
182 [format_string % (magic_escapes['cell'], fname,
183 indent(dedent(fndoc)))
183 indent(dedent(fndoc)))
184 for fname, fndoc in sorted(docs['cell'].items())]
184 for fname, fndoc in sorted(docs['cell'].items())]
185 )
185 )
186
186
187 @line_magic
187 @line_magic
188 def magic(self, parameter_s=''):
188 def magic(self, parameter_s=''):
189 """Print information about the magic function system.
189 """Print information about the magic function system.
190
190
191 Supported formats: -latex, -brief, -rest
191 Supported formats: -latex, -brief, -rest
192 """
192 """
193
193
194 mode = ''
194 mode = ''
195 try:
195 try:
196 mode = parameter_s.split()[0][1:]
196 mode = parameter_s.split()[0][1:]
197 except IndexError:
197 except IndexError:
198 pass
198 pass
199
199
200 brief = (mode == 'brief')
200 brief = (mode == 'brief')
201 rest = (mode == 'rest')
201 rest = (mode == 'rest')
202 magic_docs = self._magic_docs(brief, rest)
202 magic_docs = self._magic_docs(brief, rest)
203
203
204 if mode == 'latex':
204 if mode == 'latex':
205 print(self.format_latex(magic_docs))
205 print(self.format_latex(magic_docs))
206 return
206 return
207 else:
207 else:
208 magic_docs = format_screen(magic_docs)
208 magic_docs = format_screen(magic_docs)
209
209
210 out = ["""
210 out = ["""
211 IPython's 'magic' functions
211 IPython's 'magic' functions
212 ===========================
212 ===========================
213
213
214 The magic function system provides a series of functions which allow you to
214 The magic function system provides a series of functions which allow you to
215 control the behavior of IPython itself, plus a lot of system-type
215 control the behavior of IPython itself, plus a lot of system-type
216 features. There are two kinds of magics, line-oriented and cell-oriented.
216 features. There are two kinds of magics, line-oriented and cell-oriented.
217
217
218 Line magics are prefixed with the % character and work much like OS
218 Line magics are prefixed with the % character and work much like OS
219 command-line calls: they get as an argument the rest of the line, where
219 command-line calls: they get as an argument the rest of the line, where
220 arguments are passed without parentheses or quotes. For example, this will
220 arguments are passed without parentheses or quotes. For example, this will
221 time the given statement::
221 time the given statement::
222
222
223 %timeit range(1000)
223 %timeit range(1000)
224
224
225 Cell magics are prefixed with a double %%, and they are functions that get as
225 Cell magics are prefixed with a double %%, and they are functions that get as
226 an argument not only the rest of the line, but also the lines below it in a
226 an argument not only the rest of the line, but also the lines below it in a
227 separate argument. These magics are called with two arguments: the rest of the
227 separate argument. These magics are called with two arguments: the rest of the
228 call line and the body of the cell, consisting of the lines below the first.
228 call line and the body of the cell, consisting of the lines below the first.
229 For example::
229 For example::
230
230
231 %%timeit x = numpy.random.randn((100, 100))
231 %%timeit x = numpy.random.randn((100, 100))
232 numpy.linalg.svd(x)
232 numpy.linalg.svd(x)
233
233
234 will time the execution of the numpy svd routine, running the assignment of x
234 will time the execution of the numpy svd routine, running the assignment of x
235 as part of the setup phase, which is not timed.
235 as part of the setup phase, which is not timed.
236
236
237 In a line-oriented client (the terminal or Qt console IPython), starting a new
237 In a line-oriented client (the terminal or Qt console IPython), starting a new
238 input with %% will automatically enter cell mode, and IPython will continue
238 input with %% will automatically enter cell mode, and IPython will continue
239 reading input until a blank line is given. In the notebook, simply type the
239 reading input until a blank line is given. In the notebook, simply type the
240 whole cell as one entity, but keep in mind that the %% escape can only be at
240 whole cell as one entity, but keep in mind that the %% escape can only be at
241 the very start of the cell.
241 the very start of the cell.
242
242
243 NOTE: If you have 'automagic' enabled (via the command line option or with the
243 NOTE: If you have 'automagic' enabled (via the command line option or with the
244 %automagic function), you don't need to type in the % explicitly for line
244 %automagic function), you don't need to type in the % explicitly for line
245 magics; cell magics always require an explicit '%%' escape. By default,
245 magics; cell magics always require an explicit '%%' escape. By default,
246 IPython ships with automagic on, so you should only rarely need the % escape.
246 IPython ships with automagic on, so you should only rarely need the % escape.
247
247
248 Example: typing '%cd mydir' (without the quotes) changes your working directory
248 Example: typing '%cd mydir' (without the quotes) changes your working directory
249 to 'mydir', if it exists.
249 to 'mydir', if it exists.
250
250
251 For a list of the available magic functions, use %lsmagic. For a description
251 For a list of the available magic functions, use %lsmagic. For a description
252 of any of them, type %magic_name?, e.g. '%cd?'.
252 of any of them, type %magic_name?, e.g. '%cd?'.
253
253
254 Currently the magic system has the following functions:""",
254 Currently the magic system has the following functions:""",
255 magic_docs,
255 magic_docs,
256 "Summary of magic functions (from %slsmagic):" % magic_escapes['line'],
256 "Summary of magic functions (from %slsmagic):" % magic_escapes['line'],
257 str(self.lsmagic()),
257 str(self.lsmagic()),
258 ]
258 ]
259 page.page('\n'.join(out))
259 page.page('\n'.join(out))
260
260
261
261
262 @line_magic
262 @line_magic
263 def page(self, parameter_s=''):
263 def page(self, parameter_s=''):
264 """Pretty print the object and display it through a pager.
264 """Pretty print the object and display it through a pager.
265
265
266 %page [options] OBJECT
266 %page [options] OBJECT
267
267
268 If no object is given, use _ (last output).
268 If no object is given, use _ (last output).
269
269
270 Options:
270 Options:
271
271
272 -r: page str(object), don't pretty-print it."""
272 -r: page str(object), don't pretty-print it."""
273
273
274 # After a function contributed by Olivier Aubert, slightly modified.
274 # After a function contributed by Olivier Aubert, slightly modified.
275
275
276 # Process options/args
276 # Process options/args
277 opts, args = self.parse_options(parameter_s, 'r')
277 opts, args = self.parse_options(parameter_s, 'r')
278 raw = 'r' in opts
278 raw = 'r' in opts
279
279
280 oname = args and args or '_'
280 oname = args and args or '_'
281 info = self.shell._ofind(oname)
281 info = self.shell._ofind(oname)
282 if info['found']:
282 if info['found']:
283 txt = (raw and str or pformat)( info['obj'] )
283 txt = (raw and str or pformat)( info['obj'] )
284 page.page(txt)
284 page.page(txt)
285 else:
285 else:
286 print('Object `%s` not found' % oname)
286 print('Object `%s` not found' % oname)
287
287
288 @line_magic
288 @line_magic
289 def profile(self, parameter_s=''):
289 def profile(self, parameter_s=''):
290 """Print your currently active IPython profile.
290 """Print your currently active IPython profile.
291
291
292 See Also
292 See Also
293 --------
293 --------
294 prun : run code using the Python profiler
294 prun : run code using the Python profiler
295 (:meth:`~IPython.core.magics.execution.ExecutionMagics.prun`)
295 (:meth:`~IPython.core.magics.execution.ExecutionMagics.prun`)
296 """
296 """
297 warn("%profile is now deprecated. Please use get_ipython().profile instead.")
297 warn("%profile is now deprecated. Please use get_ipython().profile instead.")
298 from IPython.core.application import BaseIPythonApplication
298 from IPython.core.application import BaseIPythonApplication
299 if BaseIPythonApplication.initialized():
299 if BaseIPythonApplication.initialized():
300 print(BaseIPythonApplication.instance().profile)
300 print(BaseIPythonApplication.instance().profile)
301 else:
301 else:
302 error("profile is an application-level value, but you don't appear to be in an IPython application")
302 error("profile is an application-level value, but you don't appear to be in an IPython application")
303
303
304 @line_magic
304 @line_magic
305 def pprint(self, parameter_s=''):
305 def pprint(self, parameter_s=''):
306 """Toggle pretty printing on/off."""
306 """Toggle pretty printing on/off."""
307 ptformatter = self.shell.display_formatter.formatters['text/plain']
307 ptformatter = self.shell.display_formatter.formatters['text/plain']
308 ptformatter.pprint = bool(1 - ptformatter.pprint)
308 ptformatter.pprint = bool(1 - ptformatter.pprint)
309 print('Pretty printing has been turned',
309 print('Pretty printing has been turned',
310 ['OFF','ON'][ptformatter.pprint])
310 ['OFF','ON'][ptformatter.pprint])
311
311
312 @line_magic
312 @line_magic
313 def colors(self, parameter_s=''):
313 def colors(self, parameter_s=''):
314 """Switch color scheme for prompts, info system and exception handlers.
314 """Switch color scheme for prompts, info system and exception handlers.
315
315
316 Currently implemented schemes: NoColor, Linux, LightBG.
316 Currently implemented schemes: NoColor, Linux, LightBG.
317
317
318 Color scheme names are not case-sensitive.
318 Color scheme names are not case-sensitive.
319
319
320 Examples
320 Examples
321 --------
321 --------
322 To get a plain black and white terminal::
322 To get a plain black and white terminal::
323
323
324 %colors nocolor
324 %colors nocolor
325 """
325 """
326 def color_switch_err(name):
326 def color_switch_err(name):
327 warn('Error changing %s color schemes.\n%s' %
327 warn('Error changing %s color schemes.\n%s' %
328 (name, sys.exc_info()[1]), stacklevel=2)
328 (name, sys.exc_info()[1]), stacklevel=2)
329
329
330
330
331 new_scheme = parameter_s.strip()
331 new_scheme = parameter_s.strip()
332 if not new_scheme:
332 if not new_scheme:
333 raise UsageError(
333 raise UsageError(
334 "%colors: you must specify a color scheme. See '%colors?'")
334 "%colors: you must specify a color scheme. See '%colors?'")
335 # local shortcut
335 # local shortcut
336 shell = self.shell
336 shell = self.shell
337
337
338
338 # Set shell colour scheme
339
339 try:
340 if not shell.colors_force:
340 shell.colors = new_scheme
341 if sys.platform in {'win32', 'cli'}:
341 shell.refresh_style()
342 import IPython.utils.rlineimpl as readline
342 except:
343 if not readline.have_readline:
343 color_switch_err('shell')
344 msg = """\
345 Proper color support under MS Windows requires the pyreadline library.
346 You can find it at:
347 http://ipython.org/pyreadline.html
348
349 Defaulting color scheme to 'NoColor'"""
350 new_scheme = 'NoColor'
351 warn(msg)
352
353 elif not shell.has_readline:
354 # Coloured prompts get messed up without readline
355 # Will remove this check after switching to prompt_toolkit
356 new_scheme = 'NoColor'
357
344
358 # Set exception colors
345 # Set exception colors
359 try:
346 try:
360 shell.InteractiveTB.set_colors(scheme = new_scheme)
347 shell.InteractiveTB.set_colors(scheme = new_scheme)
361 shell.colors = new_scheme
362 shell.refresh_style()
363 shell.SyntaxTB.set_colors(scheme = new_scheme)
348 shell.SyntaxTB.set_colors(scheme = new_scheme)
364 except:
349 except:
365 color_switch_err('exception')
350 color_switch_err('exception')
366
351
367 # Set info (for 'object?') colors
352 # Set info (for 'object?') colors
368 if shell.color_info:
353 if shell.color_info:
369 try:
354 try:
370 shell.inspector.set_active_scheme(new_scheme)
355 shell.inspector.set_active_scheme(new_scheme)
371 except:
356 except:
372 color_switch_err('object inspector')
357 color_switch_err('object inspector')
373 else:
358 else:
374 shell.inspector.set_active_scheme('NoColor')
359 shell.inspector.set_active_scheme('NoColor')
375
360
376 @line_magic
361 @line_magic
377 def xmode(self, parameter_s=''):
362 def xmode(self, parameter_s=''):
378 """Switch modes for the exception handlers.
363 """Switch modes for the exception handlers.
379
364
380 Valid modes: Plain, Context and Verbose.
365 Valid modes: Plain, Context and Verbose.
381
366
382 If called without arguments, acts as a toggle."""
367 If called without arguments, acts as a toggle."""
383
368
384 def xmode_switch_err(name):
369 def xmode_switch_err(name):
385 warn('Error changing %s exception modes.\n%s' %
370 warn('Error changing %s exception modes.\n%s' %
386 (name,sys.exc_info()[1]))
371 (name,sys.exc_info()[1]))
387
372
388 shell = self.shell
373 shell = self.shell
389 new_mode = parameter_s.strip().capitalize()
374 new_mode = parameter_s.strip().capitalize()
390 try:
375 try:
391 shell.InteractiveTB.set_mode(mode=new_mode)
376 shell.InteractiveTB.set_mode(mode=new_mode)
392 print('Exception reporting mode:',shell.InteractiveTB.mode)
377 print('Exception reporting mode:',shell.InteractiveTB.mode)
393 except:
378 except:
394 xmode_switch_err('user')
379 xmode_switch_err('user')
395
380
396 @line_magic
381 @line_magic
397 def quickref(self,arg):
382 def quickref(self,arg):
398 """ Show a quick reference sheet """
383 """ Show a quick reference sheet """
399 from IPython.core.usage import quick_reference
384 from IPython.core.usage import quick_reference
400 qr = quick_reference + self._magic_docs(brief=True)
385 qr = quick_reference + self._magic_docs(brief=True)
401 page.page(qr)
386 page.page(qr)
402
387
403 @line_magic
388 @line_magic
404 def doctest_mode(self, parameter_s=''):
389 def doctest_mode(self, parameter_s=''):
405 """Toggle doctest mode on and off.
390 """Toggle doctest mode on and off.
406
391
407 This mode is intended to make IPython behave as much as possible like a
392 This mode is intended to make IPython behave as much as possible like a
408 plain Python shell, from the perspective of how its prompts, exceptions
393 plain Python shell, from the perspective of how its prompts, exceptions
409 and output look. This makes it easy to copy and paste parts of a
394 and output look. This makes it easy to copy and paste parts of a
410 session into doctests. It does so by:
395 session into doctests. It does so by:
411
396
412 - Changing the prompts to the classic ``>>>`` ones.
397 - Changing the prompts to the classic ``>>>`` ones.
413 - Changing the exception reporting mode to 'Plain'.
398 - Changing the exception reporting mode to 'Plain'.
414 - Disabling pretty-printing of output.
399 - Disabling pretty-printing of output.
415
400
416 Note that IPython also supports the pasting of code snippets that have
401 Note that IPython also supports the pasting of code snippets that have
417 leading '>>>' and '...' prompts in them. This means that you can paste
402 leading '>>>' and '...' prompts in them. This means that you can paste
418 doctests from files or docstrings (even if they have leading
403 doctests from files or docstrings (even if they have leading
419 whitespace), and the code will execute correctly. You can then use
404 whitespace), and the code will execute correctly. You can then use
420 '%history -t' to see the translated history; this will give you the
405 '%history -t' to see the translated history; this will give you the
421 input after removal of all the leading prompts and whitespace, which
406 input after removal of all the leading prompts and whitespace, which
422 can be pasted back into an editor.
407 can be pasted back into an editor.
423
408
424 With these features, you can switch into this mode easily whenever you
409 With these features, you can switch into this mode easily whenever you
425 need to do testing and changes to doctests, without having to leave
410 need to do testing and changes to doctests, without having to leave
426 your existing IPython session.
411 your existing IPython session.
427 """
412 """
428
413
429 # Shorthands
414 # Shorthands
430 shell = self.shell
415 shell = self.shell
431 meta = shell.meta
416 meta = shell.meta
432 disp_formatter = self.shell.display_formatter
417 disp_formatter = self.shell.display_formatter
433 ptformatter = disp_formatter.formatters['text/plain']
418 ptformatter = disp_formatter.formatters['text/plain']
434 # dstore is a data store kept in the instance metadata bag to track any
419 # dstore is a data store kept in the instance metadata bag to track any
435 # changes we make, so we can undo them later.
420 # changes we make, so we can undo them later.
436 dstore = meta.setdefault('doctest_mode',Struct())
421 dstore = meta.setdefault('doctest_mode',Struct())
437 save_dstore = dstore.setdefault
422 save_dstore = dstore.setdefault
438
423
439 # save a few values we'll need to recover later
424 # save a few values we'll need to recover later
440 mode = save_dstore('mode',False)
425 mode = save_dstore('mode',False)
441 save_dstore('rc_pprint',ptformatter.pprint)
426 save_dstore('rc_pprint',ptformatter.pprint)
442 save_dstore('xmode',shell.InteractiveTB.mode)
427 save_dstore('xmode',shell.InteractiveTB.mode)
443 save_dstore('rc_separate_out',shell.separate_out)
428 save_dstore('rc_separate_out',shell.separate_out)
444 save_dstore('rc_separate_out2',shell.separate_out2)
429 save_dstore('rc_separate_out2',shell.separate_out2)
445 save_dstore('rc_separate_in',shell.separate_in)
430 save_dstore('rc_separate_in',shell.separate_in)
446 save_dstore('rc_active_types',disp_formatter.active_types)
431 save_dstore('rc_active_types',disp_formatter.active_types)
447
432
448 if not mode:
433 if not mode:
449 # turn on
434 # turn on
450
435
451 # Prompt separators like plain python
436 # Prompt separators like plain python
452 shell.separate_in = ''
437 shell.separate_in = ''
453 shell.separate_out = ''
438 shell.separate_out = ''
454 shell.separate_out2 = ''
439 shell.separate_out2 = ''
455
440
456
441
457 ptformatter.pprint = False
442 ptformatter.pprint = False
458 disp_formatter.active_types = ['text/plain']
443 disp_formatter.active_types = ['text/plain']
459
444
460 shell.magic('xmode Plain')
445 shell.magic('xmode Plain')
461 else:
446 else:
462 # turn off
447 # turn off
463 shell.separate_in = dstore.rc_separate_in
448 shell.separate_in = dstore.rc_separate_in
464
449
465 shell.separate_out = dstore.rc_separate_out
450 shell.separate_out = dstore.rc_separate_out
466 shell.separate_out2 = dstore.rc_separate_out2
451 shell.separate_out2 = dstore.rc_separate_out2
467
452
468 ptformatter.pprint = dstore.rc_pprint
453 ptformatter.pprint = dstore.rc_pprint
469 disp_formatter.active_types = dstore.rc_active_types
454 disp_formatter.active_types = dstore.rc_active_types
470
455
471 shell.magic('xmode ' + dstore.xmode)
456 shell.magic('xmode ' + dstore.xmode)
472
457
473 # mode here is the state before we switch; switch_doctest_mode takes
458 # mode here is the state before we switch; switch_doctest_mode takes
474 # the mode we're switching to.
459 # the mode we're switching to.
475 shell.switch_doctest_mode(not mode)
460 shell.switch_doctest_mode(not mode)
476
461
477 # Store new mode and inform
462 # Store new mode and inform
478 dstore.mode = bool(not mode)
463 dstore.mode = bool(not mode)
479 mode_label = ['OFF','ON'][dstore.mode]
464 mode_label = ['OFF','ON'][dstore.mode]
480 print('Doctest mode is:', mode_label)
465 print('Doctest mode is:', mode_label)
481
466
482 @line_magic
467 @line_magic
483 def gui(self, parameter_s=''):
468 def gui(self, parameter_s=''):
484 """Enable or disable IPython GUI event loop integration.
469 """Enable or disable IPython GUI event loop integration.
485
470
486 %gui [GUINAME]
471 %gui [GUINAME]
487
472
488 This magic replaces IPython's threaded shells that were activated
473 This magic replaces IPython's threaded shells that were activated
489 using the (pylab/wthread/etc.) command line flags. GUI toolkits
474 using the (pylab/wthread/etc.) command line flags. GUI toolkits
490 can now be enabled at runtime and keyboard
475 can now be enabled at runtime and keyboard
491 interrupts should work without any problems. The following toolkits
476 interrupts should work without any problems. The following toolkits
492 are supported: wxPython, PyQt4, PyGTK, Tk and Cocoa (OSX)::
477 are supported: wxPython, PyQt4, PyGTK, Tk and Cocoa (OSX)::
493
478
494 %gui wx # enable wxPython event loop integration
479 %gui wx # enable wxPython event loop integration
495 %gui qt4|qt # enable PyQt4 event loop integration
480 %gui qt4|qt # enable PyQt4 event loop integration
496 %gui qt5 # enable PyQt5 event loop integration
481 %gui qt5 # enable PyQt5 event loop integration
497 %gui gtk # enable PyGTK event loop integration
482 %gui gtk # enable PyGTK event loop integration
498 %gui gtk3 # enable Gtk3 event loop integration
483 %gui gtk3 # enable Gtk3 event loop integration
499 %gui tk # enable Tk event loop integration
484 %gui tk # enable Tk event loop integration
500 %gui osx # enable Cocoa event loop integration
485 %gui osx # enable Cocoa event loop integration
501 # (requires %matplotlib 1.1)
486 # (requires %matplotlib 1.1)
502 %gui # disable all event loop integration
487 %gui # disable all event loop integration
503
488
504 WARNING: after any of these has been called you can simply create
489 WARNING: after any of these has been called you can simply create
505 an application object, but DO NOT start the event loop yourself, as
490 an application object, but DO NOT start the event loop yourself, as
506 we have already handled that.
491 we have already handled that.
507 """
492 """
508 opts, arg = self.parse_options(parameter_s, '')
493 opts, arg = self.parse_options(parameter_s, '')
509 if arg=='': arg = None
494 if arg=='': arg = None
510 try:
495 try:
511 return self.shell.enable_gui(arg)
496 return self.shell.enable_gui(arg)
512 except Exception as e:
497 except Exception as e:
513 # print simple error message, rather than traceback if we can't
498 # print simple error message, rather than traceback if we can't
514 # hook up the GUI
499 # hook up the GUI
515 error(str(e))
500 error(str(e))
516
501
517 @skip_doctest
502 @skip_doctest
518 @line_magic
503 @line_magic
519 def precision(self, s=''):
504 def precision(self, s=''):
520 """Set floating point precision for pretty printing.
505 """Set floating point precision for pretty printing.
521
506
522 Can set either integer precision or a format string.
507 Can set either integer precision or a format string.
523
508
524 If numpy has been imported and precision is an int,
509 If numpy has been imported and precision is an int,
525 numpy display precision will also be set, via ``numpy.set_printoptions``.
510 numpy display precision will also be set, via ``numpy.set_printoptions``.
526
511
527 If no argument is given, defaults will be restored.
512 If no argument is given, defaults will be restored.
528
513
529 Examples
514 Examples
530 --------
515 --------
531 ::
516 ::
532
517
533 In [1]: from math import pi
518 In [1]: from math import pi
534
519
535 In [2]: %precision 3
520 In [2]: %precision 3
536 Out[2]: u'%.3f'
521 Out[2]: u'%.3f'
537
522
538 In [3]: pi
523 In [3]: pi
539 Out[3]: 3.142
524 Out[3]: 3.142
540
525
541 In [4]: %precision %i
526 In [4]: %precision %i
542 Out[4]: u'%i'
527 Out[4]: u'%i'
543
528
544 In [5]: pi
529 In [5]: pi
545 Out[5]: 3
530 Out[5]: 3
546
531
547 In [6]: %precision %e
532 In [6]: %precision %e
548 Out[6]: u'%e'
533 Out[6]: u'%e'
549
534
550 In [7]: pi**10
535 In [7]: pi**10
551 Out[7]: 9.364805e+04
536 Out[7]: 9.364805e+04
552
537
553 In [8]: %precision
538 In [8]: %precision
554 Out[8]: u'%r'
539 Out[8]: u'%r'
555
540
556 In [9]: pi**10
541 In [9]: pi**10
557 Out[9]: 93648.047476082982
542 Out[9]: 93648.047476082982
558 """
543 """
559 ptformatter = self.shell.display_formatter.formatters['text/plain']
544 ptformatter = self.shell.display_formatter.formatters['text/plain']
560 ptformatter.float_precision = s
545 ptformatter.float_precision = s
561 return ptformatter.float_format
546 return ptformatter.float_format
562
547
563 @magic_arguments.magic_arguments()
548 @magic_arguments.magic_arguments()
564 @magic_arguments.argument(
549 @magic_arguments.argument(
565 '-e', '--export', action='store_true', default=False,
550 '-e', '--export', action='store_true', default=False,
566 help='Export IPython history as a notebook. The filename argument '
551 help='Export IPython history as a notebook. The filename argument '
567 'is used to specify the notebook name and format. For example '
552 'is used to specify the notebook name and format. For example '
568 'a filename of notebook.ipynb will result in a notebook name '
553 'a filename of notebook.ipynb will result in a notebook name '
569 'of "notebook" and a format of "json". Likewise using a ".py" '
554 'of "notebook" and a format of "json". Likewise using a ".py" '
570 'file extension will write the notebook as a Python script'
555 'file extension will write the notebook as a Python script'
571 )
556 )
572 @magic_arguments.argument(
557 @magic_arguments.argument(
573 'filename', type=unicode_type,
558 'filename', type=unicode_type,
574 help='Notebook name or filename'
559 help='Notebook name or filename'
575 )
560 )
576 @line_magic
561 @line_magic
577 def notebook(self, s):
562 def notebook(self, s):
578 """Export and convert IPython notebooks.
563 """Export and convert IPython notebooks.
579
564
580 This function can export the current IPython history to a notebook file.
565 This function can export the current IPython history to a notebook file.
581 For example, to export the history to "foo.ipynb" do "%notebook -e foo.ipynb".
566 For example, to export the history to "foo.ipynb" do "%notebook -e foo.ipynb".
582 To export the history to "foo.py" do "%notebook -e foo.py".
567 To export the history to "foo.py" do "%notebook -e foo.py".
583 """
568 """
584 args = magic_arguments.parse_argstring(self.notebook, s)
569 args = magic_arguments.parse_argstring(self.notebook, s)
585
570
586 from nbformat import write, v4
571 from nbformat import write, v4
587 if args.export:
572 if args.export:
588 cells = []
573 cells = []
589 hist = list(self.shell.history_manager.get_range())
574 hist = list(self.shell.history_manager.get_range())
590 if(len(hist)<=1):
575 if(len(hist)<=1):
591 raise ValueError('History is empty, cannot export')
576 raise ValueError('History is empty, cannot export')
592 for session, execution_count, source in hist[:-1]:
577 for session, execution_count, source in hist[:-1]:
593 cells.append(v4.new_code_cell(
578 cells.append(v4.new_code_cell(
594 execution_count=execution_count,
579 execution_count=execution_count,
595 source=source
580 source=source
596 ))
581 ))
597 nb = v4.new_notebook(cells=cells)
582 nb = v4.new_notebook(cells=cells)
598 with io.open(args.filename, 'w', encoding='utf-8') as f:
583 with io.open(args.filename, 'w', encoding='utf-8') as f:
599 write(nb, f, version=4)
584 write(nb, f, version=4)
@@ -1,579 +1,577 b''
1 """IPython terminal interface using prompt_toolkit"""
1 """IPython terminal interface using prompt_toolkit"""
2 from __future__ import print_function
2 from __future__ import print_function
3
3
4 import os
4 import os
5 import sys
5 import sys
6 import signal
6 import signal
7 from warnings import warn
7 from warnings import warn
8
8
9 from IPython.core.error import TryNext
9 from IPython.core.error import TryNext
10 from IPython.core.interactiveshell import InteractiveShell, InteractiveShellABC
10 from IPython.core.interactiveshell import InteractiveShell, InteractiveShellABC
11 from IPython.utils.py3compat import PY3, cast_unicode_py2, input
11 from IPython.utils.py3compat import PY3, cast_unicode_py2, input
12 from IPython.utils.terminal import toggle_set_term_title, set_term_title
12 from IPython.utils.terminal import toggle_set_term_title, set_term_title
13 from IPython.utils.process import abbrev_cwd
13 from IPython.utils.process import abbrev_cwd
14 from traitlets import Bool, Unicode, Dict, Integer, observe, Instance, Type, default, Enum
14 from traitlets import Bool, Unicode, Dict, Integer, observe, Instance, Type, default, Enum
15
15
16 from prompt_toolkit.enums import DEFAULT_BUFFER, SEARCH_BUFFER, EditingMode
16 from prompt_toolkit.enums import DEFAULT_BUFFER, SEARCH_BUFFER, EditingMode
17 from prompt_toolkit.filters import (HasFocus, HasSelection, Condition,
17 from prompt_toolkit.filters import (HasFocus, HasSelection, Condition,
18 ViInsertMode, EmacsInsertMode, IsDone, HasCompletions)
18 ViInsertMode, EmacsInsertMode, IsDone, HasCompletions)
19 from prompt_toolkit.filters.cli import ViMode
19 from prompt_toolkit.filters.cli import ViMode
20 from prompt_toolkit.history import InMemoryHistory
20 from prompt_toolkit.history import InMemoryHistory
21 from prompt_toolkit.shortcuts import create_prompt_application, create_eventloop, create_prompt_layout
21 from prompt_toolkit.shortcuts import create_prompt_application, create_eventloop, create_prompt_layout
22 from prompt_toolkit.interface import CommandLineInterface
22 from prompt_toolkit.interface import CommandLineInterface
23 from prompt_toolkit.key_binding.manager import KeyBindingManager
23 from prompt_toolkit.key_binding.manager import KeyBindingManager
24 from prompt_toolkit.keys import Keys
24 from prompt_toolkit.keys import Keys
25 from prompt_toolkit.layout.processors import ConditionalProcessor, HighlightMatchingBracketProcessor
25 from prompt_toolkit.layout.processors import ConditionalProcessor, HighlightMatchingBracketProcessor
26 from prompt_toolkit.styles import PygmentsStyle, DynamicStyle
26 from prompt_toolkit.styles import PygmentsStyle, DynamicStyle
27 from prompt_toolkit.key_binding.bindings.completion import display_completions_like_readline
27 from prompt_toolkit.key_binding.bindings.completion import display_completions_like_readline
28
28
29 from pygments.styles import get_style_by_name, get_all_styles
29 from pygments.styles import get_style_by_name, get_all_styles
30 from pygments.token import Token
30 from pygments.token import Token
31
31
32 from .debugger import TerminalPdb, Pdb
32 from .debugger import TerminalPdb, Pdb
33 from .magics import TerminalMagics
33 from .magics import TerminalMagics
34 from .pt_inputhooks import get_inputhook_func
34 from .pt_inputhooks import get_inputhook_func
35 from .prompts import Prompts, ClassicPrompts, RichPromptDisplayHook
35 from .prompts import Prompts, ClassicPrompts, RichPromptDisplayHook
36 from .ptutils import IPythonPTCompleter, IPythonPTLexer
36 from .ptutils import IPythonPTCompleter, IPythonPTLexer
37
37
38 DISPLAY_BANNER_DEPRECATED = object()
38 DISPLAY_BANNER_DEPRECATED = object()
39
39
40
40
41 from pygments.style import Style
41 from pygments.style import Style
42
42
43 class _NoStyle(Style): pass
43 class _NoStyle(Style): pass
44
44
45
45
46
46
47 _style_overrides_light_bg = {
47 _style_overrides_light_bg = {
48 Token.Prompt: '#0000ff',
48 Token.Prompt: '#0000ff',
49 Token.PromptNum: '#0000ee bold',
49 Token.PromptNum: '#0000ee bold',
50 Token.OutPrompt: '#cc0000',
50 Token.OutPrompt: '#cc0000',
51 Token.OutPromptNum: '#bb0000 bold',
51 Token.OutPromptNum: '#bb0000 bold',
52 }
52 }
53
53
54 _style_overrides_linux = {
54 _style_overrides_linux = {
55 Token.Prompt: '#00cc00',
55 Token.Prompt: '#00cc00',
56 Token.PromptNum: '#00bb00 bold',
56 Token.PromptNum: '#00bb00 bold',
57 Token.OutPrompt: '#cc0000',
57 Token.OutPrompt: '#cc0000',
58 Token.OutPromptNum: '#bb0000 bold',
58 Token.OutPromptNum: '#bb0000 bold',
59 }
59 }
60
60
61
61
62
62
63 def get_default_editor():
63 def get_default_editor():
64 try:
64 try:
65 ed = os.environ['EDITOR']
65 ed = os.environ['EDITOR']
66 if not PY3:
66 if not PY3:
67 ed = ed.decode()
67 ed = ed.decode()
68 return ed
68 return ed
69 except KeyError:
69 except KeyError:
70 pass
70 pass
71 except UnicodeError:
71 except UnicodeError:
72 warn("$EDITOR environment variable is not pure ASCII. Using platform "
72 warn("$EDITOR environment variable is not pure ASCII. Using platform "
73 "default editor.")
73 "default editor.")
74
74
75 if os.name == 'posix':
75 if os.name == 'posix':
76 return 'vi' # the only one guaranteed to be there!
76 return 'vi' # the only one guaranteed to be there!
77 else:
77 else:
78 return 'notepad' # same in Windows!
78 return 'notepad' # same in Windows!
79
79
80
80
81 if sys.stdin and sys.stdout and sys.stderr:
81 if sys.stdin and sys.stdout and sys.stderr:
82 _is_tty = (sys.stdin.isatty()) and (sys.stdout.isatty()) and (sys.stderr.isatty())
82 _is_tty = (sys.stdin.isatty()) and (sys.stdout.isatty()) and (sys.stderr.isatty())
83 else:
83 else:
84 _is_tty = False
84 _is_tty = False
85
85
86
86
87 _use_simple_prompt = ('IPY_TEST_SIMPLE_PROMPT' in os.environ) or (not _is_tty)
87 _use_simple_prompt = ('IPY_TEST_SIMPLE_PROMPT' in os.environ) or (not _is_tty)
88
88
89 class TerminalInteractiveShell(InteractiveShell):
89 class TerminalInteractiveShell(InteractiveShell):
90 colors_force = True
91
92 space_for_menu = Integer(6, help='Number of line at the bottom of the screen '
90 space_for_menu = Integer(6, help='Number of line at the bottom of the screen '
93 'to reserve for the completion menu'
91 'to reserve for the completion menu'
94 ).tag(config=True)
92 ).tag(config=True)
95
93
96 def _space_for_menu_changed(self, old, new):
94 def _space_for_menu_changed(self, old, new):
97 self._update_layout()
95 self._update_layout()
98
96
99 pt_cli = None
97 pt_cli = None
100 debugger_history = None
98 debugger_history = None
101 _pt_app = None
99 _pt_app = None
102
100
103 simple_prompt = Bool(_use_simple_prompt,
101 simple_prompt = Bool(_use_simple_prompt,
104 help="""Use `raw_input` for the REPL, without completion, multiline input, and prompt colors.
102 help="""Use `raw_input` for the REPL, without completion, multiline input, and prompt colors.
105
103
106 Useful when controlling IPython as a subprocess, and piping STDIN/OUT/ERR. Known usage are:
104 Useful when controlling IPython as a subprocess, and piping STDIN/OUT/ERR. Known usage are:
107 IPython own testing machinery, and emacs inferior-shell integration through elpy.
105 IPython own testing machinery, and emacs inferior-shell integration through elpy.
108
106
109 This mode default to `True` if the `IPY_TEST_SIMPLE_PROMPT`
107 This mode default to `True` if the `IPY_TEST_SIMPLE_PROMPT`
110 environment variable is set, or the current terminal is not a tty.
108 environment variable is set, or the current terminal is not a tty.
111
109
112 """
110 """
113 ).tag(config=True)
111 ).tag(config=True)
114
112
115 @property
113 @property
116 def debugger_cls(self):
114 def debugger_cls(self):
117 return Pdb if self.simple_prompt else TerminalPdb
115 return Pdb if self.simple_prompt else TerminalPdb
118
116
119 confirm_exit = Bool(True,
117 confirm_exit = Bool(True,
120 help="""
118 help="""
121 Set to confirm when you try to exit IPython with an EOF (Control-D
119 Set to confirm when you try to exit IPython with an EOF (Control-D
122 in Unix, Control-Z/Enter in Windows). By typing 'exit' or 'quit',
120 in Unix, Control-Z/Enter in Windows). By typing 'exit' or 'quit',
123 you can force a direct exit without any confirmation.""",
121 you can force a direct exit without any confirmation.""",
124 ).tag(config=True)
122 ).tag(config=True)
125
123
126 editing_mode = Unicode('emacs',
124 editing_mode = Unicode('emacs',
127 help="Shortcut style to use at the prompt. 'vi' or 'emacs'.",
125 help="Shortcut style to use at the prompt. 'vi' or 'emacs'.",
128 ).tag(config=True)
126 ).tag(config=True)
129
127
130 mouse_support = Bool(False,
128 mouse_support = Bool(False,
131 help="Enable mouse support in the prompt"
129 help="Enable mouse support in the prompt"
132 ).tag(config=True)
130 ).tag(config=True)
133
131
134 highlighting_style = Unicode('legacy',
132 highlighting_style = Unicode('legacy',
135 help="The name of a Pygments style to use for syntax highlighting: \n %s" % ', '.join(get_all_styles())
133 help="The name of a Pygments style to use for syntax highlighting: \n %s" % ', '.join(get_all_styles())
136 ).tag(config=True)
134 ).tag(config=True)
137
135
138
136
139 @observe('highlighting_style')
137 @observe('highlighting_style')
140 @observe('colors')
138 @observe('colors')
141 def _highlighting_style_changed(self, change):
139 def _highlighting_style_changed(self, change):
142 self.refresh_style()
140 self.refresh_style()
143
141
144 def refresh_style(self):
142 def refresh_style(self):
145 self._style = self._make_style_from_name(self.highlighting_style)
143 self._style = self._make_style_from_name(self.highlighting_style)
146
144
147
145
148 highlighting_style_overrides = Dict(
146 highlighting_style_overrides = Dict(
149 help="Override highlighting format for specific tokens"
147 help="Override highlighting format for specific tokens"
150 ).tag(config=True)
148 ).tag(config=True)
151
149
152 editor = Unicode(get_default_editor(),
150 editor = Unicode(get_default_editor(),
153 help="Set the editor used by IPython (default to $EDITOR/vi/notepad)."
151 help="Set the editor used by IPython (default to $EDITOR/vi/notepad)."
154 ).tag(config=True)
152 ).tag(config=True)
155
153
156 prompts_class = Type(Prompts, help='Class used to generate Prompt token for prompt_toolkit').tag(config=True)
154 prompts_class = Type(Prompts, help='Class used to generate Prompt token for prompt_toolkit').tag(config=True)
157
155
158 prompts = Instance(Prompts)
156 prompts = Instance(Prompts)
159
157
160 @default('prompts')
158 @default('prompts')
161 def _prompts_default(self):
159 def _prompts_default(self):
162 return self.prompts_class(self)
160 return self.prompts_class(self)
163
161
164 @observe('prompts')
162 @observe('prompts')
165 def _(self, change):
163 def _(self, change):
166 self._update_layout()
164 self._update_layout()
167
165
168 @default('displayhook_class')
166 @default('displayhook_class')
169 def _displayhook_class_default(self):
167 def _displayhook_class_default(self):
170 return RichPromptDisplayHook
168 return RichPromptDisplayHook
171
169
172 term_title = Bool(True,
170 term_title = Bool(True,
173 help="Automatically set the terminal title"
171 help="Automatically set the terminal title"
174 ).tag(config=True)
172 ).tag(config=True)
175
173
176 # Leaving that for beta/rc tester, shoudl remove for 5.0.0 final.
174 # Leaving that for beta/rc tester, shoudl remove for 5.0.0 final.
177 display_completions_in_columns = Bool(None,
175 display_completions_in_columns = Bool(None,
178 help="DEPRECATED", allow_none=True
176 help="DEPRECATED", allow_none=True
179 ).tag(config=True)
177 ).tag(config=True)
180
178
181 @observe('display_completions_in_columns')
179 @observe('display_completions_in_columns')
182 def _display_completions_in_columns_changed(self, new):
180 def _display_completions_in_columns_changed(self, new):
183 raise DeprecationWarning("The `display_completions_in_columns` Boolean has been replaced by the enum `display_completions`"
181 raise DeprecationWarning("The `display_completions_in_columns` Boolean has been replaced by the enum `display_completions`"
184 "with the following acceptable value: 'column', 'multicolumn','readlinelike'. ")
182 "with the following acceptable value: 'column', 'multicolumn','readlinelike'. ")
185
183
186 display_completions = Enum(('column', 'multicolumn','readlinelike'), default_value='multicolumn').tag(config=True)
184 display_completions = Enum(('column', 'multicolumn','readlinelike'), default_value='multicolumn').tag(config=True)
187
185
188 highlight_matching_brackets = Bool(True,
186 highlight_matching_brackets = Bool(True,
189 help="Highlight matching brackets .",
187 help="Highlight matching brackets .",
190 ).tag(config=True)
188 ).tag(config=True)
191
189
192 @observe('term_title')
190 @observe('term_title')
193 def init_term_title(self, change=None):
191 def init_term_title(self, change=None):
194 # Enable or disable the terminal title.
192 # Enable or disable the terminal title.
195 if self.term_title:
193 if self.term_title:
196 toggle_set_term_title(True)
194 toggle_set_term_title(True)
197 set_term_title('IPython: ' + abbrev_cwd())
195 set_term_title('IPython: ' + abbrev_cwd())
198 else:
196 else:
199 toggle_set_term_title(False)
197 toggle_set_term_title(False)
200
198
201 def init_display_formatter(self):
199 def init_display_formatter(self):
202 super(TerminalInteractiveShell, self).init_display_formatter()
200 super(TerminalInteractiveShell, self).init_display_formatter()
203 # terminal only supports plain text
201 # terminal only supports plain text
204 self.display_formatter.active_types = ['text/plain']
202 self.display_formatter.active_types = ['text/plain']
205
203
206 def init_prompt_toolkit_cli(self):
204 def init_prompt_toolkit_cli(self):
207 if self.simple_prompt:
205 if self.simple_prompt:
208 # Fall back to plain non-interactive output for tests.
206 # Fall back to plain non-interactive output for tests.
209 # This is very limited, and only accepts a single line.
207 # This is very limited, and only accepts a single line.
210 def prompt():
208 def prompt():
211 return cast_unicode_py2(input('In [%d]: ' % self.execution_count))
209 return cast_unicode_py2(input('In [%d]: ' % self.execution_count))
212 self.prompt_for_code = prompt
210 self.prompt_for_code = prompt
213 return
211 return
214
212
215 kbmanager = KeyBindingManager.for_prompt()
213 kbmanager = KeyBindingManager.for_prompt()
216 insert_mode = ViInsertMode() | EmacsInsertMode()
214 insert_mode = ViInsertMode() | EmacsInsertMode()
217 # Ctrl+J == Enter, seemingly
215 # Ctrl+J == Enter, seemingly
218 @kbmanager.registry.add_binding(Keys.ControlJ,
216 @kbmanager.registry.add_binding(Keys.ControlJ,
219 filter=(HasFocus(DEFAULT_BUFFER)
217 filter=(HasFocus(DEFAULT_BUFFER)
220 & ~HasSelection()
218 & ~HasSelection()
221 & insert_mode
219 & insert_mode
222 ))
220 ))
223 def _(event):
221 def _(event):
224 b = event.current_buffer
222 b = event.current_buffer
225 d = b.document
223 d = b.document
226
224
227 if b.complete_state:
225 if b.complete_state:
228 cc = b.complete_state.current_completion
226 cc = b.complete_state.current_completion
229 if cc:
227 if cc:
230 b.apply_completion(cc)
228 b.apply_completion(cc)
231 else:
229 else:
232 b.cancel_completion()
230 b.cancel_completion()
233 return
231 return
234
232
235 if not (d.on_last_line or d.cursor_position_row >= d.line_count
233 if not (d.on_last_line or d.cursor_position_row >= d.line_count
236 - d.empty_line_count_at_the_end()):
234 - d.empty_line_count_at_the_end()):
237 b.newline()
235 b.newline()
238 return
236 return
239
237
240 status, indent = self.input_splitter.check_complete(d.text + '\n')
238 status, indent = self.input_splitter.check_complete(d.text + '\n')
241
239
242 if (status != 'incomplete') and b.accept_action.is_returnable:
240 if (status != 'incomplete') and b.accept_action.is_returnable:
243 b.accept_action.validate_and_handle(event.cli, b)
241 b.accept_action.validate_and_handle(event.cli, b)
244 else:
242 else:
245 b.insert_text('\n' + (' ' * (indent or 0)))
243 b.insert_text('\n' + (' ' * (indent or 0)))
246
244
247 @kbmanager.registry.add_binding(Keys.ControlP, filter=(ViInsertMode() & HasFocus(DEFAULT_BUFFER)))
245 @kbmanager.registry.add_binding(Keys.ControlP, filter=(ViInsertMode() & HasFocus(DEFAULT_BUFFER)))
248 def _previous_history_or_previous_completion(event):
246 def _previous_history_or_previous_completion(event):
249 """
247 """
250 Control-P in vi edit mode on readline is history next, unlike default prompt toolkit.
248 Control-P in vi edit mode on readline is history next, unlike default prompt toolkit.
251
249
252 If completer is open this still select previous completion.
250 If completer is open this still select previous completion.
253 """
251 """
254 event.current_buffer.auto_up()
252 event.current_buffer.auto_up()
255
253
256 @kbmanager.registry.add_binding(Keys.ControlN, filter=(ViInsertMode() & HasFocus(DEFAULT_BUFFER)))
254 @kbmanager.registry.add_binding(Keys.ControlN, filter=(ViInsertMode() & HasFocus(DEFAULT_BUFFER)))
257 def _next_history_or_next_completion(event):
255 def _next_history_or_next_completion(event):
258 """
256 """
259 Control-N in vi edit mode on readline is history previous, unlike default prompt toolkit.
257 Control-N in vi edit mode on readline is history previous, unlike default prompt toolkit.
260
258
261 If completer is open this still select next completion.
259 If completer is open this still select next completion.
262 """
260 """
263 event.current_buffer.auto_down()
261 event.current_buffer.auto_down()
264
262
265 @kbmanager.registry.add_binding(Keys.ControlG, filter=(
263 @kbmanager.registry.add_binding(Keys.ControlG, filter=(
266 HasFocus(DEFAULT_BUFFER) & HasCompletions()
264 HasFocus(DEFAULT_BUFFER) & HasCompletions()
267 ))
265 ))
268 def _dismiss_completion(event):
266 def _dismiss_completion(event):
269 b = event.current_buffer
267 b = event.current_buffer
270 if b.complete_state:
268 if b.complete_state:
271 b.cancel_completion()
269 b.cancel_completion()
272
270
273 @kbmanager.registry.add_binding(Keys.ControlC, filter=HasFocus(DEFAULT_BUFFER))
271 @kbmanager.registry.add_binding(Keys.ControlC, filter=HasFocus(DEFAULT_BUFFER))
274 def _reset_buffer(event):
272 def _reset_buffer(event):
275 b = event.current_buffer
273 b = event.current_buffer
276 if b.complete_state:
274 if b.complete_state:
277 b.cancel_completion()
275 b.cancel_completion()
278 else:
276 else:
279 b.reset()
277 b.reset()
280
278
281 @kbmanager.registry.add_binding(Keys.ControlC, filter=HasFocus(SEARCH_BUFFER))
279 @kbmanager.registry.add_binding(Keys.ControlC, filter=HasFocus(SEARCH_BUFFER))
282 def _reset_search_buffer(event):
280 def _reset_search_buffer(event):
283 if event.current_buffer.document.text:
281 if event.current_buffer.document.text:
284 event.current_buffer.reset()
282 event.current_buffer.reset()
285 else:
283 else:
286 event.cli.push_focus(DEFAULT_BUFFER)
284 event.cli.push_focus(DEFAULT_BUFFER)
287
285
288 supports_suspend = Condition(lambda cli: hasattr(signal, 'SIGTSTP'))
286 supports_suspend = Condition(lambda cli: hasattr(signal, 'SIGTSTP'))
289
287
290 @kbmanager.registry.add_binding(Keys.ControlZ, filter=supports_suspend)
288 @kbmanager.registry.add_binding(Keys.ControlZ, filter=supports_suspend)
291 def _suspend_to_bg(event):
289 def _suspend_to_bg(event):
292 event.cli.suspend_to_background()
290 event.cli.suspend_to_background()
293
291
294 @Condition
292 @Condition
295 def cursor_in_leading_ws(cli):
293 def cursor_in_leading_ws(cli):
296 before = cli.application.buffer.document.current_line_before_cursor
294 before = cli.application.buffer.document.current_line_before_cursor
297 return (not before) or before.isspace()
295 return (not before) or before.isspace()
298
296
299 # Ctrl+I == Tab
297 # Ctrl+I == Tab
300 @kbmanager.registry.add_binding(Keys.ControlI,
298 @kbmanager.registry.add_binding(Keys.ControlI,
301 filter=(HasFocus(DEFAULT_BUFFER)
299 filter=(HasFocus(DEFAULT_BUFFER)
302 & ~HasSelection()
300 & ~HasSelection()
303 & insert_mode
301 & insert_mode
304 & cursor_in_leading_ws
302 & cursor_in_leading_ws
305 ))
303 ))
306 def _indent_buffer(event):
304 def _indent_buffer(event):
307 event.current_buffer.insert_text(' ' * 4)
305 event.current_buffer.insert_text(' ' * 4)
308
306
309
307
310 if self.display_completions == 'readlinelike':
308 if self.display_completions == 'readlinelike':
311 @kbmanager.registry.add_binding(Keys.ControlI,
309 @kbmanager.registry.add_binding(Keys.ControlI,
312 filter=(HasFocus(DEFAULT_BUFFER)
310 filter=(HasFocus(DEFAULT_BUFFER)
313 & ~HasSelection()
311 & ~HasSelection()
314 & insert_mode
312 & insert_mode
315 & ~cursor_in_leading_ws
313 & ~cursor_in_leading_ws
316 ))
314 ))
317 def _disaply_compl(ev):
315 def _disaply_compl(ev):
318 display_completions_like_readline(ev)
316 display_completions_like_readline(ev)
319
317
320
318
321 if sys.platform == 'win32':
319 if sys.platform == 'win32':
322 from IPython.lib.clipboard import (ClipboardEmpty,
320 from IPython.lib.clipboard import (ClipboardEmpty,
323 win32_clipboard_get, tkinter_clipboard_get)
321 win32_clipboard_get, tkinter_clipboard_get)
324 @kbmanager.registry.add_binding(Keys.ControlV,
322 @kbmanager.registry.add_binding(Keys.ControlV,
325 filter=(HasFocus(DEFAULT_BUFFER) & ~ViMode()))
323 filter=(HasFocus(DEFAULT_BUFFER) & ~ViMode()))
326 def _paste(event):
324 def _paste(event):
327 try:
325 try:
328 text = win32_clipboard_get()
326 text = win32_clipboard_get()
329 except TryNext:
327 except TryNext:
330 try:
328 try:
331 text = tkinter_clipboard_get()
329 text = tkinter_clipboard_get()
332 except (TryNext, ClipboardEmpty):
330 except (TryNext, ClipboardEmpty):
333 return
331 return
334 except ClipboardEmpty:
332 except ClipboardEmpty:
335 return
333 return
336 event.current_buffer.insert_text(text.replace('\t', ' ' * 4))
334 event.current_buffer.insert_text(text.replace('\t', ' ' * 4))
337
335
338 # Pre-populate history from IPython's history database
336 # Pre-populate history from IPython's history database
339 history = InMemoryHistory()
337 history = InMemoryHistory()
340 last_cell = u""
338 last_cell = u""
341 for __, ___, cell in self.history_manager.get_tail(self.history_load_length,
339 for __, ___, cell in self.history_manager.get_tail(self.history_load_length,
342 include_latest=True):
340 include_latest=True):
343 # Ignore blank lines and consecutive duplicates
341 # Ignore blank lines and consecutive duplicates
344 cell = cell.rstrip()
342 cell = cell.rstrip()
345 if cell and (cell != last_cell):
343 if cell and (cell != last_cell):
346 history.append(cell)
344 history.append(cell)
347
345
348 self._style = self._make_style_from_name(self.highlighting_style)
346 self._style = self._make_style_from_name(self.highlighting_style)
349 style = DynamicStyle(lambda: self._style)
347 style = DynamicStyle(lambda: self._style)
350
348
351 editing_mode = getattr(EditingMode, self.editing_mode.upper())
349 editing_mode = getattr(EditingMode, self.editing_mode.upper())
352
350
353 self._pt_app = create_prompt_application(
351 self._pt_app = create_prompt_application(
354 editing_mode=editing_mode,
352 editing_mode=editing_mode,
355 key_bindings_registry=kbmanager.registry,
353 key_bindings_registry=kbmanager.registry,
356 history=history,
354 history=history,
357 completer=IPythonPTCompleter(self.Completer),
355 completer=IPythonPTCompleter(self.Completer),
358 enable_history_search=True,
356 enable_history_search=True,
359 style=style,
357 style=style,
360 mouse_support=self.mouse_support,
358 mouse_support=self.mouse_support,
361 **self._layout_options()
359 **self._layout_options()
362 )
360 )
363 self._eventloop = create_eventloop(self.inputhook)
361 self._eventloop = create_eventloop(self.inputhook)
364 self.pt_cli = CommandLineInterface(self._pt_app, eventloop=self._eventloop)
362 self.pt_cli = CommandLineInterface(self._pt_app, eventloop=self._eventloop)
365
363
366 def _make_style_from_name(self, name):
364 def _make_style_from_name(self, name):
367 """
365 """
368 Small wrapper that make an IPython compatible style from a style name
366 Small wrapper that make an IPython compatible style from a style name
369
367
370 We need that to add style for prompt ... etc.
368 We need that to add style for prompt ... etc.
371 """
369 """
372 style_overrides = {}
370 style_overrides = {}
373 if name == 'legacy':
371 if name == 'legacy':
374 legacy = self.colors.lower()
372 legacy = self.colors.lower()
375 if legacy == 'linux':
373 if legacy == 'linux':
376 style_cls = get_style_by_name('monokai')
374 style_cls = get_style_by_name('monokai')
377 style_overrides = _style_overrides_linux
375 style_overrides = _style_overrides_linux
378 elif legacy == 'lightbg':
376 elif legacy == 'lightbg':
379 style_overrides = _style_overrides_light_bg
377 style_overrides = _style_overrides_light_bg
380 style_cls = get_style_by_name('pastie')
378 style_cls = get_style_by_name('pastie')
381 elif legacy == 'neutral':
379 elif legacy == 'neutral':
382 # The default theme needs to be visible on both a dark background
380 # The default theme needs to be visible on both a dark background
383 # and a light background, because we can't tell what the terminal
381 # and a light background, because we can't tell what the terminal
384 # looks like. These tweaks to the default theme help with that.
382 # looks like. These tweaks to the default theme help with that.
385 style_cls = get_style_by_name('default')
383 style_cls = get_style_by_name('default')
386 style_overrides.update({
384 style_overrides.update({
387 Token.Number: '#007700',
385 Token.Number: '#007700',
388 Token.Operator: 'noinherit',
386 Token.Operator: 'noinherit',
389 Token.String: '#BB6622',
387 Token.String: '#BB6622',
390 Token.Name.Function: '#2080D0',
388 Token.Name.Function: '#2080D0',
391 Token.Name.Class: 'bold #2080D0',
389 Token.Name.Class: 'bold #2080D0',
392 Token.Name.Namespace: 'bold #2080D0',
390 Token.Name.Namespace: 'bold #2080D0',
393 Token.Prompt: '#009900',
391 Token.Prompt: '#009900',
394 Token.PromptNum: '#00ff00 bold',
392 Token.PromptNum: '#00ff00 bold',
395 Token.OutPrompt: '#990000',
393 Token.OutPrompt: '#990000',
396 Token.OutPromptNum: '#ff0000 bold',
394 Token.OutPromptNum: '#ff0000 bold',
397 })
395 })
398 elif legacy =='nocolor':
396 elif legacy =='nocolor':
399 style_cls=_NoStyle
397 style_cls=_NoStyle
400 style_overrides = {}
398 style_overrides = {}
401 else :
399 else :
402 raise ValueError('Got unknown colors: ', legacy)
400 raise ValueError('Got unknown colors: ', legacy)
403 else :
401 else :
404 style_cls = get_style_by_name(name)
402 style_cls = get_style_by_name(name)
405 style_overrides = {
403 style_overrides = {
406 Token.Prompt: '#009900',
404 Token.Prompt: '#009900',
407 Token.PromptNum: '#00ff00 bold',
405 Token.PromptNum: '#00ff00 bold',
408 Token.OutPrompt: '#990000',
406 Token.OutPrompt: '#990000',
409 Token.OutPromptNum: '#ff0000 bold',
407 Token.OutPromptNum: '#ff0000 bold',
410 }
408 }
411 style_overrides.update(self.highlighting_style_overrides)
409 style_overrides.update(self.highlighting_style_overrides)
412 style = PygmentsStyle.from_defaults(pygments_style_cls=style_cls,
410 style = PygmentsStyle.from_defaults(pygments_style_cls=style_cls,
413 style_dict=style_overrides)
411 style_dict=style_overrides)
414
412
415 return style
413 return style
416
414
417 def _layout_options(self):
415 def _layout_options(self):
418 """
416 """
419 Return the current layout option for the current Terminal InteractiveShell
417 Return the current layout option for the current Terminal InteractiveShell
420 """
418 """
421 return {
419 return {
422 'lexer':IPythonPTLexer(),
420 'lexer':IPythonPTLexer(),
423 'reserve_space_for_menu':self.space_for_menu,
421 'reserve_space_for_menu':self.space_for_menu,
424 'get_prompt_tokens':self.prompts.in_prompt_tokens,
422 'get_prompt_tokens':self.prompts.in_prompt_tokens,
425 'get_continuation_tokens':self.prompts.continuation_prompt_tokens,
423 'get_continuation_tokens':self.prompts.continuation_prompt_tokens,
426 'multiline':True,
424 'multiline':True,
427 'display_completions_in_columns': (self.display_completions == 'multicolumn'),
425 'display_completions_in_columns': (self.display_completions == 'multicolumn'),
428
426
429 # Highlight matching brackets, but only when this setting is
427 # Highlight matching brackets, but only when this setting is
430 # enabled, and only when the DEFAULT_BUFFER has the focus.
428 # enabled, and only when the DEFAULT_BUFFER has the focus.
431 'extra_input_processors': [ConditionalProcessor(
429 'extra_input_processors': [ConditionalProcessor(
432 processor=HighlightMatchingBracketProcessor(chars='[](){}'),
430 processor=HighlightMatchingBracketProcessor(chars='[](){}'),
433 filter=HasFocus(DEFAULT_BUFFER) & ~IsDone() &
431 filter=HasFocus(DEFAULT_BUFFER) & ~IsDone() &
434 Condition(lambda cli: self.highlight_matching_brackets))],
432 Condition(lambda cli: self.highlight_matching_brackets))],
435 }
433 }
436
434
437 def _update_layout(self):
435 def _update_layout(self):
438 """
436 """
439 Ask for a re computation of the application layout, if for example ,
437 Ask for a re computation of the application layout, if for example ,
440 some configuration options have changed.
438 some configuration options have changed.
441 """
439 """
442 if self._pt_app:
440 if self._pt_app:
443 self._pt_app.layout = create_prompt_layout(**self._layout_options())
441 self._pt_app.layout = create_prompt_layout(**self._layout_options())
444
442
445 def prompt_for_code(self):
443 def prompt_for_code(self):
446 document = self.pt_cli.run(
444 document = self.pt_cli.run(
447 pre_run=self.pre_prompt, reset_current_buffer=True)
445 pre_run=self.pre_prompt, reset_current_buffer=True)
448 return document.text
446 return document.text
449
447
450 def init_io(self):
448 def init_io(self):
451 if sys.platform not in {'win32', 'cli'}:
449 if sys.platform not in {'win32', 'cli'}:
452 return
450 return
453
451
454 import win_unicode_console
452 import win_unicode_console
455 import colorama
453 import colorama
456
454
457 win_unicode_console.enable()
455 win_unicode_console.enable()
458 colorama.init()
456 colorama.init()
459
457
460 # For some reason we make these wrappers around stdout/stderr.
458 # For some reason we make these wrappers around stdout/stderr.
461 # For now, we need to reset them so all output gets coloured.
459 # For now, we need to reset them so all output gets coloured.
462 # https://github.com/ipython/ipython/issues/8669
460 # https://github.com/ipython/ipython/issues/8669
463 from IPython.utils import io
461 from IPython.utils import io
464 io.stdout = io.IOStream(sys.stdout)
462 io.stdout = io.IOStream(sys.stdout)
465 io.stderr = io.IOStream(sys.stderr)
463 io.stderr = io.IOStream(sys.stderr)
466
464
467 def init_magics(self):
465 def init_magics(self):
468 super(TerminalInteractiveShell, self).init_magics()
466 super(TerminalInteractiveShell, self).init_magics()
469 self.register_magics(TerminalMagics)
467 self.register_magics(TerminalMagics)
470
468
471 def init_alias(self):
469 def init_alias(self):
472 # The parent class defines aliases that can be safely used with any
470 # The parent class defines aliases that can be safely used with any
473 # frontend.
471 # frontend.
474 super(TerminalInteractiveShell, self).init_alias()
472 super(TerminalInteractiveShell, self).init_alias()
475
473
476 # Now define aliases that only make sense on the terminal, because they
474 # Now define aliases that only make sense on the terminal, because they
477 # need direct access to the console in a way that we can't emulate in
475 # need direct access to the console in a way that we can't emulate in
478 # GUI or web frontend
476 # GUI or web frontend
479 if os.name == 'posix':
477 if os.name == 'posix':
480 for cmd in ['clear', 'more', 'less', 'man']:
478 for cmd in ['clear', 'more', 'less', 'man']:
481 self.alias_manager.soft_define_alias(cmd, cmd)
479 self.alias_manager.soft_define_alias(cmd, cmd)
482
480
483
481
484 def __init__(self, *args, **kwargs):
482 def __init__(self, *args, **kwargs):
485 super(TerminalInteractiveShell, self).__init__(*args, **kwargs)
483 super(TerminalInteractiveShell, self).__init__(*args, **kwargs)
486 self.init_prompt_toolkit_cli()
484 self.init_prompt_toolkit_cli()
487 self.init_term_title()
485 self.init_term_title()
488 self.keep_running = True
486 self.keep_running = True
489
487
490 self.debugger_history = InMemoryHistory()
488 self.debugger_history = InMemoryHistory()
491
489
492 def ask_exit(self):
490 def ask_exit(self):
493 self.keep_running = False
491 self.keep_running = False
494
492
495 rl_next_input = None
493 rl_next_input = None
496
494
497 def pre_prompt(self):
495 def pre_prompt(self):
498 if self.rl_next_input:
496 if self.rl_next_input:
499 self.pt_cli.application.buffer.text = cast_unicode_py2(self.rl_next_input)
497 self.pt_cli.application.buffer.text = cast_unicode_py2(self.rl_next_input)
500 self.rl_next_input = None
498 self.rl_next_input = None
501
499
502 def interact(self, display_banner=DISPLAY_BANNER_DEPRECATED):
500 def interact(self, display_banner=DISPLAY_BANNER_DEPRECATED):
503
501
504 if display_banner is not DISPLAY_BANNER_DEPRECATED:
502 if display_banner is not DISPLAY_BANNER_DEPRECATED:
505 warn('interact `display_banner` argument is deprecated since IPython 5.0. Call `show_banner()` if needed.', DeprecationWarning, stacklevel=2)
503 warn('interact `display_banner` argument is deprecated since IPython 5.0. Call `show_banner()` if needed.', DeprecationWarning, stacklevel=2)
506
504
507 while self.keep_running:
505 while self.keep_running:
508 print(self.separate_in, end='')
506 print(self.separate_in, end='')
509
507
510 try:
508 try:
511 code = self.prompt_for_code()
509 code = self.prompt_for_code()
512 except EOFError:
510 except EOFError:
513 if (not self.confirm_exit) \
511 if (not self.confirm_exit) \
514 or self.ask_yes_no('Do you really want to exit ([y]/n)?','y','n'):
512 or self.ask_yes_no('Do you really want to exit ([y]/n)?','y','n'):
515 self.ask_exit()
513 self.ask_exit()
516
514
517 else:
515 else:
518 if code:
516 if code:
519 self.run_cell(code, store_history=True)
517 self.run_cell(code, store_history=True)
520
518
521 def mainloop(self, display_banner=DISPLAY_BANNER_DEPRECATED):
519 def mainloop(self, display_banner=DISPLAY_BANNER_DEPRECATED):
522 # An extra layer of protection in case someone mashing Ctrl-C breaks
520 # An extra layer of protection in case someone mashing Ctrl-C breaks
523 # out of our internal code.
521 # out of our internal code.
524 if display_banner is not DISPLAY_BANNER_DEPRECATED:
522 if display_banner is not DISPLAY_BANNER_DEPRECATED:
525 warn('mainloop `display_banner` argument is deprecated since IPython 5.0. Call `show_banner()` if needed.', DeprecationWarning, stacklevel=2)
523 warn('mainloop `display_banner` argument is deprecated since IPython 5.0. Call `show_banner()` if needed.', DeprecationWarning, stacklevel=2)
526 while True:
524 while True:
527 try:
525 try:
528 self.interact()
526 self.interact()
529 break
527 break
530 except KeyboardInterrupt:
528 except KeyboardInterrupt:
531 print("\nKeyboardInterrupt escaped interact()\n")
529 print("\nKeyboardInterrupt escaped interact()\n")
532
530
533 if hasattr(self, '_eventloop'):
531 if hasattr(self, '_eventloop'):
534 self._eventloop.close()
532 self._eventloop.close()
535
533
536 _inputhook = None
534 _inputhook = None
537 def inputhook(self, context):
535 def inputhook(self, context):
538 if self._inputhook is not None:
536 if self._inputhook is not None:
539 self._inputhook(context)
537 self._inputhook(context)
540
538
541 def enable_gui(self, gui=None):
539 def enable_gui(self, gui=None):
542 if gui:
540 if gui:
543 self._inputhook = get_inputhook_func(gui)
541 self._inputhook = get_inputhook_func(gui)
544 else:
542 else:
545 self._inputhook = None
543 self._inputhook = None
546
544
547 # Run !system commands directly, not through pipes, so terminal programs
545 # Run !system commands directly, not through pipes, so terminal programs
548 # work correctly.
546 # work correctly.
549 system = InteractiveShell.system_raw
547 system = InteractiveShell.system_raw
550
548
551 def auto_rewrite_input(self, cmd):
549 def auto_rewrite_input(self, cmd):
552 """Overridden from the parent class to use fancy rewriting prompt"""
550 """Overridden from the parent class to use fancy rewriting prompt"""
553 if not self.show_rewritten_input:
551 if not self.show_rewritten_input:
554 return
552 return
555
553
556 tokens = self.prompts.rewrite_prompt_tokens()
554 tokens = self.prompts.rewrite_prompt_tokens()
557 if self.pt_cli:
555 if self.pt_cli:
558 self.pt_cli.print_tokens(tokens)
556 self.pt_cli.print_tokens(tokens)
559 print(cmd)
557 print(cmd)
560 else:
558 else:
561 prompt = ''.join(s for t, s in tokens)
559 prompt = ''.join(s for t, s in tokens)
562 print(prompt, cmd, sep='')
560 print(prompt, cmd, sep='')
563
561
564 _prompts_before = None
562 _prompts_before = None
565 def switch_doctest_mode(self, mode):
563 def switch_doctest_mode(self, mode):
566 """Switch prompts to classic for %doctest_mode"""
564 """Switch prompts to classic for %doctest_mode"""
567 if mode:
565 if mode:
568 self._prompts_before = self.prompts
566 self._prompts_before = self.prompts
569 self.prompts = ClassicPrompts(self)
567 self.prompts = ClassicPrompts(self)
570 elif self._prompts_before:
568 elif self._prompts_before:
571 self.prompts = self._prompts_before
569 self.prompts = self._prompts_before
572 self._prompts_before = None
570 self._prompts_before = None
573 self._update_layout()
571 self._update_layout()
574
572
575
573
576 InteractiveShellABC.register(TerminalInteractiveShell)
574 InteractiveShellABC.register(TerminalInteractiveShell)
577
575
578 if __name__ == '__main__':
576 if __name__ == '__main__':
579 TerminalInteractiveShell.instance().interact()
577 TerminalInteractiveShell.instance().interact()
General Comments 0
You need to be logged in to leave comments. Login now