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