##// END OF EJS Templates
remove rest of readline, pass II
Matthias Bussonnier -
Show More
@@ -1,3253 +1,3241 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
66 from IPython.utils.decorators import undoc
65 from IPython.utils.decorators import undoc
67 from IPython.utils.io import ask_yes_no
66 from IPython.utils.io import ask_yes_no
68 from IPython.utils.ipstruct import Struct
67 from IPython.utils.ipstruct import Struct
69 from IPython.paths import get_ipython_dir
68 from IPython.paths import get_ipython_dir
70 from IPython.utils.path import get_home_dir, get_py_filename, ensure_dir_exists
69 from IPython.utils.path import get_home_dir, get_py_filename, ensure_dir_exists
71 from IPython.utils.process import system, getoutput
70 from IPython.utils.process import system, getoutput
72 from IPython.utils.py3compat import (builtin_mod, unicode_type, string_types,
71 from IPython.utils.py3compat import (builtin_mod, unicode_type, string_types,
73 with_metaclass, iteritems)
72 with_metaclass, iteritems)
74 from IPython.utils.strdispatch import StrDispatch
73 from IPython.utils.strdispatch import StrDispatch
75 from IPython.utils.syspathcontext import prepended_to_syspath
74 from IPython.utils.syspathcontext import prepended_to_syspath
76 from IPython.utils.text import format_screen, LSString, SList, DollarFormatter
75 from IPython.utils.text import format_screen, LSString, SList, DollarFormatter
77 from IPython.utils.tempdir import TemporaryDirectory
76 from IPython.utils.tempdir import TemporaryDirectory
78 from traitlets import (
77 from traitlets import (
79 Integer, Bool, CaselessStrEnum, Enum, List, Dict, Unicode, Instance, Type,
78 Integer, Bool, CaselessStrEnum, Enum, List, Dict, Unicode, Instance, Type,
80 observe, default,
79 observe, default,
81 )
80 )
82 from warnings import warn
81 from warnings import warn
83 from logging import error
82 from logging import error
84 import IPython.core.hooks
83 import IPython.core.hooks
85
84
86 try:
85 try:
87 import docrepr.sphinxify as sphx
86 import docrepr.sphinxify as sphx
88
87
89 def sphinxify(doc):
88 def sphinxify(doc):
90 with TemporaryDirectory() as dirname:
89 with TemporaryDirectory() as dirname:
91 return {
90 return {
92 'text/html': sphx.sphinxify(doc, dirname),
91 'text/html': sphx.sphinxify(doc, dirname),
93 'text/plain': doc
92 'text/plain': doc
94 }
93 }
95 except ImportError:
94 except ImportError:
96 sphinxify = None
95 sphinxify = None
97
96
98
97
99 class ProvisionalWarning(DeprecationWarning):
98 class ProvisionalWarning(DeprecationWarning):
100 """
99 """
101 Warning class for unstable features
100 Warning class for unstable features
102 """
101 """
103 pass
102 pass
104
103
105 #-----------------------------------------------------------------------------
104 #-----------------------------------------------------------------------------
106 # Globals
105 # Globals
107 #-----------------------------------------------------------------------------
106 #-----------------------------------------------------------------------------
108
107
109 # compiled regexps for autoindent management
108 # compiled regexps for autoindent management
110 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
109 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
111
110
112 #-----------------------------------------------------------------------------
111 #-----------------------------------------------------------------------------
113 # Utilities
112 # Utilities
114 #-----------------------------------------------------------------------------
113 #-----------------------------------------------------------------------------
115
114
116 @undoc
115 @undoc
117 def softspace(file, newvalue):
116 def softspace(file, newvalue):
118 """Copied from code.py, to remove the dependency"""
117 """Copied from code.py, to remove the dependency"""
119
118
120 oldvalue = 0
119 oldvalue = 0
121 try:
120 try:
122 oldvalue = file.softspace
121 oldvalue = file.softspace
123 except AttributeError:
122 except AttributeError:
124 pass
123 pass
125 try:
124 try:
126 file.softspace = newvalue
125 file.softspace = newvalue
127 except (AttributeError, TypeError):
126 except (AttributeError, TypeError):
128 # "attribute-less object" or "read-only attributes"
127 # "attribute-less object" or "read-only attributes"
129 pass
128 pass
130 return oldvalue
129 return oldvalue
131
130
132 @undoc
131 @undoc
133 def no_op(*a, **kw): pass
132 def no_op(*a, **kw): pass
134
133
135
134
136 class SpaceInInput(Exception): pass
135 class SpaceInInput(Exception): pass
137
136
138
137
139 def get_default_colors():
138 def get_default_colors():
140 "DEPRECATED"
139 "DEPRECATED"
141 warn('get_default_color is Deprecated, and is `Neutral` on all platforms.',
140 warn('get_default_color is Deprecated, and is `Neutral` on all platforms.',
142 DeprecationWarning, stacklevel=2)
141 DeprecationWarning, stacklevel=2)
143 return 'Neutral'
142 return 'Neutral'
144
143
145
144
146 class SeparateUnicode(Unicode):
145 class SeparateUnicode(Unicode):
147 r"""A Unicode subclass to validate separate_in, separate_out, etc.
146 r"""A Unicode subclass to validate separate_in, separate_out, etc.
148
147
149 This is a Unicode based trait that converts '0'->'' and ``'\\n'->'\n'``.
148 This is a Unicode based trait that converts '0'->'' and ``'\\n'->'\n'``.
150 """
149 """
151
150
152 def validate(self, obj, value):
151 def validate(self, obj, value):
153 if value == '0': value = ''
152 if value == '0': value = ''
154 value = value.replace('\\n','\n')
153 value = value.replace('\\n','\n')
155 return super(SeparateUnicode, self).validate(obj, value)
154 return super(SeparateUnicode, self).validate(obj, value)
156
155
157
156
158 @undoc
157 @undoc
159 class DummyMod(object):
158 class DummyMod(object):
160 """A dummy module used for IPython's interactive module when
159 """A dummy module used for IPython's interactive module when
161 a namespace must be assigned to the module's __dict__."""
160 a namespace must be assigned to the module's __dict__."""
162 pass
161 pass
163
162
164
163
165 class ExecutionResult(object):
164 class ExecutionResult(object):
166 """The result of a call to :meth:`InteractiveShell.run_cell`
165 """The result of a call to :meth:`InteractiveShell.run_cell`
167
166
168 Stores information about what took place.
167 Stores information about what took place.
169 """
168 """
170 execution_count = None
169 execution_count = None
171 error_before_exec = None
170 error_before_exec = None
172 error_in_exec = None
171 error_in_exec = None
173 result = None
172 result = None
174
173
175 @property
174 @property
176 def success(self):
175 def success(self):
177 return (self.error_before_exec is None) and (self.error_in_exec is None)
176 return (self.error_before_exec is None) and (self.error_in_exec is None)
178
177
179 def raise_error(self):
178 def raise_error(self):
180 """Reraises error if `success` is `False`, otherwise does nothing"""
179 """Reraises error if `success` is `False`, otherwise does nothing"""
181 if self.error_before_exec is not None:
180 if self.error_before_exec is not None:
182 raise self.error_before_exec
181 raise self.error_before_exec
183 if self.error_in_exec is not None:
182 if self.error_in_exec is not None:
184 raise self.error_in_exec
183 raise self.error_in_exec
185
184
186 def __repr__(self):
185 def __repr__(self):
187 return '<%s object at %x, execution_count=%s error_before_exec=%s error_in_exec=%s result=%s>' %\
186 return '<%s object at %x, execution_count=%s error_before_exec=%s error_in_exec=%s result=%s>' %\
188 (self.__class__.__qualname__, id(self), self.execution_count, self.error_before_exec, self.error_in_exec, repr(self.result))
187 (self.__class__.__qualname__, id(self), self.execution_count, self.error_before_exec, self.error_in_exec, repr(self.result))
189
188
190
189
191 class InteractiveShell(SingletonConfigurable):
190 class InteractiveShell(SingletonConfigurable):
192 """An enhanced, interactive shell for Python."""
191 """An enhanced, interactive shell for Python."""
193
192
194 _instance = None
193 _instance = None
195
194
196 ast_transformers = List([], help=
195 ast_transformers = List([], help=
197 """
196 """
198 A list of ast.NodeTransformer subclass instances, which will be applied
197 A list of ast.NodeTransformer subclass instances, which will be applied
199 to user input before code is run.
198 to user input before code is run.
200 """
199 """
201 ).tag(config=True)
200 ).tag(config=True)
202
201
203 autocall = Enum((0,1,2), default_value=0, help=
202 autocall = Enum((0,1,2), default_value=0, help=
204 """
203 """
205 Make IPython automatically call any callable object even if you didn't
204 Make IPython automatically call any callable object even if you didn't
206 type explicit parentheses. For example, 'str 43' becomes 'str(43)'
205 type explicit parentheses. For example, 'str 43' becomes 'str(43)'
207 automatically. The value can be '0' to disable the feature, '1' for
206 automatically. The value can be '0' to disable the feature, '1' for
208 'smart' autocall, where it is not applied if there are no more
207 'smart' autocall, where it is not applied if there are no more
209 arguments on the line, and '2' for 'full' autocall, where all callable
208 arguments on the line, and '2' for 'full' autocall, where all callable
210 objects are automatically called (even if no arguments are present).
209 objects are automatically called (even if no arguments are present).
211 """
210 """
212 ).tag(config=True)
211 ).tag(config=True)
213 # TODO: remove all autoindent logic and put into frontends.
212 # TODO: remove all autoindent logic and put into frontends.
214 # We can't do this yet because even runlines uses the autoindent.
213 # We can't do this yet because even runlines uses the autoindent.
215 autoindent = Bool(True, help=
214 autoindent = Bool(True, help=
216 """
215 """
217 Autoindent IPython code entered interactively.
216 Autoindent IPython code entered interactively.
218 """
217 """
219 ).tag(config=True)
218 ).tag(config=True)
220
219
221 automagic = Bool(True, help=
220 automagic = Bool(True, help=
222 """
221 """
223 Enable magic commands to be called without the leading %.
222 Enable magic commands to be called without the leading %.
224 """
223 """
225 ).tag(config=True)
224 ).tag(config=True)
226
225
227 banner1 = Unicode(default_banner,
226 banner1 = Unicode(default_banner,
228 help="""The part of the banner to be printed before the profile"""
227 help="""The part of the banner to be printed before the profile"""
229 ).tag(config=True)
228 ).tag(config=True)
230 banner2 = Unicode('',
229 banner2 = Unicode('',
231 help="""The part of the banner to be printed after the profile"""
230 help="""The part of the banner to be printed after the profile"""
232 ).tag(config=True)
231 ).tag(config=True)
233
232
234 cache_size = Integer(1000, help=
233 cache_size = Integer(1000, help=
235 """
234 """
236 Set the size of the output cache. The default is 1000, you can
235 Set the size of the output cache. The default is 1000, you can
237 change it permanently in your config file. Setting it to 0 completely
236 change it permanently in your config file. Setting it to 0 completely
238 disables the caching system, and the minimum value accepted is 20 (if
237 disables the caching system, and the minimum value accepted is 20 (if
239 you provide a value less than 20, it is reset to 0 and a warning is
238 you provide a value less than 20, it is reset to 0 and a warning is
240 issued). This limit is defined because otherwise you'll spend more
239 issued). This limit is defined because otherwise you'll spend more
241 time re-flushing a too small cache than working
240 time re-flushing a too small cache than working
242 """
241 """
243 ).tag(config=True)
242 ).tag(config=True)
244 color_info = Bool(True, help=
243 color_info = Bool(True, help=
245 """
244 """
246 Use colors for displaying information about objects. Because this
245 Use colors for displaying information about objects. Because this
247 information is passed through a pager (like 'less'), and some pagers
246 information is passed through a pager (like 'less'), and some pagers
248 get confused with color codes, this capability can be turned off.
247 get confused with color codes, this capability can be turned off.
249 """
248 """
250 ).tag(config=True)
249 ).tag(config=True)
251 colors = CaselessStrEnum(('Neutral', 'NoColor','LightBG','Linux'),
250 colors = CaselessStrEnum(('Neutral', 'NoColor','LightBG','Linux'),
252 default_value='Neutral',
251 default_value='Neutral',
253 help="Set the color scheme (NoColor, Neutral, Linux, or LightBG)."
252 help="Set the color scheme (NoColor, Neutral, Linux, or LightBG)."
254 ).tag(config=True)
253 ).tag(config=True)
255 debug = Bool(False).tag(config=True)
254 debug = Bool(False).tag(config=True)
256 deep_reload = Bool(False, help=
255 deep_reload = Bool(False, help=
257 """
256 """
258 **Deprecated**
257 **Deprecated**
259
258
260 Will be removed in IPython 6.0
259 Will be removed in IPython 6.0
261
260
262 Enable deep (recursive) reloading by default. IPython can use the
261 Enable deep (recursive) reloading by default. IPython can use the
263 deep_reload module which reloads changes in modules recursively (it
262 deep_reload module which reloads changes in modules recursively (it
264 replaces the reload() function, so you don't need to change anything to
263 replaces the reload() function, so you don't need to change anything to
265 use it). `deep_reload` forces a full reload of modules whose code may
264 use it). `deep_reload` forces a full reload of modules whose code may
266 have changed, which the default reload() function does not. When
265 have changed, which the default reload() function does not. When
267 deep_reload is off, IPython will use the normal reload(), but
266 deep_reload is off, IPython will use the normal reload(), but
268 deep_reload will still be available as dreload().
267 deep_reload will still be available as dreload().
269 """
268 """
270 ).tag(config=True)
269 ).tag(config=True)
271 disable_failing_post_execute = Bool(False,
270 disable_failing_post_execute = Bool(False,
272 help="Don't call post-execute functions that have failed in the past."
271 help="Don't call post-execute functions that have failed in the past."
273 ).tag(config=True)
272 ).tag(config=True)
274 display_formatter = Instance(DisplayFormatter, allow_none=True)
273 display_formatter = Instance(DisplayFormatter, allow_none=True)
275 displayhook_class = Type(DisplayHook)
274 displayhook_class = Type(DisplayHook)
276 display_pub_class = Type(DisplayPublisher)
275 display_pub_class = Type(DisplayPublisher)
277
276
278 sphinxify_docstring = Bool(False, help=
277 sphinxify_docstring = Bool(False, help=
279 """
278 """
280 Enables rich html representation of docstrings. (This requires the
279 Enables rich html representation of docstrings. (This requires the
281 docrepr module).
280 docrepr module).
282 """).tag(config=True)
281 """).tag(config=True)
283
282
284 @observe("sphinxify_docstring")
283 @observe("sphinxify_docstring")
285 def _sphinxify_docstring_changed(self, change):
284 def _sphinxify_docstring_changed(self, change):
286 if change['new']:
285 if change['new']:
287 warn("`sphinxify_docstring` is provisional since IPython 5.0 and might change in future versions." , ProvisionalWarning)
286 warn("`sphinxify_docstring` is provisional since IPython 5.0 and might change in future versions." , ProvisionalWarning)
288
287
289 enable_html_pager = Bool(False, help=
288 enable_html_pager = Bool(False, help=
290 """
289 """
291 (Provisional API) enables html representation in mime bundles sent
290 (Provisional API) enables html representation in mime bundles sent
292 to pagers.
291 to pagers.
293 """).tag(config=True)
292 """).tag(config=True)
294
293
295 @observe("enable_html_pager")
294 @observe("enable_html_pager")
296 def _enable_html_pager_changed(self, change):
295 def _enable_html_pager_changed(self, change):
297 if change['new']:
296 if change['new']:
298 warn("`enable_html_pager` is provisional since IPython 5.0 and might change in future versions.", ProvisionalWarning)
297 warn("`enable_html_pager` is provisional since IPython 5.0 and might change in future versions.", ProvisionalWarning)
299
298
300 data_pub_class = None
299 data_pub_class = None
301
300
302 exit_now = Bool(False)
301 exit_now = Bool(False)
303 exiter = Instance(ExitAutocall)
302 exiter = Instance(ExitAutocall)
304 @default('exiter')
303 @default('exiter')
305 def _exiter_default(self):
304 def _exiter_default(self):
306 return ExitAutocall(self)
305 return ExitAutocall(self)
307 # Monotonically increasing execution counter
306 # Monotonically increasing execution counter
308 execution_count = Integer(1)
307 execution_count = Integer(1)
309 filename = Unicode("<ipython console>")
308 filename = Unicode("<ipython console>")
310 ipython_dir= Unicode('').tag(config=True) # Set to get_ipython_dir() in __init__
309 ipython_dir= Unicode('').tag(config=True) # Set to get_ipython_dir() in __init__
311
310
312 # Input splitter, to transform input line by line and detect when a block
311 # Input splitter, to transform input line by line and detect when a block
313 # is ready to be executed.
312 # is ready to be executed.
314 input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
313 input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
315 (), {'line_input_checker': True})
314 (), {'line_input_checker': True})
316
315
317 # This InputSplitter instance is used to transform completed cells before
316 # This InputSplitter instance is used to transform completed cells before
318 # running them. It allows cell magics to contain blank lines.
317 # running them. It allows cell magics to contain blank lines.
319 input_transformer_manager = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
318 input_transformer_manager = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
320 (), {'line_input_checker': False})
319 (), {'line_input_checker': False})
321
320
322 logstart = Bool(False, help=
321 logstart = Bool(False, help=
323 """
322 """
324 Start logging to the default log file in overwrite mode.
323 Start logging to the default log file in overwrite mode.
325 Use `logappend` to specify a log file to **append** logs to.
324 Use `logappend` to specify a log file to **append** logs to.
326 """
325 """
327 ).tag(config=True)
326 ).tag(config=True)
328 logfile = Unicode('', help=
327 logfile = Unicode('', help=
329 """
328 """
330 The name of the logfile to use.
329 The name of the logfile to use.
331 """
330 """
332 ).tag(config=True)
331 ).tag(config=True)
333 logappend = Unicode('', help=
332 logappend = Unicode('', help=
334 """
333 """
335 Start logging to the given file in append mode.
334 Start logging to the given file in append mode.
336 Use `logfile` to specify a log file to **overwrite** logs to.
335 Use `logfile` to specify a log file to **overwrite** logs to.
337 """
336 """
338 ).tag(config=True)
337 ).tag(config=True)
339 object_info_string_level = Enum((0,1,2), default_value=0,
338 object_info_string_level = Enum((0,1,2), default_value=0,
340 ).tag(config=True)
339 ).tag(config=True)
341 pdb = Bool(False, help=
340 pdb = Bool(False, help=
342 """
341 """
343 Automatically call the pdb debugger after every exception.
342 Automatically call the pdb debugger after every exception.
344 """
343 """
345 ).tag(config=True)
344 ).tag(config=True)
346 display_page = Bool(False,
345 display_page = Bool(False,
347 help="""If True, anything that would be passed to the pager
346 help="""If True, anything that would be passed to the pager
348 will be displayed as regular output instead."""
347 will be displayed as regular output instead."""
349 ).tag(config=True)
348 ).tag(config=True)
350
349
351 # deprecated prompt traits:
350 # deprecated prompt traits:
352
351
353 prompt_in1 = Unicode('In [\\#]: ',
352 prompt_in1 = Unicode('In [\\#]: ',
354 help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
353 help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
355 ).tag(config=True)
354 ).tag(config=True)
356 prompt_in2 = Unicode(' .\\D.: ',
355 prompt_in2 = Unicode(' .\\D.: ',
357 help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
356 help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
358 ).tag(config=True)
357 ).tag(config=True)
359 prompt_out = Unicode('Out[\\#]: ',
358 prompt_out = Unicode('Out[\\#]: ',
360 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."
361 ).tag(config=True)
360 ).tag(config=True)
362 prompts_pad_left = Bool(True,
361 prompts_pad_left = Bool(True,
363 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."
364 ).tag(config=True)
363 ).tag(config=True)
365
364
366 @observe('prompt_in1', 'prompt_in2', 'prompt_out', 'prompt_pad_left')
365 @observe('prompt_in1', 'prompt_in2', 'prompt_out', 'prompt_pad_left')
367 def _prompt_trait_changed(self, change):
366 def _prompt_trait_changed(self, change):
368 name = change['name']
367 name = change['name']
369 warn("InteractiveShell.{name} is deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly.".format(
368 warn("InteractiveShell.{name} is deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly.".format(
370 name=name)
369 name=name)
371 )
370 )
372 # protect against weird cases where self.config may not exist:
371 # protect against weird cases where self.config may not exist:
373
372
374 show_rewritten_input = Bool(True,
373 show_rewritten_input = Bool(True,
375 help="Show rewritten input, e.g. for autocall."
374 help="Show rewritten input, e.g. for autocall."
376 ).tag(config=True)
375 ).tag(config=True)
377
376
378 quiet = Bool(False).tag(config=True)
377 quiet = Bool(False).tag(config=True)
379
378
380 history_length = Integer(10000,
379 history_length = Integer(10000,
381 help='Total length of command history'
380 help='Total length of command history'
382 ).tag(config=True)
381 ).tag(config=True)
383
382
384 history_load_length = Integer(1000, help=
383 history_load_length = Integer(1000, help=
385 """
384 """
386 The number of saved history entries to be loaded
385 The number of saved history entries to be loaded
387 into the history buffer at startup.
386 into the history buffer at startup.
388 """
387 """
389 ).tag(config=True)
388 ).tag(config=True)
390
389
391 ast_node_interactivity = Enum(['all', 'last', 'last_expr', 'none'],
390 ast_node_interactivity = Enum(['all', 'last', 'last_expr', 'none'],
392 default_value='last_expr',
391 default_value='last_expr',
393 help="""
392 help="""
394 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
393 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
395 run interactively (displaying output from expressions)."""
394 run interactively (displaying output from expressions)."""
396 ).tag(config=True)
395 ).tag(config=True)
397
396
398 # TODO: this part of prompt management should be moved to the frontends.
397 # TODO: this part of prompt management should be moved to the frontends.
399 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
398 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
400 separate_in = SeparateUnicode('\n').tag(config=True)
399 separate_in = SeparateUnicode('\n').tag(config=True)
401 separate_out = SeparateUnicode('').tag(config=True)
400 separate_out = SeparateUnicode('').tag(config=True)
402 separate_out2 = SeparateUnicode('').tag(config=True)
401 separate_out2 = SeparateUnicode('').tag(config=True)
403 wildcards_case_sensitive = Bool(True).tag(config=True)
402 wildcards_case_sensitive = Bool(True).tag(config=True)
404 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
403 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
405 default_value='Context').tag(config=True)
404 default_value='Context').tag(config=True)
406
405
407 # Subcomponents of InteractiveShell
406 # Subcomponents of InteractiveShell
408 alias_manager = Instance('IPython.core.alias.AliasManager', allow_none=True)
407 alias_manager = Instance('IPython.core.alias.AliasManager', allow_none=True)
409 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager', allow_none=True)
408 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager', allow_none=True)
410 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap', allow_none=True)
409 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap', allow_none=True)
411 display_trap = Instance('IPython.core.display_trap.DisplayTrap', allow_none=True)
410 display_trap = Instance('IPython.core.display_trap.DisplayTrap', allow_none=True)
412 extension_manager = Instance('IPython.core.extensions.ExtensionManager', allow_none=True)
411 extension_manager = Instance('IPython.core.extensions.ExtensionManager', allow_none=True)
413 payload_manager = Instance('IPython.core.payload.PayloadManager', allow_none=True)
412 payload_manager = Instance('IPython.core.payload.PayloadManager', allow_none=True)
414 history_manager = Instance('IPython.core.history.HistoryAccessorBase', allow_none=True)
413 history_manager = Instance('IPython.core.history.HistoryAccessorBase', allow_none=True)
415 magics_manager = Instance('IPython.core.magic.MagicsManager', allow_none=True)
414 magics_manager = Instance('IPython.core.magic.MagicsManager', allow_none=True)
416
415
417 profile_dir = Instance('IPython.core.application.ProfileDir', allow_none=True)
416 profile_dir = Instance('IPython.core.application.ProfileDir', allow_none=True)
418 @property
417 @property
419 def profile(self):
418 def profile(self):
420 if self.profile_dir is not None:
419 if self.profile_dir is not None:
421 name = os.path.basename(self.profile_dir.location)
420 name = os.path.basename(self.profile_dir.location)
422 return name.replace('profile_','')
421 return name.replace('profile_','')
423
422
424
423
425 # Private interface
424 # Private interface
426 _post_execute = Dict()
425 _post_execute = Dict()
427
426
428 # Tracks any GUI loop loaded for pylab
427 # Tracks any GUI loop loaded for pylab
429 pylab_gui_select = None
428 pylab_gui_select = None
430
429
431 last_execution_succeeded = Bool(True, help='Did last executed command succeeded')
430 last_execution_succeeded = Bool(True, help='Did last executed command succeeded')
432
431
433 def __init__(self, ipython_dir=None, profile_dir=None,
432 def __init__(self, ipython_dir=None, profile_dir=None,
434 user_module=None, user_ns=None,
433 user_module=None, user_ns=None,
435 custom_exceptions=((), None), **kwargs):
434 custom_exceptions=((), None), **kwargs):
436
435
437 # This is where traits with a config_key argument are updated
436 # This is where traits with a config_key argument are updated
438 # from the values on config.
437 # from the values on config.
439 super(InteractiveShell, self).__init__(**kwargs)
438 super(InteractiveShell, self).__init__(**kwargs)
440 if 'PromptManager' in self.config:
439 if 'PromptManager' in self.config:
441 warn('As of IPython 5.0 `PromptManager` config will have no effect'
440 warn('As of IPython 5.0 `PromptManager` config will have no effect'
442 ' and has been replaced by TerminalInteractiveShell.prompts_class')
441 ' and has been replaced by TerminalInteractiveShell.prompts_class')
443 self.configurables = [self]
442 self.configurables = [self]
444
443
445 # These are relatively independent and stateless
444 # These are relatively independent and stateless
446 self.init_ipython_dir(ipython_dir)
445 self.init_ipython_dir(ipython_dir)
447 self.init_profile_dir(profile_dir)
446 self.init_profile_dir(profile_dir)
448 self.init_instance_attrs()
447 self.init_instance_attrs()
449 self.init_environment()
448 self.init_environment()
450
449
451 # Check if we're in a virtualenv, and set up sys.path.
450 # Check if we're in a virtualenv, and set up sys.path.
452 self.init_virtualenv()
451 self.init_virtualenv()
453
452
454 # Create namespaces (user_ns, user_global_ns, etc.)
453 # Create namespaces (user_ns, user_global_ns, etc.)
455 self.init_create_namespaces(user_module, user_ns)
454 self.init_create_namespaces(user_module, user_ns)
456 # This has to be done after init_create_namespaces because it uses
455 # This has to be done after init_create_namespaces because it uses
457 # something in self.user_ns, but before init_sys_modules, which
456 # something in self.user_ns, but before init_sys_modules, which
458 # is the first thing to modify sys.
457 # is the first thing to modify sys.
459 # TODO: When we override sys.stdout and sys.stderr before this class
458 # TODO: When we override sys.stdout and sys.stderr before this class
460 # is created, we are saving the overridden ones here. Not sure if this
459 # is created, we are saving the overridden ones here. Not sure if this
461 # is what we want to do.
460 # is what we want to do.
462 self.save_sys_module_state()
461 self.save_sys_module_state()
463 self.init_sys_modules()
462 self.init_sys_modules()
464
463
465 # While we're trying to have each part of the code directly access what
464 # While we're trying to have each part of the code directly access what
466 # it needs without keeping redundant references to objects, we have too
465 # it needs without keeping redundant references to objects, we have too
467 # much legacy code that expects ip.db to exist.
466 # much legacy code that expects ip.db to exist.
468 self.db = PickleShareDB(os.path.join(self.profile_dir.location, 'db'))
467 self.db = PickleShareDB(os.path.join(self.profile_dir.location, 'db'))
469
468
470 self.init_history()
469 self.init_history()
471 self.init_encoding()
470 self.init_encoding()
472 self.init_prefilter()
471 self.init_prefilter()
473
472
474 self.init_syntax_highlighting()
473 self.init_syntax_highlighting()
475 self.init_hooks()
474 self.init_hooks()
476 self.init_events()
475 self.init_events()
477 self.init_pushd_popd_magic()
476 self.init_pushd_popd_magic()
478 # self.init_traceback_handlers use to be here, but we moved it below
477 # self.init_traceback_handlers use to be here, but we moved it below
479 # because it and init_io have to come after init_readline.
478 # because it and init_io have to come after init_readline.
480 self.init_user_ns()
479 self.init_user_ns()
481 self.init_logger()
480 self.init_logger()
482 self.init_builtins()
481 self.init_builtins()
483
482
484 # The following was in post_config_initialization
483 # The following was in post_config_initialization
485 self.init_inspector()
484 self.init_inspector()
486 # init_readline() must come before init_io(), because init_io uses
485 # init_readline() must come before init_io(), because init_io uses
487 # readline related things.
486 # readline related things.
488 self.init_readline()
487 self.init_readline()
489 # We save this here in case user code replaces raw_input, but it needs
488 # We save this here in case user code replaces raw_input, but it needs
490 # to be after init_readline(), because PyPy's readline works by replacing
489 # to be after init_readline(), because PyPy's readline works by replacing
491 # raw_input.
490 # raw_input.
492 if py3compat.PY3:
491 if py3compat.PY3:
493 self.raw_input_original = input
492 self.raw_input_original = input
494 else:
493 else:
495 self.raw_input_original = raw_input
494 self.raw_input_original = raw_input
496 # init_completer must come after init_readline, because it needs to
495 # init_completer must come after init_readline, because it needs to
497 # know whether readline is present or not system-wide to configure the
496 # know whether readline is present or not system-wide to configure the
498 # completers, since the completion machinery can now operate
497 # completers, since the completion machinery can now operate
499 # independently of readline (e.g. over the network)
498 # independently of readline (e.g. over the network)
500 self.init_completer()
499 self.init_completer()
501 # TODO: init_io() needs to happen before init_traceback handlers
500 # TODO: init_io() needs to happen before init_traceback handlers
502 # because the traceback handlers hardcode the stdout/stderr streams.
501 # because the traceback handlers hardcode the stdout/stderr streams.
503 # This logic in in debugger.Pdb and should eventually be changed.
502 # This logic in in debugger.Pdb and should eventually be changed.
504 self.init_io()
503 self.init_io()
505 self.init_traceback_handlers(custom_exceptions)
504 self.init_traceback_handlers(custom_exceptions)
506 self.init_prompts()
505 self.init_prompts()
507 self.init_display_formatter()
506 self.init_display_formatter()
508 self.init_display_pub()
507 self.init_display_pub()
509 self.init_data_pub()
508 self.init_data_pub()
510 self.init_displayhook()
509 self.init_displayhook()
511 self.init_magics()
510 self.init_magics()
512 self.init_alias()
511 self.init_alias()
513 self.init_logstart()
512 self.init_logstart()
514 self.init_pdb()
513 self.init_pdb()
515 self.init_extension_manager()
514 self.init_extension_manager()
516 self.init_payload()
515 self.init_payload()
517 self.init_deprecation_warnings()
516 self.init_deprecation_warnings()
518 self.hooks.late_startup_hook()
517 self.hooks.late_startup_hook()
519 self.events.trigger('shell_initialized', self)
518 self.events.trigger('shell_initialized', self)
520 atexit.register(self.atexit_operations)
519 atexit.register(self.atexit_operations)
521
520
522 def get_ipython(self):
521 def get_ipython(self):
523 """Return the currently running IPython instance."""
522 """Return the currently running IPython instance."""
524 return self
523 return self
525
524
526 #-------------------------------------------------------------------------
525 #-------------------------------------------------------------------------
527 # Trait changed handlers
526 # Trait changed handlers
528 #-------------------------------------------------------------------------
527 #-------------------------------------------------------------------------
529 @observe('ipython_dir')
528 @observe('ipython_dir')
530 def _ipython_dir_changed(self, change):
529 def _ipython_dir_changed(self, change):
531 ensure_dir_exists(change['new'])
530 ensure_dir_exists(change['new'])
532
531
533 def set_autoindent(self,value=None):
532 def set_autoindent(self,value=None):
534 """Set the autoindent flag.
533 """Set the autoindent flag.
535
534
536 If called with no arguments, it acts as a toggle."""
535 If called with no arguments, it acts as a toggle."""
537 if value is None:
536 if value is None:
538 self.autoindent = not self.autoindent
537 self.autoindent = not self.autoindent
539 else:
538 else:
540 self.autoindent = value
539 self.autoindent = value
541
540
542 #-------------------------------------------------------------------------
541 #-------------------------------------------------------------------------
543 # init_* methods called by __init__
542 # init_* methods called by __init__
544 #-------------------------------------------------------------------------
543 #-------------------------------------------------------------------------
545
544
546 def init_ipython_dir(self, ipython_dir):
545 def init_ipython_dir(self, ipython_dir):
547 if ipython_dir is not None:
546 if ipython_dir is not None:
548 self.ipython_dir = ipython_dir
547 self.ipython_dir = ipython_dir
549 return
548 return
550
549
551 self.ipython_dir = get_ipython_dir()
550 self.ipython_dir = get_ipython_dir()
552
551
553 def init_profile_dir(self, profile_dir):
552 def init_profile_dir(self, profile_dir):
554 if profile_dir is not None:
553 if profile_dir is not None:
555 self.profile_dir = profile_dir
554 self.profile_dir = profile_dir
556 return
555 return
557 self.profile_dir =\
556 self.profile_dir =\
558 ProfileDir.create_profile_dir_by_name(self.ipython_dir, 'default')
557 ProfileDir.create_profile_dir_by_name(self.ipython_dir, 'default')
559
558
560 def init_instance_attrs(self):
559 def init_instance_attrs(self):
561 self.more = False
560 self.more = False
562
561
563 # command compiler
562 # command compiler
564 self.compile = CachingCompiler()
563 self.compile = CachingCompiler()
565
564
566 # Make an empty namespace, which extension writers can rely on both
565 # Make an empty namespace, which extension writers can rely on both
567 # existing and NEVER being used by ipython itself. This gives them a
566 # existing and NEVER being used by ipython itself. This gives them a
568 # convenient location for storing additional information and state
567 # convenient location for storing additional information and state
569 # their extensions may require, without fear of collisions with other
568 # their extensions may require, without fear of collisions with other
570 # ipython names that may develop later.
569 # ipython names that may develop later.
571 self.meta = Struct()
570 self.meta = Struct()
572
571
573 # Temporary files used for various purposes. Deleted at exit.
572 # Temporary files used for various purposes. Deleted at exit.
574 self.tempfiles = []
573 self.tempfiles = []
575 self.tempdirs = []
574 self.tempdirs = []
576
575
577 # Keep track of readline usage (later set by init_readline)
578 self.has_readline = False
579
580 # keep track of where we started running (mainly for crash post-mortem)
576 # keep track of where we started running (mainly for crash post-mortem)
581 # This is not being used anywhere currently.
577 # This is not being used anywhere currently.
582 self.starting_dir = py3compat.getcwd()
578 self.starting_dir = py3compat.getcwd()
583
579
584 # Indentation management
580 # Indentation management
585 self.indent_current_nsp = 0
581 self.indent_current_nsp = 0
586
582
587 # Dict to track post-execution functions that have been registered
583 # Dict to track post-execution functions that have been registered
588 self._post_execute = {}
584 self._post_execute = {}
589
585
590 def init_environment(self):
586 def init_environment(self):
591 """Any changes we need to make to the user's environment."""
587 """Any changes we need to make to the user's environment."""
592 pass
588 pass
593
589
594 def init_encoding(self):
590 def init_encoding(self):
595 # Get system encoding at startup time. Certain terminals (like Emacs
591 # Get system encoding at startup time. Certain terminals (like Emacs
596 # under Win32 have it set to None, and we need to have a known valid
592 # under Win32 have it set to None, and we need to have a known valid
597 # encoding to use in the raw_input() method
593 # encoding to use in the raw_input() method
598 try:
594 try:
599 self.stdin_encoding = sys.stdin.encoding or 'ascii'
595 self.stdin_encoding = sys.stdin.encoding or 'ascii'
600 except AttributeError:
596 except AttributeError:
601 self.stdin_encoding = 'ascii'
597 self.stdin_encoding = 'ascii'
602
598
603 def init_syntax_highlighting(self):
599 def init_syntax_highlighting(self):
604 # Python source parser/formatter for syntax highlighting
600 # Python source parser/formatter for syntax highlighting
605 pyformat = PyColorize.Parser().format
601 pyformat = PyColorize.Parser().format
606 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
602 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
607
603
608 def refresh_style(self):
604 def refresh_style(self):
609 # No-op here, used in subclass
605 # No-op here, used in subclass
610 pass
606 pass
611
607
612 def init_pushd_popd_magic(self):
608 def init_pushd_popd_magic(self):
613 # for pushd/popd management
609 # for pushd/popd management
614 self.home_dir = get_home_dir()
610 self.home_dir = get_home_dir()
615
611
616 self.dir_stack = []
612 self.dir_stack = []
617
613
618 def init_logger(self):
614 def init_logger(self):
619 self.logger = Logger(self.home_dir, logfname='ipython_log.py',
615 self.logger = Logger(self.home_dir, logfname='ipython_log.py',
620 logmode='rotate')
616 logmode='rotate')
621
617
622 def init_logstart(self):
618 def init_logstart(self):
623 """Initialize logging in case it was requested at the command line.
619 """Initialize logging in case it was requested at the command line.
624 """
620 """
625 if self.logappend:
621 if self.logappend:
626 self.magic('logstart %s append' % self.logappend)
622 self.magic('logstart %s append' % self.logappend)
627 elif self.logfile:
623 elif self.logfile:
628 self.magic('logstart %s' % self.logfile)
624 self.magic('logstart %s' % self.logfile)
629 elif self.logstart:
625 elif self.logstart:
630 self.magic('logstart')
626 self.magic('logstart')
631
627
632 def init_deprecation_warnings(self):
628 def init_deprecation_warnings(self):
633 """
629 """
634 register default filter for deprecation warning.
630 register default filter for deprecation warning.
635
631
636 This will allow deprecation warning of function used interactively to show
632 This will allow deprecation warning of function used interactively to show
637 warning to users, and still hide deprecation warning from libraries import.
633 warning to users, and still hide deprecation warning from libraries import.
638 """
634 """
639 warnings.filterwarnings("default", category=DeprecationWarning, module=self.user_ns.get("__name__"))
635 warnings.filterwarnings("default", category=DeprecationWarning, module=self.user_ns.get("__name__"))
640
636
641 def init_builtins(self):
637 def init_builtins(self):
642 # A single, static flag that we set to True. Its presence indicates
638 # A single, static flag that we set to True. Its presence indicates
643 # that an IPython shell has been created, and we make no attempts at
639 # that an IPython shell has been created, and we make no attempts at
644 # removing on exit or representing the existence of more than one
640 # removing on exit or representing the existence of more than one
645 # IPython at a time.
641 # IPython at a time.
646 builtin_mod.__dict__['__IPYTHON__'] = True
642 builtin_mod.__dict__['__IPYTHON__'] = True
647
643
648 self.builtin_trap = BuiltinTrap(shell=self)
644 self.builtin_trap = BuiltinTrap(shell=self)
649
645
650 def init_inspector(self):
646 def init_inspector(self):
651 # Object inspector
647 # Object inspector
652 self.inspector = oinspect.Inspector(oinspect.InspectColors,
648 self.inspector = oinspect.Inspector(oinspect.InspectColors,
653 PyColorize.ANSICodeColors,
649 PyColorize.ANSICodeColors,
654 'NoColor',
650 'NoColor',
655 self.object_info_string_level)
651 self.object_info_string_level)
656
652
657 def init_io(self):
653 def init_io(self):
658 # This will just use sys.stdout and sys.stderr. If you want to
654 # This will just use sys.stdout and sys.stderr. If you want to
659 # override sys.stdout and sys.stderr themselves, you need to do that
655 # override sys.stdout and sys.stderr themselves, you need to do that
660 # *before* instantiating this class, because io holds onto
656 # *before* instantiating this class, because io holds onto
661 # references to the underlying streams.
657 # references to the underlying streams.
662 if (sys.platform == 'win32' or sys.platform == 'cli') and self.has_readline:
658 io.stdout = io.IOStream(sys.stdout)
663 io.stdout = io.stderr = io.IOStream(self.readline._outputfile)
659 io.stderr = io.IOStream(sys.stderr)
664 else:
665 io.stdout = io.IOStream(sys.stdout)
666 io.stderr = io.IOStream(sys.stderr)
667
660
668 def init_prompts(self):
661 def init_prompts(self):
669 # Set system prompts, so that scripts can decide if they are running
662 # Set system prompts, so that scripts can decide if they are running
670 # interactively.
663 # interactively.
671 sys.ps1 = 'In : '
664 sys.ps1 = 'In : '
672 sys.ps2 = '...: '
665 sys.ps2 = '...: '
673 sys.ps3 = 'Out: '
666 sys.ps3 = 'Out: '
674
667
675 def init_display_formatter(self):
668 def init_display_formatter(self):
676 self.display_formatter = DisplayFormatter(parent=self)
669 self.display_formatter = DisplayFormatter(parent=self)
677 self.configurables.append(self.display_formatter)
670 self.configurables.append(self.display_formatter)
678
671
679 def init_display_pub(self):
672 def init_display_pub(self):
680 self.display_pub = self.display_pub_class(parent=self)
673 self.display_pub = self.display_pub_class(parent=self)
681 self.configurables.append(self.display_pub)
674 self.configurables.append(self.display_pub)
682
675
683 def init_data_pub(self):
676 def init_data_pub(self):
684 if not self.data_pub_class:
677 if not self.data_pub_class:
685 self.data_pub = None
678 self.data_pub = None
686 return
679 return
687 self.data_pub = self.data_pub_class(parent=self)
680 self.data_pub = self.data_pub_class(parent=self)
688 self.configurables.append(self.data_pub)
681 self.configurables.append(self.data_pub)
689
682
690 def init_displayhook(self):
683 def init_displayhook(self):
691 # Initialize displayhook, set in/out prompts and printing system
684 # Initialize displayhook, set in/out prompts and printing system
692 self.displayhook = self.displayhook_class(
685 self.displayhook = self.displayhook_class(
693 parent=self,
686 parent=self,
694 shell=self,
687 shell=self,
695 cache_size=self.cache_size,
688 cache_size=self.cache_size,
696 )
689 )
697 self.configurables.append(self.displayhook)
690 self.configurables.append(self.displayhook)
698 # This is a context manager that installs/revmoes the displayhook at
691 # This is a context manager that installs/revmoes the displayhook at
699 # the appropriate time.
692 # the appropriate time.
700 self.display_trap = DisplayTrap(hook=self.displayhook)
693 self.display_trap = DisplayTrap(hook=self.displayhook)
701
694
702 def init_virtualenv(self):
695 def init_virtualenv(self):
703 """Add a virtualenv to sys.path so the user can import modules from it.
696 """Add a virtualenv to sys.path so the user can import modules from it.
704 This isn't perfect: it doesn't use the Python interpreter with which the
697 This isn't perfect: it doesn't use the Python interpreter with which the
705 virtualenv was built, and it ignores the --no-site-packages option. A
698 virtualenv was built, and it ignores the --no-site-packages option. A
706 warning will appear suggesting the user installs IPython in the
699 warning will appear suggesting the user installs IPython in the
707 virtualenv, but for many cases, it probably works well enough.
700 virtualenv, but for many cases, it probably works well enough.
708
701
709 Adapted from code snippets online.
702 Adapted from code snippets online.
710
703
711 http://blog.ufsoft.org/2009/1/29/ipython-and-virtualenv
704 http://blog.ufsoft.org/2009/1/29/ipython-and-virtualenv
712 """
705 """
713 if 'VIRTUAL_ENV' not in os.environ:
706 if 'VIRTUAL_ENV' not in os.environ:
714 # Not in a virtualenv
707 # Not in a virtualenv
715 return
708 return
716
709
717 # venv detection:
710 # venv detection:
718 # stdlib venv may symlink sys.executable, so we can't use realpath.
711 # stdlib venv may symlink sys.executable, so we can't use realpath.
719 # but others can symlink *to* the venv Python, so we can't just use sys.executable.
712 # but others can symlink *to* the venv Python, so we can't just use sys.executable.
720 # So we just check every item in the symlink tree (generally <= 3)
713 # So we just check every item in the symlink tree (generally <= 3)
721 p = os.path.normcase(sys.executable)
714 p = os.path.normcase(sys.executable)
722 paths = [p]
715 paths = [p]
723 while os.path.islink(p):
716 while os.path.islink(p):
724 p = os.path.normcase(os.path.join(os.path.dirname(p), os.readlink(p)))
717 p = os.path.normcase(os.path.join(os.path.dirname(p), os.readlink(p)))
725 paths.append(p)
718 paths.append(p)
726 p_venv = os.path.normcase(os.environ['VIRTUAL_ENV'])
719 p_venv = os.path.normcase(os.environ['VIRTUAL_ENV'])
727 if any(p.startswith(p_venv) for p in paths):
720 if any(p.startswith(p_venv) for p in paths):
728 # Running properly in the virtualenv, don't need to do anything
721 # Running properly in the virtualenv, don't need to do anything
729 return
722 return
730
723
731 warn("Attempting to work in a virtualenv. If you encounter problems, please "
724 warn("Attempting to work in a virtualenv. If you encounter problems, please "
732 "install IPython inside the virtualenv.")
725 "install IPython inside the virtualenv.")
733 if sys.platform == "win32":
726 if sys.platform == "win32":
734 virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'Lib', 'site-packages')
727 virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'Lib', 'site-packages')
735 else:
728 else:
736 virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'lib',
729 virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'lib',
737 'python%d.%d' % sys.version_info[:2], 'site-packages')
730 'python%d.%d' % sys.version_info[:2], 'site-packages')
738
731
739 import site
732 import site
740 sys.path.insert(0, virtual_env)
733 sys.path.insert(0, virtual_env)
741 site.addsitedir(virtual_env)
734 site.addsitedir(virtual_env)
742
735
743 #-------------------------------------------------------------------------
736 #-------------------------------------------------------------------------
744 # Things related to injections into the sys module
737 # Things related to injections into the sys module
745 #-------------------------------------------------------------------------
738 #-------------------------------------------------------------------------
746
739
747 def save_sys_module_state(self):
740 def save_sys_module_state(self):
748 """Save the state of hooks in the sys module.
741 """Save the state of hooks in the sys module.
749
742
750 This has to be called after self.user_module is created.
743 This has to be called after self.user_module is created.
751 """
744 """
752 self._orig_sys_module_state = {'stdin': sys.stdin,
745 self._orig_sys_module_state = {'stdin': sys.stdin,
753 'stdout': sys.stdout,
746 'stdout': sys.stdout,
754 'stderr': sys.stderr,
747 'stderr': sys.stderr,
755 'excepthook': sys.excepthook}
748 'excepthook': sys.excepthook}
756 self._orig_sys_modules_main_name = self.user_module.__name__
749 self._orig_sys_modules_main_name = self.user_module.__name__
757 self._orig_sys_modules_main_mod = sys.modules.get(self.user_module.__name__)
750 self._orig_sys_modules_main_mod = sys.modules.get(self.user_module.__name__)
758
751
759 def restore_sys_module_state(self):
752 def restore_sys_module_state(self):
760 """Restore the state of the sys module."""
753 """Restore the state of the sys module."""
761 try:
754 try:
762 for k, v in iteritems(self._orig_sys_module_state):
755 for k, v in iteritems(self._orig_sys_module_state):
763 setattr(sys, k, v)
756 setattr(sys, k, v)
764 except AttributeError:
757 except AttributeError:
765 pass
758 pass
766 # Reset what what done in self.init_sys_modules
759 # Reset what what done in self.init_sys_modules
767 if self._orig_sys_modules_main_mod is not None:
760 if self._orig_sys_modules_main_mod is not None:
768 sys.modules[self._orig_sys_modules_main_name] = self._orig_sys_modules_main_mod
761 sys.modules[self._orig_sys_modules_main_name] = self._orig_sys_modules_main_mod
769
762
770 #-------------------------------------------------------------------------
763 #-------------------------------------------------------------------------
771 # Things related to the banner
764 # Things related to the banner
772 #-------------------------------------------------------------------------
765 #-------------------------------------------------------------------------
773
766
774 @property
767 @property
775 def banner(self):
768 def banner(self):
776 banner = self.banner1
769 banner = self.banner1
777 if self.profile and self.profile != 'default':
770 if self.profile and self.profile != 'default':
778 banner += '\nIPython profile: %s\n' % self.profile
771 banner += '\nIPython profile: %s\n' % self.profile
779 if self.banner2:
772 if self.banner2:
780 banner += '\n' + self.banner2
773 banner += '\n' + self.banner2
781 return banner
774 return banner
782
775
783 def show_banner(self, banner=None):
776 def show_banner(self, banner=None):
784 if banner is None:
777 if banner is None:
785 banner = self.banner
778 banner = self.banner
786 sys.stdout.write(banner)
779 sys.stdout.write(banner)
787
780
788 #-------------------------------------------------------------------------
781 #-------------------------------------------------------------------------
789 # Things related to hooks
782 # Things related to hooks
790 #-------------------------------------------------------------------------
783 #-------------------------------------------------------------------------
791
784
792 def init_hooks(self):
785 def init_hooks(self):
793 # hooks holds pointers used for user-side customizations
786 # hooks holds pointers used for user-side customizations
794 self.hooks = Struct()
787 self.hooks = Struct()
795
788
796 self.strdispatchers = {}
789 self.strdispatchers = {}
797
790
798 # Set all default hooks, defined in the IPython.hooks module.
791 # Set all default hooks, defined in the IPython.hooks module.
799 hooks = IPython.core.hooks
792 hooks = IPython.core.hooks
800 for hook_name in hooks.__all__:
793 for hook_name in hooks.__all__:
801 # default hooks have priority 100, i.e. low; user hooks should have
794 # default hooks have priority 100, i.e. low; user hooks should have
802 # 0-100 priority
795 # 0-100 priority
803 self.set_hook(hook_name,getattr(hooks,hook_name), 100, _warn_deprecated=False)
796 self.set_hook(hook_name,getattr(hooks,hook_name), 100, _warn_deprecated=False)
804
797
805 if self.display_page:
798 if self.display_page:
806 self.set_hook('show_in_pager', page.as_hook(page.display_page), 90)
799 self.set_hook('show_in_pager', page.as_hook(page.display_page), 90)
807
800
808 def set_hook(self,name,hook, priority=50, str_key=None, re_key=None,
801 def set_hook(self,name,hook, priority=50, str_key=None, re_key=None,
809 _warn_deprecated=True):
802 _warn_deprecated=True):
810 """set_hook(name,hook) -> sets an internal IPython hook.
803 """set_hook(name,hook) -> sets an internal IPython hook.
811
804
812 IPython exposes some of its internal API as user-modifiable hooks. By
805 IPython exposes some of its internal API as user-modifiable hooks. By
813 adding your function to one of these hooks, you can modify IPython's
806 adding your function to one of these hooks, you can modify IPython's
814 behavior to call at runtime your own routines."""
807 behavior to call at runtime your own routines."""
815
808
816 # At some point in the future, this should validate the hook before it
809 # At some point in the future, this should validate the hook before it
817 # accepts it. Probably at least check that the hook takes the number
810 # accepts it. Probably at least check that the hook takes the number
818 # of args it's supposed to.
811 # of args it's supposed to.
819
812
820 f = types.MethodType(hook,self)
813 f = types.MethodType(hook,self)
821
814
822 # check if the hook is for strdispatcher first
815 # check if the hook is for strdispatcher first
823 if str_key is not None:
816 if str_key is not None:
824 sdp = self.strdispatchers.get(name, StrDispatch())
817 sdp = self.strdispatchers.get(name, StrDispatch())
825 sdp.add_s(str_key, f, priority )
818 sdp.add_s(str_key, f, priority )
826 self.strdispatchers[name] = sdp
819 self.strdispatchers[name] = sdp
827 return
820 return
828 if re_key is not None:
821 if re_key is not None:
829 sdp = self.strdispatchers.get(name, StrDispatch())
822 sdp = self.strdispatchers.get(name, StrDispatch())
830 sdp.add_re(re.compile(re_key), f, priority )
823 sdp.add_re(re.compile(re_key), f, priority )
831 self.strdispatchers[name] = sdp
824 self.strdispatchers[name] = sdp
832 return
825 return
833
826
834 dp = getattr(self.hooks, name, None)
827 dp = getattr(self.hooks, name, None)
835 if name not in IPython.core.hooks.__all__:
828 if name not in IPython.core.hooks.__all__:
836 print("Warning! Hook '%s' is not one of %s" % \
829 print("Warning! Hook '%s' is not one of %s" % \
837 (name, IPython.core.hooks.__all__ ))
830 (name, IPython.core.hooks.__all__ ))
838
831
839 if _warn_deprecated and (name in IPython.core.hooks.deprecated):
832 if _warn_deprecated and (name in IPython.core.hooks.deprecated):
840 alternative = IPython.core.hooks.deprecated[name]
833 alternative = IPython.core.hooks.deprecated[name]
841 warn("Hook {} is deprecated. Use {} instead.".format(name, alternative))
834 warn("Hook {} is deprecated. Use {} instead.".format(name, alternative))
842
835
843 if not dp:
836 if not dp:
844 dp = IPython.core.hooks.CommandChainDispatcher()
837 dp = IPython.core.hooks.CommandChainDispatcher()
845
838
846 try:
839 try:
847 dp.add(f,priority)
840 dp.add(f,priority)
848 except AttributeError:
841 except AttributeError:
849 # it was not commandchain, plain old func - replace
842 # it was not commandchain, plain old func - replace
850 dp = f
843 dp = f
851
844
852 setattr(self.hooks,name, dp)
845 setattr(self.hooks,name, dp)
853
846
854 #-------------------------------------------------------------------------
847 #-------------------------------------------------------------------------
855 # Things related to events
848 # Things related to events
856 #-------------------------------------------------------------------------
849 #-------------------------------------------------------------------------
857
850
858 def init_events(self):
851 def init_events(self):
859 self.events = EventManager(self, available_events)
852 self.events = EventManager(self, available_events)
860
853
861 self.events.register("pre_execute", self._clear_warning_registry)
854 self.events.register("pre_execute", self._clear_warning_registry)
862
855
863 def register_post_execute(self, func):
856 def register_post_execute(self, func):
864 """DEPRECATED: Use ip.events.register('post_run_cell', func)
857 """DEPRECATED: Use ip.events.register('post_run_cell', func)
865
858
866 Register a function for calling after code execution.
859 Register a function for calling after code execution.
867 """
860 """
868 warn("ip.register_post_execute is deprecated, use "
861 warn("ip.register_post_execute is deprecated, use "
869 "ip.events.register('post_run_cell', func) instead.")
862 "ip.events.register('post_run_cell', func) instead.")
870 self.events.register('post_run_cell', func)
863 self.events.register('post_run_cell', func)
871
864
872 def _clear_warning_registry(self):
865 def _clear_warning_registry(self):
873 # clear the warning registry, so that different code blocks with
866 # clear the warning registry, so that different code blocks with
874 # overlapping line number ranges don't cause spurious suppression of
867 # overlapping line number ranges don't cause spurious suppression of
875 # warnings (see gh-6611 for details)
868 # warnings (see gh-6611 for details)
876 if "__warningregistry__" in self.user_global_ns:
869 if "__warningregistry__" in self.user_global_ns:
877 del self.user_global_ns["__warningregistry__"]
870 del self.user_global_ns["__warningregistry__"]
878
871
879 #-------------------------------------------------------------------------
872 #-------------------------------------------------------------------------
880 # Things related to the "main" module
873 # Things related to the "main" module
881 #-------------------------------------------------------------------------
874 #-------------------------------------------------------------------------
882
875
883 def new_main_mod(self, filename, modname):
876 def new_main_mod(self, filename, modname):
884 """Return a new 'main' module object for user code execution.
877 """Return a new 'main' module object for user code execution.
885
878
886 ``filename`` should be the path of the script which will be run in the
879 ``filename`` should be the path of the script which will be run in the
887 module. Requests with the same filename will get the same module, with
880 module. Requests with the same filename will get the same module, with
888 its namespace cleared.
881 its namespace cleared.
889
882
890 ``modname`` should be the module name - normally either '__main__' or
883 ``modname`` should be the module name - normally either '__main__' or
891 the basename of the file without the extension.
884 the basename of the file without the extension.
892
885
893 When scripts are executed via %run, we must keep a reference to their
886 When scripts are executed via %run, we must keep a reference to their
894 __main__ module around so that Python doesn't
887 __main__ module around so that Python doesn't
895 clear it, rendering references to module globals useless.
888 clear it, rendering references to module globals useless.
896
889
897 This method keeps said reference in a private dict, keyed by the
890 This method keeps said reference in a private dict, keyed by the
898 absolute path of the script. This way, for multiple executions of the
891 absolute path of the script. This way, for multiple executions of the
899 same script we only keep one copy of the namespace (the last one),
892 same script we only keep one copy of the namespace (the last one),
900 thus preventing memory leaks from old references while allowing the
893 thus preventing memory leaks from old references while allowing the
901 objects from the last execution to be accessible.
894 objects from the last execution to be accessible.
902 """
895 """
903 filename = os.path.abspath(filename)
896 filename = os.path.abspath(filename)
904 try:
897 try:
905 main_mod = self._main_mod_cache[filename]
898 main_mod = self._main_mod_cache[filename]
906 except KeyError:
899 except KeyError:
907 main_mod = self._main_mod_cache[filename] = types.ModuleType(
900 main_mod = self._main_mod_cache[filename] = types.ModuleType(
908 py3compat.cast_bytes_py2(modname),
901 py3compat.cast_bytes_py2(modname),
909 doc="Module created for script run in IPython")
902 doc="Module created for script run in IPython")
910 else:
903 else:
911 main_mod.__dict__.clear()
904 main_mod.__dict__.clear()
912 main_mod.__name__ = modname
905 main_mod.__name__ = modname
913
906
914 main_mod.__file__ = filename
907 main_mod.__file__ = filename
915 # It seems pydoc (and perhaps others) needs any module instance to
908 # It seems pydoc (and perhaps others) needs any module instance to
916 # implement a __nonzero__ method
909 # implement a __nonzero__ method
917 main_mod.__nonzero__ = lambda : True
910 main_mod.__nonzero__ = lambda : True
918
911
919 return main_mod
912 return main_mod
920
913
921 def clear_main_mod_cache(self):
914 def clear_main_mod_cache(self):
922 """Clear the cache of main modules.
915 """Clear the cache of main modules.
923
916
924 Mainly for use by utilities like %reset.
917 Mainly for use by utilities like %reset.
925
918
926 Examples
919 Examples
927 --------
920 --------
928
921
929 In [15]: import IPython
922 In [15]: import IPython
930
923
931 In [16]: m = _ip.new_main_mod(IPython.__file__, 'IPython')
924 In [16]: m = _ip.new_main_mod(IPython.__file__, 'IPython')
932
925
933 In [17]: len(_ip._main_mod_cache) > 0
926 In [17]: len(_ip._main_mod_cache) > 0
934 Out[17]: True
927 Out[17]: True
935
928
936 In [18]: _ip.clear_main_mod_cache()
929 In [18]: _ip.clear_main_mod_cache()
937
930
938 In [19]: len(_ip._main_mod_cache) == 0
931 In [19]: len(_ip._main_mod_cache) == 0
939 Out[19]: True
932 Out[19]: True
940 """
933 """
941 self._main_mod_cache.clear()
934 self._main_mod_cache.clear()
942
935
943 #-------------------------------------------------------------------------
936 #-------------------------------------------------------------------------
944 # Things related to debugging
937 # Things related to debugging
945 #-------------------------------------------------------------------------
938 #-------------------------------------------------------------------------
946
939
947 def init_pdb(self):
940 def init_pdb(self):
948 # Set calling of pdb on exceptions
941 # Set calling of pdb on exceptions
949 # self.call_pdb is a property
942 # self.call_pdb is a property
950 self.call_pdb = self.pdb
943 self.call_pdb = self.pdb
951
944
952 def _get_call_pdb(self):
945 def _get_call_pdb(self):
953 return self._call_pdb
946 return self._call_pdb
954
947
955 def _set_call_pdb(self,val):
948 def _set_call_pdb(self,val):
956
949
957 if val not in (0,1,False,True):
950 if val not in (0,1,False,True):
958 raise ValueError('new call_pdb value must be boolean')
951 raise ValueError('new call_pdb value must be boolean')
959
952
960 # store value in instance
953 # store value in instance
961 self._call_pdb = val
954 self._call_pdb = val
962
955
963 # notify the actual exception handlers
956 # notify the actual exception handlers
964 self.InteractiveTB.call_pdb = val
957 self.InteractiveTB.call_pdb = val
965
958
966 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
959 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
967 'Control auto-activation of pdb at exceptions')
960 'Control auto-activation of pdb at exceptions')
968
961
969 def debugger(self,force=False):
962 def debugger(self,force=False):
970 """Call the pdb debugger.
963 """Call the pdb debugger.
971
964
972 Keywords:
965 Keywords:
973
966
974 - force(False): by default, this routine checks the instance call_pdb
967 - force(False): by default, this routine checks the instance call_pdb
975 flag and does not actually invoke the debugger if the flag is false.
968 flag and does not actually invoke the debugger if the flag is false.
976 The 'force' option forces the debugger to activate even if the flag
969 The 'force' option forces the debugger to activate even if the flag
977 is false.
970 is false.
978 """
971 """
979
972
980 if not (force or self.call_pdb):
973 if not (force or self.call_pdb):
981 return
974 return
982
975
983 if not hasattr(sys,'last_traceback'):
976 if not hasattr(sys,'last_traceback'):
984 error('No traceback has been produced, nothing to debug.')
977 error('No traceback has been produced, nothing to debug.')
985 return
978 return
986
979
987
980 self.InteractiveTB.debugger(force=True)
988 with self.readline_no_record:
989 self.InteractiveTB.debugger(force=True)
990
981
991 #-------------------------------------------------------------------------
982 #-------------------------------------------------------------------------
992 # Things related to IPython's various namespaces
983 # Things related to IPython's various namespaces
993 #-------------------------------------------------------------------------
984 #-------------------------------------------------------------------------
994 default_user_namespaces = True
985 default_user_namespaces = True
995
986
996 def init_create_namespaces(self, user_module=None, user_ns=None):
987 def init_create_namespaces(self, user_module=None, user_ns=None):
997 # Create the namespace where the user will operate. user_ns is
988 # Create the namespace where the user will operate. user_ns is
998 # normally the only one used, and it is passed to the exec calls as
989 # normally the only one used, and it is passed to the exec calls as
999 # the locals argument. But we do carry a user_global_ns namespace
990 # the locals argument. But we do carry a user_global_ns namespace
1000 # given as the exec 'globals' argument, This is useful in embedding
991 # given as the exec 'globals' argument, This is useful in embedding
1001 # situations where the ipython shell opens in a context where the
992 # situations where the ipython shell opens in a context where the
1002 # distinction between locals and globals is meaningful. For
993 # distinction between locals and globals is meaningful. For
1003 # non-embedded contexts, it is just the same object as the user_ns dict.
994 # non-embedded contexts, it is just the same object as the user_ns dict.
1004
995
1005 # FIXME. For some strange reason, __builtins__ is showing up at user
996 # FIXME. For some strange reason, __builtins__ is showing up at user
1006 # level as a dict instead of a module. This is a manual fix, but I
997 # level as a dict instead of a module. This is a manual fix, but I
1007 # should really track down where the problem is coming from. Alex
998 # should really track down where the problem is coming from. Alex
1008 # Schmolck reported this problem first.
999 # Schmolck reported this problem first.
1009
1000
1010 # A useful post by Alex Martelli on this topic:
1001 # A useful post by Alex Martelli on this topic:
1011 # Re: inconsistent value from __builtins__
1002 # Re: inconsistent value from __builtins__
1012 # Von: Alex Martelli <aleaxit@yahoo.com>
1003 # Von: Alex Martelli <aleaxit@yahoo.com>
1013 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
1004 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
1014 # Gruppen: comp.lang.python
1005 # Gruppen: comp.lang.python
1015
1006
1016 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
1007 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
1017 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
1008 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
1018 # > <type 'dict'>
1009 # > <type 'dict'>
1019 # > >>> print type(__builtins__)
1010 # > >>> print type(__builtins__)
1020 # > <type 'module'>
1011 # > <type 'module'>
1021 # > Is this difference in return value intentional?
1012 # > Is this difference in return value intentional?
1022
1013
1023 # Well, it's documented that '__builtins__' can be either a dictionary
1014 # Well, it's documented that '__builtins__' can be either a dictionary
1024 # or a module, and it's been that way for a long time. Whether it's
1015 # or a module, and it's been that way for a long time. Whether it's
1025 # intentional (or sensible), I don't know. In any case, the idea is
1016 # intentional (or sensible), I don't know. In any case, the idea is
1026 # that if you need to access the built-in namespace directly, you
1017 # that if you need to access the built-in namespace directly, you
1027 # should start with "import __builtin__" (note, no 's') which will
1018 # should start with "import __builtin__" (note, no 's') which will
1028 # definitely give you a module. Yeah, it's somewhat confusing:-(.
1019 # definitely give you a module. Yeah, it's somewhat confusing:-(.
1029
1020
1030 # These routines return a properly built module and dict as needed by
1021 # These routines return a properly built module and dict as needed by
1031 # the rest of the code, and can also be used by extension writers to
1022 # the rest of the code, and can also be used by extension writers to
1032 # generate properly initialized namespaces.
1023 # generate properly initialized namespaces.
1033 if (user_ns is not None) or (user_module is not None):
1024 if (user_ns is not None) or (user_module is not None):
1034 self.default_user_namespaces = False
1025 self.default_user_namespaces = False
1035 self.user_module, self.user_ns = self.prepare_user_module(user_module, user_ns)
1026 self.user_module, self.user_ns = self.prepare_user_module(user_module, user_ns)
1036
1027
1037 # A record of hidden variables we have added to the user namespace, so
1028 # A record of hidden variables we have added to the user namespace, so
1038 # we can list later only variables defined in actual interactive use.
1029 # we can list later only variables defined in actual interactive use.
1039 self.user_ns_hidden = {}
1030 self.user_ns_hidden = {}
1040
1031
1041 # Now that FakeModule produces a real module, we've run into a nasty
1032 # Now that FakeModule produces a real module, we've run into a nasty
1042 # problem: after script execution (via %run), the module where the user
1033 # problem: after script execution (via %run), the module where the user
1043 # code ran is deleted. Now that this object is a true module (needed
1034 # code ran is deleted. Now that this object is a true module (needed
1044 # so doctest and other tools work correctly), the Python module
1035 # so doctest and other tools work correctly), the Python module
1045 # teardown mechanism runs over it, and sets to None every variable
1036 # teardown mechanism runs over it, and sets to None every variable
1046 # present in that module. Top-level references to objects from the
1037 # present in that module. Top-level references to objects from the
1047 # script survive, because the user_ns is updated with them. However,
1038 # script survive, because the user_ns is updated with them. However,
1048 # calling functions defined in the script that use other things from
1039 # calling functions defined in the script that use other things from
1049 # the script will fail, because the function's closure had references
1040 # the script will fail, because the function's closure had references
1050 # to the original objects, which are now all None. So we must protect
1041 # to the original objects, which are now all None. So we must protect
1051 # these modules from deletion by keeping a cache.
1042 # these modules from deletion by keeping a cache.
1052 #
1043 #
1053 # To avoid keeping stale modules around (we only need the one from the
1044 # To avoid keeping stale modules around (we only need the one from the
1054 # last run), we use a dict keyed with the full path to the script, so
1045 # last run), we use a dict keyed with the full path to the script, so
1055 # only the last version of the module is held in the cache. Note,
1046 # only the last version of the module is held in the cache. Note,
1056 # however, that we must cache the module *namespace contents* (their
1047 # however, that we must cache the module *namespace contents* (their
1057 # __dict__). Because if we try to cache the actual modules, old ones
1048 # __dict__). Because if we try to cache the actual modules, old ones
1058 # (uncached) could be destroyed while still holding references (such as
1049 # (uncached) could be destroyed while still holding references (such as
1059 # those held by GUI objects that tend to be long-lived)>
1050 # those held by GUI objects that tend to be long-lived)>
1060 #
1051 #
1061 # The %reset command will flush this cache. See the cache_main_mod()
1052 # The %reset command will flush this cache. See the cache_main_mod()
1062 # and clear_main_mod_cache() methods for details on use.
1053 # and clear_main_mod_cache() methods for details on use.
1063
1054
1064 # This is the cache used for 'main' namespaces
1055 # This is the cache used for 'main' namespaces
1065 self._main_mod_cache = {}
1056 self._main_mod_cache = {}
1066
1057
1067 # A table holding all the namespaces IPython deals with, so that
1058 # A table holding all the namespaces IPython deals with, so that
1068 # introspection facilities can search easily.
1059 # introspection facilities can search easily.
1069 self.ns_table = {'user_global':self.user_module.__dict__,
1060 self.ns_table = {'user_global':self.user_module.__dict__,
1070 'user_local':self.user_ns,
1061 'user_local':self.user_ns,
1071 'builtin':builtin_mod.__dict__
1062 'builtin':builtin_mod.__dict__
1072 }
1063 }
1073
1064
1074 @property
1065 @property
1075 def user_global_ns(self):
1066 def user_global_ns(self):
1076 return self.user_module.__dict__
1067 return self.user_module.__dict__
1077
1068
1078 def prepare_user_module(self, user_module=None, user_ns=None):
1069 def prepare_user_module(self, user_module=None, user_ns=None):
1079 """Prepare the module and namespace in which user code will be run.
1070 """Prepare the module and namespace in which user code will be run.
1080
1071
1081 When IPython is started normally, both parameters are None: a new module
1072 When IPython is started normally, both parameters are None: a new module
1082 is created automatically, and its __dict__ used as the namespace.
1073 is created automatically, and its __dict__ used as the namespace.
1083
1074
1084 If only user_module is provided, its __dict__ is used as the namespace.
1075 If only user_module is provided, its __dict__ is used as the namespace.
1085 If only user_ns is provided, a dummy module is created, and user_ns
1076 If only user_ns is provided, a dummy module is created, and user_ns
1086 becomes the global namespace. If both are provided (as they may be
1077 becomes the global namespace. If both are provided (as they may be
1087 when embedding), user_ns is the local namespace, and user_module
1078 when embedding), user_ns is the local namespace, and user_module
1088 provides the global namespace.
1079 provides the global namespace.
1089
1080
1090 Parameters
1081 Parameters
1091 ----------
1082 ----------
1092 user_module : module, optional
1083 user_module : module, optional
1093 The current user module in which IPython is being run. If None,
1084 The current user module in which IPython is being run. If None,
1094 a clean module will be created.
1085 a clean module will be created.
1095 user_ns : dict, optional
1086 user_ns : dict, optional
1096 A namespace in which to run interactive commands.
1087 A namespace in which to run interactive commands.
1097
1088
1098 Returns
1089 Returns
1099 -------
1090 -------
1100 A tuple of user_module and user_ns, each properly initialised.
1091 A tuple of user_module and user_ns, each properly initialised.
1101 """
1092 """
1102 if user_module is None and user_ns is not None:
1093 if user_module is None and user_ns is not None:
1103 user_ns.setdefault("__name__", "__main__")
1094 user_ns.setdefault("__name__", "__main__")
1104 user_module = DummyMod()
1095 user_module = DummyMod()
1105 user_module.__dict__ = user_ns
1096 user_module.__dict__ = user_ns
1106
1097
1107 if user_module is None:
1098 if user_module is None:
1108 user_module = types.ModuleType("__main__",
1099 user_module = types.ModuleType("__main__",
1109 doc="Automatically created module for IPython interactive environment")
1100 doc="Automatically created module for IPython interactive environment")
1110
1101
1111 # We must ensure that __builtin__ (without the final 's') is always
1102 # We must ensure that __builtin__ (without the final 's') is always
1112 # available and pointing to the __builtin__ *module*. For more details:
1103 # available and pointing to the __builtin__ *module*. For more details:
1113 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1104 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1114 user_module.__dict__.setdefault('__builtin__', builtin_mod)
1105 user_module.__dict__.setdefault('__builtin__', builtin_mod)
1115 user_module.__dict__.setdefault('__builtins__', builtin_mod)
1106 user_module.__dict__.setdefault('__builtins__', builtin_mod)
1116
1107
1117 if user_ns is None:
1108 if user_ns is None:
1118 user_ns = user_module.__dict__
1109 user_ns = user_module.__dict__
1119
1110
1120 return user_module, user_ns
1111 return user_module, user_ns
1121
1112
1122 def init_sys_modules(self):
1113 def init_sys_modules(self):
1123 # We need to insert into sys.modules something that looks like a
1114 # We need to insert into sys.modules something that looks like a
1124 # module but which accesses the IPython namespace, for shelve and
1115 # module but which accesses the IPython namespace, for shelve and
1125 # pickle to work interactively. Normally they rely on getting
1116 # pickle to work interactively. Normally they rely on getting
1126 # everything out of __main__, but for embedding purposes each IPython
1117 # everything out of __main__, but for embedding purposes each IPython
1127 # instance has its own private namespace, so we can't go shoving
1118 # instance has its own private namespace, so we can't go shoving
1128 # everything into __main__.
1119 # everything into __main__.
1129
1120
1130 # note, however, that we should only do this for non-embedded
1121 # note, however, that we should only do this for non-embedded
1131 # ipythons, which really mimic the __main__.__dict__ with their own
1122 # ipythons, which really mimic the __main__.__dict__ with their own
1132 # namespace. Embedded instances, on the other hand, should not do
1123 # namespace. Embedded instances, on the other hand, should not do
1133 # this because they need to manage the user local/global namespaces
1124 # this because they need to manage the user local/global namespaces
1134 # only, but they live within a 'normal' __main__ (meaning, they
1125 # only, but they live within a 'normal' __main__ (meaning, they
1135 # shouldn't overtake the execution environment of the script they're
1126 # shouldn't overtake the execution environment of the script they're
1136 # embedded in).
1127 # embedded in).
1137
1128
1138 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
1129 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
1139 main_name = self.user_module.__name__
1130 main_name = self.user_module.__name__
1140 sys.modules[main_name] = self.user_module
1131 sys.modules[main_name] = self.user_module
1141
1132
1142 def init_user_ns(self):
1133 def init_user_ns(self):
1143 """Initialize all user-visible namespaces to their minimum defaults.
1134 """Initialize all user-visible namespaces to their minimum defaults.
1144
1135
1145 Certain history lists are also initialized here, as they effectively
1136 Certain history lists are also initialized here, as they effectively
1146 act as user namespaces.
1137 act as user namespaces.
1147
1138
1148 Notes
1139 Notes
1149 -----
1140 -----
1150 All data structures here are only filled in, they are NOT reset by this
1141 All data structures here are only filled in, they are NOT reset by this
1151 method. If they were not empty before, data will simply be added to
1142 method. If they were not empty before, data will simply be added to
1152 therm.
1143 therm.
1153 """
1144 """
1154 # This function works in two parts: first we put a few things in
1145 # This function works in two parts: first we put a few things in
1155 # user_ns, and we sync that contents into user_ns_hidden so that these
1146 # user_ns, and we sync that contents into user_ns_hidden so that these
1156 # initial variables aren't shown by %who. After the sync, we add the
1147 # initial variables aren't shown by %who. After the sync, we add the
1157 # rest of what we *do* want the user to see with %who even on a new
1148 # rest of what we *do* want the user to see with %who even on a new
1158 # session (probably nothing, so they really only see their own stuff)
1149 # session (probably nothing, so they really only see their own stuff)
1159
1150
1160 # The user dict must *always* have a __builtin__ reference to the
1151 # The user dict must *always* have a __builtin__ reference to the
1161 # Python standard __builtin__ namespace, which must be imported.
1152 # Python standard __builtin__ namespace, which must be imported.
1162 # This is so that certain operations in prompt evaluation can be
1153 # This is so that certain operations in prompt evaluation can be
1163 # reliably executed with builtins. Note that we can NOT use
1154 # reliably executed with builtins. Note that we can NOT use
1164 # __builtins__ (note the 's'), because that can either be a dict or a
1155 # __builtins__ (note the 's'), because that can either be a dict or a
1165 # module, and can even mutate at runtime, depending on the context
1156 # module, and can even mutate at runtime, depending on the context
1166 # (Python makes no guarantees on it). In contrast, __builtin__ is
1157 # (Python makes no guarantees on it). In contrast, __builtin__ is
1167 # always a module object, though it must be explicitly imported.
1158 # always a module object, though it must be explicitly imported.
1168
1159
1169 # For more details:
1160 # For more details:
1170 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1161 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1171 ns = dict()
1162 ns = dict()
1172
1163
1173 # make global variables for user access to the histories
1164 # make global variables for user access to the histories
1174 ns['_ih'] = self.history_manager.input_hist_parsed
1165 ns['_ih'] = self.history_manager.input_hist_parsed
1175 ns['_oh'] = self.history_manager.output_hist
1166 ns['_oh'] = self.history_manager.output_hist
1176 ns['_dh'] = self.history_manager.dir_hist
1167 ns['_dh'] = self.history_manager.dir_hist
1177
1168
1178 ns['_sh'] = shadowns
1169 ns['_sh'] = shadowns
1179
1170
1180 # user aliases to input and output histories. These shouldn't show up
1171 # user aliases to input and output histories. These shouldn't show up
1181 # in %who, as they can have very large reprs.
1172 # in %who, as they can have very large reprs.
1182 ns['In'] = self.history_manager.input_hist_parsed
1173 ns['In'] = self.history_manager.input_hist_parsed
1183 ns['Out'] = self.history_manager.output_hist
1174 ns['Out'] = self.history_manager.output_hist
1184
1175
1185 # Store myself as the public api!!!
1176 # Store myself as the public api!!!
1186 ns['get_ipython'] = self.get_ipython
1177 ns['get_ipython'] = self.get_ipython
1187
1178
1188 ns['exit'] = self.exiter
1179 ns['exit'] = self.exiter
1189 ns['quit'] = self.exiter
1180 ns['quit'] = self.exiter
1190
1181
1191 # Sync what we've added so far to user_ns_hidden so these aren't seen
1182 # Sync what we've added so far to user_ns_hidden so these aren't seen
1192 # by %who
1183 # by %who
1193 self.user_ns_hidden.update(ns)
1184 self.user_ns_hidden.update(ns)
1194
1185
1195 # Anything put into ns now would show up in %who. Think twice before
1186 # Anything put into ns now would show up in %who. Think twice before
1196 # putting anything here, as we really want %who to show the user their
1187 # putting anything here, as we really want %who to show the user their
1197 # stuff, not our variables.
1188 # stuff, not our variables.
1198
1189
1199 # Finally, update the real user's namespace
1190 # Finally, update the real user's namespace
1200 self.user_ns.update(ns)
1191 self.user_ns.update(ns)
1201
1192
1202 @property
1193 @property
1203 def all_ns_refs(self):
1194 def all_ns_refs(self):
1204 """Get a list of references to all the namespace dictionaries in which
1195 """Get a list of references to all the namespace dictionaries in which
1205 IPython might store a user-created object.
1196 IPython might store a user-created object.
1206
1197
1207 Note that this does not include the displayhook, which also caches
1198 Note that this does not include the displayhook, which also caches
1208 objects from the output."""
1199 objects from the output."""
1209 return [self.user_ns, self.user_global_ns, self.user_ns_hidden] + \
1200 return [self.user_ns, self.user_global_ns, self.user_ns_hidden] + \
1210 [m.__dict__ for m in self._main_mod_cache.values()]
1201 [m.__dict__ for m in self._main_mod_cache.values()]
1211
1202
1212 def reset(self, new_session=True):
1203 def reset(self, new_session=True):
1213 """Clear all internal namespaces, and attempt to release references to
1204 """Clear all internal namespaces, and attempt to release references to
1214 user objects.
1205 user objects.
1215
1206
1216 If new_session is True, a new history session will be opened.
1207 If new_session is True, a new history session will be opened.
1217 """
1208 """
1218 # Clear histories
1209 # Clear histories
1219 self.history_manager.reset(new_session)
1210 self.history_manager.reset(new_session)
1220 # Reset counter used to index all histories
1211 # Reset counter used to index all histories
1221 if new_session:
1212 if new_session:
1222 self.execution_count = 1
1213 self.execution_count = 1
1223
1214
1224 # Flush cached output items
1215 # Flush cached output items
1225 if self.displayhook.do_full_cache:
1216 if self.displayhook.do_full_cache:
1226 self.displayhook.flush()
1217 self.displayhook.flush()
1227
1218
1228 # The main execution namespaces must be cleared very carefully,
1219 # The main execution namespaces must be cleared very carefully,
1229 # skipping the deletion of the builtin-related keys, because doing so
1220 # skipping the deletion of the builtin-related keys, because doing so
1230 # would cause errors in many object's __del__ methods.
1221 # would cause errors in many object's __del__ methods.
1231 if self.user_ns is not self.user_global_ns:
1222 if self.user_ns is not self.user_global_ns:
1232 self.user_ns.clear()
1223 self.user_ns.clear()
1233 ns = self.user_global_ns
1224 ns = self.user_global_ns
1234 drop_keys = set(ns.keys())
1225 drop_keys = set(ns.keys())
1235 drop_keys.discard('__builtin__')
1226 drop_keys.discard('__builtin__')
1236 drop_keys.discard('__builtins__')
1227 drop_keys.discard('__builtins__')
1237 drop_keys.discard('__name__')
1228 drop_keys.discard('__name__')
1238 for k in drop_keys:
1229 for k in drop_keys:
1239 del ns[k]
1230 del ns[k]
1240
1231
1241 self.user_ns_hidden.clear()
1232 self.user_ns_hidden.clear()
1242
1233
1243 # Restore the user namespaces to minimal usability
1234 # Restore the user namespaces to minimal usability
1244 self.init_user_ns()
1235 self.init_user_ns()
1245
1236
1246 # Restore the default and user aliases
1237 # Restore the default and user aliases
1247 self.alias_manager.clear_aliases()
1238 self.alias_manager.clear_aliases()
1248 self.alias_manager.init_aliases()
1239 self.alias_manager.init_aliases()
1249
1240
1250 # Flush the private list of module references kept for script
1241 # Flush the private list of module references kept for script
1251 # execution protection
1242 # execution protection
1252 self.clear_main_mod_cache()
1243 self.clear_main_mod_cache()
1253
1244
1254 def del_var(self, varname, by_name=False):
1245 def del_var(self, varname, by_name=False):
1255 """Delete a variable from the various namespaces, so that, as
1246 """Delete a variable from the various namespaces, so that, as
1256 far as possible, we're not keeping any hidden references to it.
1247 far as possible, we're not keeping any hidden references to it.
1257
1248
1258 Parameters
1249 Parameters
1259 ----------
1250 ----------
1260 varname : str
1251 varname : str
1261 The name of the variable to delete.
1252 The name of the variable to delete.
1262 by_name : bool
1253 by_name : bool
1263 If True, delete variables with the given name in each
1254 If True, delete variables with the given name in each
1264 namespace. If False (default), find the variable in the user
1255 namespace. If False (default), find the variable in the user
1265 namespace, and delete references to it.
1256 namespace, and delete references to it.
1266 """
1257 """
1267 if varname in ('__builtin__', '__builtins__'):
1258 if varname in ('__builtin__', '__builtins__'):
1268 raise ValueError("Refusing to delete %s" % varname)
1259 raise ValueError("Refusing to delete %s" % varname)
1269
1260
1270 ns_refs = self.all_ns_refs
1261 ns_refs = self.all_ns_refs
1271
1262
1272 if by_name: # Delete by name
1263 if by_name: # Delete by name
1273 for ns in ns_refs:
1264 for ns in ns_refs:
1274 try:
1265 try:
1275 del ns[varname]
1266 del ns[varname]
1276 except KeyError:
1267 except KeyError:
1277 pass
1268 pass
1278 else: # Delete by object
1269 else: # Delete by object
1279 try:
1270 try:
1280 obj = self.user_ns[varname]
1271 obj = self.user_ns[varname]
1281 except KeyError:
1272 except KeyError:
1282 raise NameError("name '%s' is not defined" % varname)
1273 raise NameError("name '%s' is not defined" % varname)
1283 # Also check in output history
1274 # Also check in output history
1284 ns_refs.append(self.history_manager.output_hist)
1275 ns_refs.append(self.history_manager.output_hist)
1285 for ns in ns_refs:
1276 for ns in ns_refs:
1286 to_delete = [n for n, o in iteritems(ns) if o is obj]
1277 to_delete = [n for n, o in iteritems(ns) if o is obj]
1287 for name in to_delete:
1278 for name in to_delete:
1288 del ns[name]
1279 del ns[name]
1289
1280
1290 # displayhook keeps extra references, but not in a dictionary
1281 # displayhook keeps extra references, but not in a dictionary
1291 for name in ('_', '__', '___'):
1282 for name in ('_', '__', '___'):
1292 if getattr(self.displayhook, name) is obj:
1283 if getattr(self.displayhook, name) is obj:
1293 setattr(self.displayhook, name, None)
1284 setattr(self.displayhook, name, None)
1294
1285
1295 def reset_selective(self, regex=None):
1286 def reset_selective(self, regex=None):
1296 """Clear selective variables from internal namespaces based on a
1287 """Clear selective variables from internal namespaces based on a
1297 specified regular expression.
1288 specified regular expression.
1298
1289
1299 Parameters
1290 Parameters
1300 ----------
1291 ----------
1301 regex : string or compiled pattern, optional
1292 regex : string or compiled pattern, optional
1302 A regular expression pattern that will be used in searching
1293 A regular expression pattern that will be used in searching
1303 variable names in the users namespaces.
1294 variable names in the users namespaces.
1304 """
1295 """
1305 if regex is not None:
1296 if regex is not None:
1306 try:
1297 try:
1307 m = re.compile(regex)
1298 m = re.compile(regex)
1308 except TypeError:
1299 except TypeError:
1309 raise TypeError('regex must be a string or compiled pattern')
1300 raise TypeError('regex must be a string or compiled pattern')
1310 # Search for keys in each namespace that match the given regex
1301 # Search for keys in each namespace that match the given regex
1311 # If a match is found, delete the key/value pair.
1302 # If a match is found, delete the key/value pair.
1312 for ns in self.all_ns_refs:
1303 for ns in self.all_ns_refs:
1313 for var in ns:
1304 for var in ns:
1314 if m.search(var):
1305 if m.search(var):
1315 del ns[var]
1306 del ns[var]
1316
1307
1317 def push(self, variables, interactive=True):
1308 def push(self, variables, interactive=True):
1318 """Inject a group of variables into the IPython user namespace.
1309 """Inject a group of variables into the IPython user namespace.
1319
1310
1320 Parameters
1311 Parameters
1321 ----------
1312 ----------
1322 variables : dict, str or list/tuple of str
1313 variables : dict, str or list/tuple of str
1323 The variables to inject into the user's namespace. If a dict, a
1314 The variables to inject into the user's namespace. If a dict, a
1324 simple update is done. If a str, the string is assumed to have
1315 simple update is done. If a str, the string is assumed to have
1325 variable names separated by spaces. A list/tuple of str can also
1316 variable names separated by spaces. A list/tuple of str can also
1326 be used to give the variable names. If just the variable names are
1317 be used to give the variable names. If just the variable names are
1327 give (list/tuple/str) then the variable values looked up in the
1318 give (list/tuple/str) then the variable values looked up in the
1328 callers frame.
1319 callers frame.
1329 interactive : bool
1320 interactive : bool
1330 If True (default), the variables will be listed with the ``who``
1321 If True (default), the variables will be listed with the ``who``
1331 magic.
1322 magic.
1332 """
1323 """
1333 vdict = None
1324 vdict = None
1334
1325
1335 # We need a dict of name/value pairs to do namespace updates.
1326 # We need a dict of name/value pairs to do namespace updates.
1336 if isinstance(variables, dict):
1327 if isinstance(variables, dict):
1337 vdict = variables
1328 vdict = variables
1338 elif isinstance(variables, string_types+(list, tuple)):
1329 elif isinstance(variables, string_types+(list, tuple)):
1339 if isinstance(variables, string_types):
1330 if isinstance(variables, string_types):
1340 vlist = variables.split()
1331 vlist = variables.split()
1341 else:
1332 else:
1342 vlist = variables
1333 vlist = variables
1343 vdict = {}
1334 vdict = {}
1344 cf = sys._getframe(1)
1335 cf = sys._getframe(1)
1345 for name in vlist:
1336 for name in vlist:
1346 try:
1337 try:
1347 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1338 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1348 except:
1339 except:
1349 print('Could not get variable %s from %s' %
1340 print('Could not get variable %s from %s' %
1350 (name,cf.f_code.co_name))
1341 (name,cf.f_code.co_name))
1351 else:
1342 else:
1352 raise ValueError('variables must be a dict/str/list/tuple')
1343 raise ValueError('variables must be a dict/str/list/tuple')
1353
1344
1354 # Propagate variables to user namespace
1345 # Propagate variables to user namespace
1355 self.user_ns.update(vdict)
1346 self.user_ns.update(vdict)
1356
1347
1357 # And configure interactive visibility
1348 # And configure interactive visibility
1358 user_ns_hidden = self.user_ns_hidden
1349 user_ns_hidden = self.user_ns_hidden
1359 if interactive:
1350 if interactive:
1360 for name in vdict:
1351 for name in vdict:
1361 user_ns_hidden.pop(name, None)
1352 user_ns_hidden.pop(name, None)
1362 else:
1353 else:
1363 user_ns_hidden.update(vdict)
1354 user_ns_hidden.update(vdict)
1364
1355
1365 def drop_by_id(self, variables):
1356 def drop_by_id(self, variables):
1366 """Remove a dict of variables from the user namespace, if they are the
1357 """Remove a dict of variables from the user namespace, if they are the
1367 same as the values in the dictionary.
1358 same as the values in the dictionary.
1368
1359
1369 This is intended for use by extensions: variables that they've added can
1360 This is intended for use by extensions: variables that they've added can
1370 be taken back out if they are unloaded, without removing any that the
1361 be taken back out if they are unloaded, without removing any that the
1371 user has overwritten.
1362 user has overwritten.
1372
1363
1373 Parameters
1364 Parameters
1374 ----------
1365 ----------
1375 variables : dict
1366 variables : dict
1376 A dictionary mapping object names (as strings) to the objects.
1367 A dictionary mapping object names (as strings) to the objects.
1377 """
1368 """
1378 for name, obj in iteritems(variables):
1369 for name, obj in iteritems(variables):
1379 if name in self.user_ns and self.user_ns[name] is obj:
1370 if name in self.user_ns and self.user_ns[name] is obj:
1380 del self.user_ns[name]
1371 del self.user_ns[name]
1381 self.user_ns_hidden.pop(name, None)
1372 self.user_ns_hidden.pop(name, None)
1382
1373
1383 #-------------------------------------------------------------------------
1374 #-------------------------------------------------------------------------
1384 # Things related to object introspection
1375 # Things related to object introspection
1385 #-------------------------------------------------------------------------
1376 #-------------------------------------------------------------------------
1386
1377
1387 def _ofind(self, oname, namespaces=None):
1378 def _ofind(self, oname, namespaces=None):
1388 """Find an object in the available namespaces.
1379 """Find an object in the available namespaces.
1389
1380
1390 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
1381 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
1391
1382
1392 Has special code to detect magic functions.
1383 Has special code to detect magic functions.
1393 """
1384 """
1394 oname = oname.strip()
1385 oname = oname.strip()
1395 #print '1- oname: <%r>' % oname # dbg
1386 #print '1- oname: <%r>' % oname # dbg
1396 if not oname.startswith(ESC_MAGIC) and \
1387 if not oname.startswith(ESC_MAGIC) and \
1397 not oname.startswith(ESC_MAGIC2) and \
1388 not oname.startswith(ESC_MAGIC2) and \
1398 not py3compat.isidentifier(oname, dotted=True):
1389 not py3compat.isidentifier(oname, dotted=True):
1399 return dict(found=False)
1390 return dict(found=False)
1400
1391
1401 if namespaces is None:
1392 if namespaces is None:
1402 # Namespaces to search in:
1393 # Namespaces to search in:
1403 # Put them in a list. The order is important so that we
1394 # Put them in a list. The order is important so that we
1404 # find things in the same order that Python finds them.
1395 # find things in the same order that Python finds them.
1405 namespaces = [ ('Interactive', self.user_ns),
1396 namespaces = [ ('Interactive', self.user_ns),
1406 ('Interactive (global)', self.user_global_ns),
1397 ('Interactive (global)', self.user_global_ns),
1407 ('Python builtin', builtin_mod.__dict__),
1398 ('Python builtin', builtin_mod.__dict__),
1408 ]
1399 ]
1409
1400
1410 # initialize results to 'null'
1401 # initialize results to 'null'
1411 found = False; obj = None; ospace = None;
1402 found = False; obj = None; ospace = None;
1412 ismagic = False; isalias = False; parent = None
1403 ismagic = False; isalias = False; parent = None
1413
1404
1414 # We need to special-case 'print', which as of python2.6 registers as a
1405 # We need to special-case 'print', which as of python2.6 registers as a
1415 # function but should only be treated as one if print_function was
1406 # function but should only be treated as one if print_function was
1416 # loaded with a future import. In this case, just bail.
1407 # loaded with a future import. In this case, just bail.
1417 if (oname == 'print' and not py3compat.PY3 and not \
1408 if (oname == 'print' and not py3compat.PY3 and not \
1418 (self.compile.compiler_flags & __future__.CO_FUTURE_PRINT_FUNCTION)):
1409 (self.compile.compiler_flags & __future__.CO_FUTURE_PRINT_FUNCTION)):
1419 return {'found':found, 'obj':obj, 'namespace':ospace,
1410 return {'found':found, 'obj':obj, 'namespace':ospace,
1420 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1411 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1421
1412
1422 # Look for the given name by splitting it in parts. If the head is
1413 # Look for the given name by splitting it in parts. If the head is
1423 # found, then we look for all the remaining parts as members, and only
1414 # found, then we look for all the remaining parts as members, and only
1424 # declare success if we can find them all.
1415 # declare success if we can find them all.
1425 oname_parts = oname.split('.')
1416 oname_parts = oname.split('.')
1426 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
1417 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
1427 for nsname,ns in namespaces:
1418 for nsname,ns in namespaces:
1428 try:
1419 try:
1429 obj = ns[oname_head]
1420 obj = ns[oname_head]
1430 except KeyError:
1421 except KeyError:
1431 continue
1422 continue
1432 else:
1423 else:
1433 #print 'oname_rest:', oname_rest # dbg
1424 #print 'oname_rest:', oname_rest # dbg
1434 for idx, part in enumerate(oname_rest):
1425 for idx, part in enumerate(oname_rest):
1435 try:
1426 try:
1436 parent = obj
1427 parent = obj
1437 # The last part is looked up in a special way to avoid
1428 # The last part is looked up in a special way to avoid
1438 # descriptor invocation as it may raise or have side
1429 # descriptor invocation as it may raise or have side
1439 # effects.
1430 # effects.
1440 if idx == len(oname_rest) - 1:
1431 if idx == len(oname_rest) - 1:
1441 obj = self._getattr_property(obj, part)
1432 obj = self._getattr_property(obj, part)
1442 else:
1433 else:
1443 obj = getattr(obj, part)
1434 obj = getattr(obj, part)
1444 except:
1435 except:
1445 # Blanket except b/c some badly implemented objects
1436 # Blanket except b/c some badly implemented objects
1446 # allow __getattr__ to raise exceptions other than
1437 # allow __getattr__ to raise exceptions other than
1447 # AttributeError, which then crashes IPython.
1438 # AttributeError, which then crashes IPython.
1448 break
1439 break
1449 else:
1440 else:
1450 # If we finish the for loop (no break), we got all members
1441 # If we finish the for loop (no break), we got all members
1451 found = True
1442 found = True
1452 ospace = nsname
1443 ospace = nsname
1453 break # namespace loop
1444 break # namespace loop
1454
1445
1455 # Try to see if it's magic
1446 # Try to see if it's magic
1456 if not found:
1447 if not found:
1457 obj = None
1448 obj = None
1458 if oname.startswith(ESC_MAGIC2):
1449 if oname.startswith(ESC_MAGIC2):
1459 oname = oname.lstrip(ESC_MAGIC2)
1450 oname = oname.lstrip(ESC_MAGIC2)
1460 obj = self.find_cell_magic(oname)
1451 obj = self.find_cell_magic(oname)
1461 elif oname.startswith(ESC_MAGIC):
1452 elif oname.startswith(ESC_MAGIC):
1462 oname = oname.lstrip(ESC_MAGIC)
1453 oname = oname.lstrip(ESC_MAGIC)
1463 obj = self.find_line_magic(oname)
1454 obj = self.find_line_magic(oname)
1464 else:
1455 else:
1465 # search without prefix, so run? will find %run?
1456 # search without prefix, so run? will find %run?
1466 obj = self.find_line_magic(oname)
1457 obj = self.find_line_magic(oname)
1467 if obj is None:
1458 if obj is None:
1468 obj = self.find_cell_magic(oname)
1459 obj = self.find_cell_magic(oname)
1469 if obj is not None:
1460 if obj is not None:
1470 found = True
1461 found = True
1471 ospace = 'IPython internal'
1462 ospace = 'IPython internal'
1472 ismagic = True
1463 ismagic = True
1473 isalias = isinstance(obj, Alias)
1464 isalias = isinstance(obj, Alias)
1474
1465
1475 # Last try: special-case some literals like '', [], {}, etc:
1466 # Last try: special-case some literals like '', [], {}, etc:
1476 if not found and oname_head in ["''",'""','[]','{}','()']:
1467 if not found and oname_head in ["''",'""','[]','{}','()']:
1477 obj = eval(oname_head)
1468 obj = eval(oname_head)
1478 found = True
1469 found = True
1479 ospace = 'Interactive'
1470 ospace = 'Interactive'
1480
1471
1481 return {'found':found, 'obj':obj, 'namespace':ospace,
1472 return {'found':found, 'obj':obj, 'namespace':ospace,
1482 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1473 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1483
1474
1484 @staticmethod
1475 @staticmethod
1485 def _getattr_property(obj, attrname):
1476 def _getattr_property(obj, attrname):
1486 """Property-aware getattr to use in object finding.
1477 """Property-aware getattr to use in object finding.
1487
1478
1488 If attrname represents a property, return it unevaluated (in case it has
1479 If attrname represents a property, return it unevaluated (in case it has
1489 side effects or raises an error.
1480 side effects or raises an error.
1490
1481
1491 """
1482 """
1492 if not isinstance(obj, type):
1483 if not isinstance(obj, type):
1493 try:
1484 try:
1494 # `getattr(type(obj), attrname)` is not guaranteed to return
1485 # `getattr(type(obj), attrname)` is not guaranteed to return
1495 # `obj`, but does so for property:
1486 # `obj`, but does so for property:
1496 #
1487 #
1497 # property.__get__(self, None, cls) -> self
1488 # property.__get__(self, None, cls) -> self
1498 #
1489 #
1499 # The universal alternative is to traverse the mro manually
1490 # The universal alternative is to traverse the mro manually
1500 # searching for attrname in class dicts.
1491 # searching for attrname in class dicts.
1501 attr = getattr(type(obj), attrname)
1492 attr = getattr(type(obj), attrname)
1502 except AttributeError:
1493 except AttributeError:
1503 pass
1494 pass
1504 else:
1495 else:
1505 # This relies on the fact that data descriptors (with both
1496 # This relies on the fact that data descriptors (with both
1506 # __get__ & __set__ magic methods) take precedence over
1497 # __get__ & __set__ magic methods) take precedence over
1507 # instance-level attributes:
1498 # instance-level attributes:
1508 #
1499 #
1509 # class A(object):
1500 # class A(object):
1510 # @property
1501 # @property
1511 # def foobar(self): return 123
1502 # def foobar(self): return 123
1512 # a = A()
1503 # a = A()
1513 # a.__dict__['foobar'] = 345
1504 # a.__dict__['foobar'] = 345
1514 # a.foobar # == 123
1505 # a.foobar # == 123
1515 #
1506 #
1516 # So, a property may be returned right away.
1507 # So, a property may be returned right away.
1517 if isinstance(attr, property):
1508 if isinstance(attr, property):
1518 return attr
1509 return attr
1519
1510
1520 # Nothing helped, fall back.
1511 # Nothing helped, fall back.
1521 return getattr(obj, attrname)
1512 return getattr(obj, attrname)
1522
1513
1523 def _object_find(self, oname, namespaces=None):
1514 def _object_find(self, oname, namespaces=None):
1524 """Find an object and return a struct with info about it."""
1515 """Find an object and return a struct with info about it."""
1525 return Struct(self._ofind(oname, namespaces))
1516 return Struct(self._ofind(oname, namespaces))
1526
1517
1527 def _inspect(self, meth, oname, namespaces=None, **kw):
1518 def _inspect(self, meth, oname, namespaces=None, **kw):
1528 """Generic interface to the inspector system.
1519 """Generic interface to the inspector system.
1529
1520
1530 This function is meant to be called by pdef, pdoc & friends.
1521 This function is meant to be called by pdef, pdoc & friends.
1531 """
1522 """
1532 info = self._object_find(oname, namespaces)
1523 info = self._object_find(oname, namespaces)
1533 docformat = sphinxify if self.sphinxify_docstring else None
1524 docformat = sphinxify if self.sphinxify_docstring else None
1534 if info.found:
1525 if info.found:
1535 pmethod = getattr(self.inspector, meth)
1526 pmethod = getattr(self.inspector, meth)
1536 # TODO: only apply format_screen to the plain/text repr of the mime
1527 # TODO: only apply format_screen to the plain/text repr of the mime
1537 # bundle.
1528 # bundle.
1538 formatter = format_screen if info.ismagic else docformat
1529 formatter = format_screen if info.ismagic else docformat
1539 if meth == 'pdoc':
1530 if meth == 'pdoc':
1540 pmethod(info.obj, oname, formatter)
1531 pmethod(info.obj, oname, formatter)
1541 elif meth == 'pinfo':
1532 elif meth == 'pinfo':
1542 pmethod(info.obj, oname, formatter, info,
1533 pmethod(info.obj, oname, formatter, info,
1543 enable_html_pager=self.enable_html_pager, **kw)
1534 enable_html_pager=self.enable_html_pager, **kw)
1544 else:
1535 else:
1545 pmethod(info.obj, oname)
1536 pmethod(info.obj, oname)
1546 else:
1537 else:
1547 print('Object `%s` not found.' % oname)
1538 print('Object `%s` not found.' % oname)
1548 return 'not found' # so callers can take other action
1539 return 'not found' # so callers can take other action
1549
1540
1550 def object_inspect(self, oname, detail_level=0):
1541 def object_inspect(self, oname, detail_level=0):
1551 """Get object info about oname"""
1542 """Get object info about oname"""
1552 with self.builtin_trap:
1543 with self.builtin_trap:
1553 info = self._object_find(oname)
1544 info = self._object_find(oname)
1554 if info.found:
1545 if info.found:
1555 return self.inspector.info(info.obj, oname, info=info,
1546 return self.inspector.info(info.obj, oname, info=info,
1556 detail_level=detail_level
1547 detail_level=detail_level
1557 )
1548 )
1558 else:
1549 else:
1559 return oinspect.object_info(name=oname, found=False)
1550 return oinspect.object_info(name=oname, found=False)
1560
1551
1561 def object_inspect_text(self, oname, detail_level=0):
1552 def object_inspect_text(self, oname, detail_level=0):
1562 """Get object info as formatted text"""
1553 """Get object info as formatted text"""
1563 return self.object_inspect_mime(oname, detail_level)['text/plain']
1554 return self.object_inspect_mime(oname, detail_level)['text/plain']
1564
1555
1565 def object_inspect_mime(self, oname, detail_level=0):
1556 def object_inspect_mime(self, oname, detail_level=0):
1566 """Get object info as a mimebundle of formatted representations.
1557 """Get object info as a mimebundle of formatted representations.
1567
1558
1568 A mimebundle is a dictionary, keyed by mime-type.
1559 A mimebundle is a dictionary, keyed by mime-type.
1569 It must always have the key `'text/plain'`.
1560 It must always have the key `'text/plain'`.
1570 """
1561 """
1571 with self.builtin_trap:
1562 with self.builtin_trap:
1572 info = self._object_find(oname)
1563 info = self._object_find(oname)
1573 if info.found:
1564 if info.found:
1574 return self.inspector._get_info(info.obj, oname, info=info,
1565 return self.inspector._get_info(info.obj, oname, info=info,
1575 detail_level=detail_level
1566 detail_level=detail_level
1576 )
1567 )
1577 else:
1568 else:
1578 raise KeyError(oname)
1569 raise KeyError(oname)
1579
1570
1580 #-------------------------------------------------------------------------
1571 #-------------------------------------------------------------------------
1581 # Things related to history management
1572 # Things related to history management
1582 #-------------------------------------------------------------------------
1573 #-------------------------------------------------------------------------
1583
1574
1584 def init_history(self):
1575 def init_history(self):
1585 """Sets up the command history, and starts regular autosaves."""
1576 """Sets up the command history, and starts regular autosaves."""
1586 self.history_manager = HistoryManager(shell=self, parent=self)
1577 self.history_manager = HistoryManager(shell=self, parent=self)
1587 self.configurables.append(self.history_manager)
1578 self.configurables.append(self.history_manager)
1588
1579
1589 #-------------------------------------------------------------------------
1580 #-------------------------------------------------------------------------
1590 # Things related to exception handling and tracebacks (not debugging)
1581 # Things related to exception handling and tracebacks (not debugging)
1591 #-------------------------------------------------------------------------
1582 #-------------------------------------------------------------------------
1592
1583
1593 debugger_cls = Pdb
1584 debugger_cls = Pdb
1594
1585
1595 def init_traceback_handlers(self, custom_exceptions):
1586 def init_traceback_handlers(self, custom_exceptions):
1596 # Syntax error handler.
1587 # Syntax error handler.
1597 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor')
1588 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor')
1598
1589
1599 # The interactive one is initialized with an offset, meaning we always
1590 # The interactive one is initialized with an offset, meaning we always
1600 # want to remove the topmost item in the traceback, which is our own
1591 # want to remove the topmost item in the traceback, which is our own
1601 # internal code. Valid modes: ['Plain','Context','Verbose']
1592 # internal code. Valid modes: ['Plain','Context','Verbose']
1602 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1593 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1603 color_scheme='NoColor',
1594 color_scheme='NoColor',
1604 tb_offset = 1,
1595 tb_offset = 1,
1605 check_cache=check_linecache_ipython,
1596 check_cache=check_linecache_ipython,
1606 debugger_cls=self.debugger_cls)
1597 debugger_cls=self.debugger_cls)
1607
1598
1608 # The instance will store a pointer to the system-wide exception hook,
1599 # The instance will store a pointer to the system-wide exception hook,
1609 # so that runtime code (such as magics) can access it. This is because
1600 # so that runtime code (such as magics) can access it. This is because
1610 # during the read-eval loop, it may get temporarily overwritten.
1601 # during the read-eval loop, it may get temporarily overwritten.
1611 self.sys_excepthook = sys.excepthook
1602 self.sys_excepthook = sys.excepthook
1612
1603
1613 # and add any custom exception handlers the user may have specified
1604 # and add any custom exception handlers the user may have specified
1614 self.set_custom_exc(*custom_exceptions)
1605 self.set_custom_exc(*custom_exceptions)
1615
1606
1616 # Set the exception mode
1607 # Set the exception mode
1617 self.InteractiveTB.set_mode(mode=self.xmode)
1608 self.InteractiveTB.set_mode(mode=self.xmode)
1618
1609
1619 def set_custom_exc(self, exc_tuple, handler):
1610 def set_custom_exc(self, exc_tuple, handler):
1620 """set_custom_exc(exc_tuple, handler)
1611 """set_custom_exc(exc_tuple, handler)
1621
1612
1622 Set a custom exception handler, which will be called if any of the
1613 Set a custom exception handler, which will be called if any of the
1623 exceptions in exc_tuple occur in the mainloop (specifically, in the
1614 exceptions in exc_tuple occur in the mainloop (specifically, in the
1624 run_code() method).
1615 run_code() method).
1625
1616
1626 Parameters
1617 Parameters
1627 ----------
1618 ----------
1628
1619
1629 exc_tuple : tuple of exception classes
1620 exc_tuple : tuple of exception classes
1630 A *tuple* of exception classes, for which to call the defined
1621 A *tuple* of exception classes, for which to call the defined
1631 handler. It is very important that you use a tuple, and NOT A
1622 handler. It is very important that you use a tuple, and NOT A
1632 LIST here, because of the way Python's except statement works. If
1623 LIST here, because of the way Python's except statement works. If
1633 you only want to trap a single exception, use a singleton tuple::
1624 you only want to trap a single exception, use a singleton tuple::
1634
1625
1635 exc_tuple == (MyCustomException,)
1626 exc_tuple == (MyCustomException,)
1636
1627
1637 handler : callable
1628 handler : callable
1638 handler must have the following signature::
1629 handler must have the following signature::
1639
1630
1640 def my_handler(self, etype, value, tb, tb_offset=None):
1631 def my_handler(self, etype, value, tb, tb_offset=None):
1641 ...
1632 ...
1642 return structured_traceback
1633 return structured_traceback
1643
1634
1644 Your handler must return a structured traceback (a list of strings),
1635 Your handler must return a structured traceback (a list of strings),
1645 or None.
1636 or None.
1646
1637
1647 This will be made into an instance method (via types.MethodType)
1638 This will be made into an instance method (via types.MethodType)
1648 of IPython itself, and it will be called if any of the exceptions
1639 of IPython itself, and it will be called if any of the exceptions
1649 listed in the exc_tuple are caught. If the handler is None, an
1640 listed in the exc_tuple are caught. If the handler is None, an
1650 internal basic one is used, which just prints basic info.
1641 internal basic one is used, which just prints basic info.
1651
1642
1652 To protect IPython from crashes, if your handler ever raises an
1643 To protect IPython from crashes, if your handler ever raises an
1653 exception or returns an invalid result, it will be immediately
1644 exception or returns an invalid result, it will be immediately
1654 disabled.
1645 disabled.
1655
1646
1656 WARNING: by putting in your own exception handler into IPython's main
1647 WARNING: by putting in your own exception handler into IPython's main
1657 execution loop, you run a very good chance of nasty crashes. This
1648 execution loop, you run a very good chance of nasty crashes. This
1658 facility should only be used if you really know what you are doing."""
1649 facility should only be used if you really know what you are doing."""
1659
1650
1660 assert type(exc_tuple)==type(()) , \
1651 assert type(exc_tuple)==type(()) , \
1661 "The custom exceptions must be given AS A TUPLE."
1652 "The custom exceptions must be given AS A TUPLE."
1662
1653
1663 def dummy_handler(self, etype, value, tb, tb_offset=None):
1654 def dummy_handler(self, etype, value, tb, tb_offset=None):
1664 print('*** Simple custom exception handler ***')
1655 print('*** Simple custom exception handler ***')
1665 print('Exception type :',etype)
1656 print('Exception type :',etype)
1666 print('Exception value:',value)
1657 print('Exception value:',value)
1667 print('Traceback :',tb)
1658 print('Traceback :',tb)
1668 #print 'Source code :','\n'.join(self.buffer)
1659 #print 'Source code :','\n'.join(self.buffer)
1669
1660
1670 def validate_stb(stb):
1661 def validate_stb(stb):
1671 """validate structured traceback return type
1662 """validate structured traceback return type
1672
1663
1673 return type of CustomTB *should* be a list of strings, but allow
1664 return type of CustomTB *should* be a list of strings, but allow
1674 single strings or None, which are harmless.
1665 single strings or None, which are harmless.
1675
1666
1676 This function will *always* return a list of strings,
1667 This function will *always* return a list of strings,
1677 and will raise a TypeError if stb is inappropriate.
1668 and will raise a TypeError if stb is inappropriate.
1678 """
1669 """
1679 msg = "CustomTB must return list of strings, not %r" % stb
1670 msg = "CustomTB must return list of strings, not %r" % stb
1680 if stb is None:
1671 if stb is None:
1681 return []
1672 return []
1682 elif isinstance(stb, string_types):
1673 elif isinstance(stb, string_types):
1683 return [stb]
1674 return [stb]
1684 elif not isinstance(stb, list):
1675 elif not isinstance(stb, list):
1685 raise TypeError(msg)
1676 raise TypeError(msg)
1686 # it's a list
1677 # it's a list
1687 for line in stb:
1678 for line in stb:
1688 # check every element
1679 # check every element
1689 if not isinstance(line, string_types):
1680 if not isinstance(line, string_types):
1690 raise TypeError(msg)
1681 raise TypeError(msg)
1691 return stb
1682 return stb
1692
1683
1693 if handler is None:
1684 if handler is None:
1694 wrapped = dummy_handler
1685 wrapped = dummy_handler
1695 else:
1686 else:
1696 def wrapped(self,etype,value,tb,tb_offset=None):
1687 def wrapped(self,etype,value,tb,tb_offset=None):
1697 """wrap CustomTB handler, to protect IPython from user code
1688 """wrap CustomTB handler, to protect IPython from user code
1698
1689
1699 This makes it harder (but not impossible) for custom exception
1690 This makes it harder (but not impossible) for custom exception
1700 handlers to crash IPython.
1691 handlers to crash IPython.
1701 """
1692 """
1702 try:
1693 try:
1703 stb = handler(self,etype,value,tb,tb_offset=tb_offset)
1694 stb = handler(self,etype,value,tb,tb_offset=tb_offset)
1704 return validate_stb(stb)
1695 return validate_stb(stb)
1705 except:
1696 except:
1706 # clear custom handler immediately
1697 # clear custom handler immediately
1707 self.set_custom_exc((), None)
1698 self.set_custom_exc((), None)
1708 print("Custom TB Handler failed, unregistering", file=sys.stderr)
1699 print("Custom TB Handler failed, unregistering", file=sys.stderr)
1709 # show the exception in handler first
1700 # show the exception in handler first
1710 stb = self.InteractiveTB.structured_traceback(*sys.exc_info())
1701 stb = self.InteractiveTB.structured_traceback(*sys.exc_info())
1711 print(self.InteractiveTB.stb2text(stb))
1702 print(self.InteractiveTB.stb2text(stb))
1712 print("The original exception:")
1703 print("The original exception:")
1713 stb = self.InteractiveTB.structured_traceback(
1704 stb = self.InteractiveTB.structured_traceback(
1714 (etype,value,tb), tb_offset=tb_offset
1705 (etype,value,tb), tb_offset=tb_offset
1715 )
1706 )
1716 return stb
1707 return stb
1717
1708
1718 self.CustomTB = types.MethodType(wrapped,self)
1709 self.CustomTB = types.MethodType(wrapped,self)
1719 self.custom_exceptions = exc_tuple
1710 self.custom_exceptions = exc_tuple
1720
1711
1721 def excepthook(self, etype, value, tb):
1712 def excepthook(self, etype, value, tb):
1722 """One more defense for GUI apps that call sys.excepthook.
1713 """One more defense for GUI apps that call sys.excepthook.
1723
1714
1724 GUI frameworks like wxPython trap exceptions and call
1715 GUI frameworks like wxPython trap exceptions and call
1725 sys.excepthook themselves. I guess this is a feature that
1716 sys.excepthook themselves. I guess this is a feature that
1726 enables them to keep running after exceptions that would
1717 enables them to keep running after exceptions that would
1727 otherwise kill their mainloop. This is a bother for IPython
1718 otherwise kill their mainloop. This is a bother for IPython
1728 which excepts to catch all of the program exceptions with a try:
1719 which excepts to catch all of the program exceptions with a try:
1729 except: statement.
1720 except: statement.
1730
1721
1731 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1722 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1732 any app directly invokes sys.excepthook, it will look to the user like
1723 any app directly invokes sys.excepthook, it will look to the user like
1733 IPython crashed. In order to work around this, we can disable the
1724 IPython crashed. In order to work around this, we can disable the
1734 CrashHandler and replace it with this excepthook instead, which prints a
1725 CrashHandler and replace it with this excepthook instead, which prints a
1735 regular traceback using our InteractiveTB. In this fashion, apps which
1726 regular traceback using our InteractiveTB. In this fashion, apps which
1736 call sys.excepthook will generate a regular-looking exception from
1727 call sys.excepthook will generate a regular-looking exception from
1737 IPython, and the CrashHandler will only be triggered by real IPython
1728 IPython, and the CrashHandler will only be triggered by real IPython
1738 crashes.
1729 crashes.
1739
1730
1740 This hook should be used sparingly, only in places which are not likely
1731 This hook should be used sparingly, only in places which are not likely
1741 to be true IPython errors.
1732 to be true IPython errors.
1742 """
1733 """
1743 self.showtraceback((etype, value, tb), tb_offset=0)
1734 self.showtraceback((etype, value, tb), tb_offset=0)
1744
1735
1745 def _get_exc_info(self, exc_tuple=None):
1736 def _get_exc_info(self, exc_tuple=None):
1746 """get exc_info from a given tuple, sys.exc_info() or sys.last_type etc.
1737 """get exc_info from a given tuple, sys.exc_info() or sys.last_type etc.
1747
1738
1748 Ensures sys.last_type,value,traceback hold the exc_info we found,
1739 Ensures sys.last_type,value,traceback hold the exc_info we found,
1749 from whichever source.
1740 from whichever source.
1750
1741
1751 raises ValueError if none of these contain any information
1742 raises ValueError if none of these contain any information
1752 """
1743 """
1753 if exc_tuple is None:
1744 if exc_tuple is None:
1754 etype, value, tb = sys.exc_info()
1745 etype, value, tb = sys.exc_info()
1755 else:
1746 else:
1756 etype, value, tb = exc_tuple
1747 etype, value, tb = exc_tuple
1757
1748
1758 if etype is None:
1749 if etype is None:
1759 if hasattr(sys, 'last_type'):
1750 if hasattr(sys, 'last_type'):
1760 etype, value, tb = sys.last_type, sys.last_value, \
1751 etype, value, tb = sys.last_type, sys.last_value, \
1761 sys.last_traceback
1752 sys.last_traceback
1762
1753
1763 if etype is None:
1754 if etype is None:
1764 raise ValueError("No exception to find")
1755 raise ValueError("No exception to find")
1765
1756
1766 # Now store the exception info in sys.last_type etc.
1757 # Now store the exception info in sys.last_type etc.
1767 # WARNING: these variables are somewhat deprecated and not
1758 # WARNING: these variables are somewhat deprecated and not
1768 # necessarily safe to use in a threaded environment, but tools
1759 # necessarily safe to use in a threaded environment, but tools
1769 # like pdb depend on their existence, so let's set them. If we
1760 # like pdb depend on their existence, so let's set them. If we
1770 # find problems in the field, we'll need to revisit their use.
1761 # find problems in the field, we'll need to revisit their use.
1771 sys.last_type = etype
1762 sys.last_type = etype
1772 sys.last_value = value
1763 sys.last_value = value
1773 sys.last_traceback = tb
1764 sys.last_traceback = tb
1774
1765
1775 return etype, value, tb
1766 return etype, value, tb
1776
1767
1777 def show_usage_error(self, exc):
1768 def show_usage_error(self, exc):
1778 """Show a short message for UsageErrors
1769 """Show a short message for UsageErrors
1779
1770
1780 These are special exceptions that shouldn't show a traceback.
1771 These are special exceptions that shouldn't show a traceback.
1781 """
1772 """
1782 print("UsageError: %s" % exc, file=sys.stderr)
1773 print("UsageError: %s" % exc, file=sys.stderr)
1783
1774
1784 def get_exception_only(self, exc_tuple=None):
1775 def get_exception_only(self, exc_tuple=None):
1785 """
1776 """
1786 Return as a string (ending with a newline) the exception that
1777 Return as a string (ending with a newline) the exception that
1787 just occurred, without any traceback.
1778 just occurred, without any traceback.
1788 """
1779 """
1789 etype, value, tb = self._get_exc_info(exc_tuple)
1780 etype, value, tb = self._get_exc_info(exc_tuple)
1790 msg = traceback.format_exception_only(etype, value)
1781 msg = traceback.format_exception_only(etype, value)
1791 return ''.join(msg)
1782 return ''.join(msg)
1792
1783
1793 def showtraceback(self, exc_tuple=None, filename=None, tb_offset=None,
1784 def showtraceback(self, exc_tuple=None, filename=None, tb_offset=None,
1794 exception_only=False):
1785 exception_only=False):
1795 """Display the exception that just occurred.
1786 """Display the exception that just occurred.
1796
1787
1797 If nothing is known about the exception, this is the method which
1788 If nothing is known about the exception, this is the method which
1798 should be used throughout the code for presenting user tracebacks,
1789 should be used throughout the code for presenting user tracebacks,
1799 rather than directly invoking the InteractiveTB object.
1790 rather than directly invoking the InteractiveTB object.
1800
1791
1801 A specific showsyntaxerror() also exists, but this method can take
1792 A specific showsyntaxerror() also exists, but this method can take
1802 care of calling it if needed, so unless you are explicitly catching a
1793 care of calling it if needed, so unless you are explicitly catching a
1803 SyntaxError exception, don't try to analyze the stack manually and
1794 SyntaxError exception, don't try to analyze the stack manually and
1804 simply call this method."""
1795 simply call this method."""
1805
1796
1806 try:
1797 try:
1807 try:
1798 try:
1808 etype, value, tb = self._get_exc_info(exc_tuple)
1799 etype, value, tb = self._get_exc_info(exc_tuple)
1809 except ValueError:
1800 except ValueError:
1810 print('No traceback available to show.', file=sys.stderr)
1801 print('No traceback available to show.', file=sys.stderr)
1811 return
1802 return
1812
1803
1813 if issubclass(etype, SyntaxError):
1804 if issubclass(etype, SyntaxError):
1814 # Though this won't be called by syntax errors in the input
1805 # Though this won't be called by syntax errors in the input
1815 # line, there may be SyntaxError cases with imported code.
1806 # line, there may be SyntaxError cases with imported code.
1816 self.showsyntaxerror(filename)
1807 self.showsyntaxerror(filename)
1817 elif etype is UsageError:
1808 elif etype is UsageError:
1818 self.show_usage_error(value)
1809 self.show_usage_error(value)
1819 else:
1810 else:
1820 if exception_only:
1811 if exception_only:
1821 stb = ['An exception has occurred, use %tb to see '
1812 stb = ['An exception has occurred, use %tb to see '
1822 'the full traceback.\n']
1813 'the full traceback.\n']
1823 stb.extend(self.InteractiveTB.get_exception_only(etype,
1814 stb.extend(self.InteractiveTB.get_exception_only(etype,
1824 value))
1815 value))
1825 else:
1816 else:
1826 try:
1817 try:
1827 # Exception classes can customise their traceback - we
1818 # Exception classes can customise their traceback - we
1828 # use this in IPython.parallel for exceptions occurring
1819 # use this in IPython.parallel for exceptions occurring
1829 # in the engines. This should return a list of strings.
1820 # in the engines. This should return a list of strings.
1830 stb = value._render_traceback_()
1821 stb = value._render_traceback_()
1831 except Exception:
1822 except Exception:
1832 stb = self.InteractiveTB.structured_traceback(etype,
1823 stb = self.InteractiveTB.structured_traceback(etype,
1833 value, tb, tb_offset=tb_offset)
1824 value, tb, tb_offset=tb_offset)
1834
1825
1835 self._showtraceback(etype, value, stb)
1826 self._showtraceback(etype, value, stb)
1836 if self.call_pdb:
1827 if self.call_pdb:
1837 # drop into debugger
1828 # drop into debugger
1838 self.debugger(force=True)
1829 self.debugger(force=True)
1839 return
1830 return
1840
1831
1841 # Actually show the traceback
1832 # Actually show the traceback
1842 self._showtraceback(etype, value, stb)
1833 self._showtraceback(etype, value, stb)
1843
1834
1844 except KeyboardInterrupt:
1835 except KeyboardInterrupt:
1845 print('\n' + self.get_exception_only(), file=sys.stderr)
1836 print('\n' + self.get_exception_only(), file=sys.stderr)
1846
1837
1847 def _showtraceback(self, etype, evalue, stb):
1838 def _showtraceback(self, etype, evalue, stb):
1848 """Actually show a traceback.
1839 """Actually show a traceback.
1849
1840
1850 Subclasses may override this method to put the traceback on a different
1841 Subclasses may override this method to put the traceback on a different
1851 place, like a side channel.
1842 place, like a side channel.
1852 """
1843 """
1853 print(self.InteractiveTB.stb2text(stb))
1844 print(self.InteractiveTB.stb2text(stb))
1854
1845
1855 def showsyntaxerror(self, filename=None):
1846 def showsyntaxerror(self, filename=None):
1856 """Display the syntax error that just occurred.
1847 """Display the syntax error that just occurred.
1857
1848
1858 This doesn't display a stack trace because there isn't one.
1849 This doesn't display a stack trace because there isn't one.
1859
1850
1860 If a filename is given, it is stuffed in the exception instead
1851 If a filename is given, it is stuffed in the exception instead
1861 of what was there before (because Python's parser always uses
1852 of what was there before (because Python's parser always uses
1862 "<string>" when reading from a string).
1853 "<string>" when reading from a string).
1863 """
1854 """
1864 etype, value, last_traceback = self._get_exc_info()
1855 etype, value, last_traceback = self._get_exc_info()
1865
1856
1866 if filename and issubclass(etype, SyntaxError):
1857 if filename and issubclass(etype, SyntaxError):
1867 try:
1858 try:
1868 value.filename = filename
1859 value.filename = filename
1869 except:
1860 except:
1870 # Not the format we expect; leave it alone
1861 # Not the format we expect; leave it alone
1871 pass
1862 pass
1872
1863
1873 stb = self.SyntaxTB.structured_traceback(etype, value, [])
1864 stb = self.SyntaxTB.structured_traceback(etype, value, [])
1874 self._showtraceback(etype, value, stb)
1865 self._showtraceback(etype, value, stb)
1875
1866
1876 # This is overridden in TerminalInteractiveShell to show a message about
1867 # This is overridden in TerminalInteractiveShell to show a message about
1877 # the %paste magic.
1868 # the %paste magic.
1878 def showindentationerror(self):
1869 def showindentationerror(self):
1879 """Called by run_cell when there's an IndentationError in code entered
1870 """Called by run_cell when there's an IndentationError in code entered
1880 at the prompt.
1871 at the prompt.
1881
1872
1882 This is overridden in TerminalInteractiveShell to show a message about
1873 This is overridden in TerminalInteractiveShell to show a message about
1883 the %paste magic."""
1874 the %paste magic."""
1884 self.showsyntaxerror()
1875 self.showsyntaxerror()
1885
1876
1886 #-------------------------------------------------------------------------
1877 #-------------------------------------------------------------------------
1887 # Things related to readline
1878 # Things related to readline
1888 #-------------------------------------------------------------------------
1879 #-------------------------------------------------------------------------
1889
1880
1890 def init_readline(self):
1881 def init_readline(self):
1891 """Moved to terminal subclass, here only to simplify the init logic."""
1882 """Moved to terminal subclass, here only to simplify the init logic."""
1892 self.readline = None
1893 # Set a number of methods that depend on readline to be no-op
1883 # Set a number of methods that depend on readline to be no-op
1894 self.readline_no_record = NoOpContext()
1895 self.set_readline_completer = no_op
1896 self.set_custom_completer = no_op
1884 self.set_custom_completer = no_op
1897
1885
1898 @skip_doctest
1886 @skip_doctest
1899 def set_next_input(self, s, replace=False):
1887 def set_next_input(self, s, replace=False):
1900 """ Sets the 'default' input string for the next command line.
1888 """ Sets the 'default' input string for the next command line.
1901
1889
1902 Example::
1890 Example::
1903
1891
1904 In [1]: _ip.set_next_input("Hello Word")
1892 In [1]: _ip.set_next_input("Hello Word")
1905 In [2]: Hello Word_ # cursor is here
1893 In [2]: Hello Word_ # cursor is here
1906 """
1894 """
1907 self.rl_next_input = py3compat.cast_bytes_py2(s)
1895 self.rl_next_input = py3compat.cast_bytes_py2(s)
1908
1896
1909 def _indent_current_str(self):
1897 def _indent_current_str(self):
1910 """return the current level of indentation as a string"""
1898 """return the current level of indentation as a string"""
1911 return self.input_splitter.indent_spaces * ' '
1899 return self.input_splitter.indent_spaces * ' '
1912
1900
1913 #-------------------------------------------------------------------------
1901 #-------------------------------------------------------------------------
1914 # Things related to text completion
1902 # Things related to text completion
1915 #-------------------------------------------------------------------------
1903 #-------------------------------------------------------------------------
1916
1904
1917 def init_completer(self):
1905 def init_completer(self):
1918 """Initialize the completion machinery.
1906 """Initialize the completion machinery.
1919
1907
1920 This creates completion machinery that can be used by client code,
1908 This creates completion machinery that can be used by client code,
1921 either interactively in-process (typically triggered by the readline
1909 either interactively in-process (typically triggered by the readline
1922 library), programmatically (such as in test suites) or out-of-process
1910 library), programmatically (such as in test suites) or out-of-process
1923 (typically over the network by remote frontends).
1911 (typically over the network by remote frontends).
1924 """
1912 """
1925 from IPython.core.completer import IPCompleter
1913 from IPython.core.completer import IPCompleter
1926 from IPython.core.completerlib import (module_completer,
1914 from IPython.core.completerlib import (module_completer,
1927 magic_run_completer, cd_completer, reset_completer)
1915 magic_run_completer, cd_completer, reset_completer)
1928
1916
1929 self.Completer = IPCompleter(shell=self,
1917 self.Completer = IPCompleter(shell=self,
1930 namespace=self.user_ns,
1918 namespace=self.user_ns,
1931 global_namespace=self.user_global_ns,
1919 global_namespace=self.user_global_ns,
1932 use_readline=self.has_readline,
1920 use_readline=False,
1933 parent=self,
1921 parent=self,
1934 )
1922 )
1935 self.configurables.append(self.Completer)
1923 self.configurables.append(self.Completer)
1936
1924
1937 # Add custom completers to the basic ones built into IPCompleter
1925 # Add custom completers to the basic ones built into IPCompleter
1938 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1926 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1939 self.strdispatchers['complete_command'] = sdisp
1927 self.strdispatchers['complete_command'] = sdisp
1940 self.Completer.custom_completers = sdisp
1928 self.Completer.custom_completers = sdisp
1941
1929
1942 self.set_hook('complete_command', module_completer, str_key = 'import')
1930 self.set_hook('complete_command', module_completer, str_key = 'import')
1943 self.set_hook('complete_command', module_completer, str_key = 'from')
1931 self.set_hook('complete_command', module_completer, str_key = 'from')
1944 self.set_hook('complete_command', module_completer, str_key = '%aimport')
1932 self.set_hook('complete_command', module_completer, str_key = '%aimport')
1945 self.set_hook('complete_command', magic_run_completer, str_key = '%run')
1933 self.set_hook('complete_command', magic_run_completer, str_key = '%run')
1946 self.set_hook('complete_command', cd_completer, str_key = '%cd')
1934 self.set_hook('complete_command', cd_completer, str_key = '%cd')
1947 self.set_hook('complete_command', reset_completer, str_key = '%reset')
1935 self.set_hook('complete_command', reset_completer, str_key = '%reset')
1948
1936
1949
1937
1950 @skip_doctest_py2
1938 @skip_doctest_py2
1951 def complete(self, text, line=None, cursor_pos=None):
1939 def complete(self, text, line=None, cursor_pos=None):
1952 """Return the completed text and a list of completions.
1940 """Return the completed text and a list of completions.
1953
1941
1954 Parameters
1942 Parameters
1955 ----------
1943 ----------
1956
1944
1957 text : string
1945 text : string
1958 A string of text to be completed on. It can be given as empty and
1946 A string of text to be completed on. It can be given as empty and
1959 instead a line/position pair are given. In this case, the
1947 instead a line/position pair are given. In this case, the
1960 completer itself will split the line like readline does.
1948 completer itself will split the line like readline does.
1961
1949
1962 line : string, optional
1950 line : string, optional
1963 The complete line that text is part of.
1951 The complete line that text is part of.
1964
1952
1965 cursor_pos : int, optional
1953 cursor_pos : int, optional
1966 The position of the cursor on the input line.
1954 The position of the cursor on the input line.
1967
1955
1968 Returns
1956 Returns
1969 -------
1957 -------
1970 text : string
1958 text : string
1971 The actual text that was completed.
1959 The actual text that was completed.
1972
1960
1973 matches : list
1961 matches : list
1974 A sorted list with all possible completions.
1962 A sorted list with all possible completions.
1975
1963
1976 The optional arguments allow the completion to take more context into
1964 The optional arguments allow the completion to take more context into
1977 account, and are part of the low-level completion API.
1965 account, and are part of the low-level completion API.
1978
1966
1979 This is a wrapper around the completion mechanism, similar to what
1967 This is a wrapper around the completion mechanism, similar to what
1980 readline does at the command line when the TAB key is hit. By
1968 readline does at the command line when the TAB key is hit. By
1981 exposing it as a method, it can be used by other non-readline
1969 exposing it as a method, it can be used by other non-readline
1982 environments (such as GUIs) for text completion.
1970 environments (such as GUIs) for text completion.
1983
1971
1984 Simple usage example:
1972 Simple usage example:
1985
1973
1986 In [1]: x = 'hello'
1974 In [1]: x = 'hello'
1987
1975
1988 In [2]: _ip.complete('x.l')
1976 In [2]: _ip.complete('x.l')
1989 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
1977 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
1990 """
1978 """
1991
1979
1992 # Inject names into __builtin__ so we can complete on the added names.
1980 # Inject names into __builtin__ so we can complete on the added names.
1993 with self.builtin_trap:
1981 with self.builtin_trap:
1994 return self.Completer.complete(text, line, cursor_pos)
1982 return self.Completer.complete(text, line, cursor_pos)
1995
1983
1996 def set_custom_completer(self, completer, pos=0):
1984 def set_custom_completer(self, completer, pos=0):
1997 """Adds a new custom completer function.
1985 """Adds a new custom completer function.
1998
1986
1999 The position argument (defaults to 0) is the index in the completers
1987 The position argument (defaults to 0) is the index in the completers
2000 list where you want the completer to be inserted."""
1988 list where you want the completer to be inserted."""
2001
1989
2002 newcomp = types.MethodType(completer,self.Completer)
1990 newcomp = types.MethodType(completer,self.Completer)
2003 self.Completer.matchers.insert(pos,newcomp)
1991 self.Completer.matchers.insert(pos,newcomp)
2004
1992
2005 def set_completer_frame(self, frame=None):
1993 def set_completer_frame(self, frame=None):
2006 """Set the frame of the completer."""
1994 """Set the frame of the completer."""
2007 if frame:
1995 if frame:
2008 self.Completer.namespace = frame.f_locals
1996 self.Completer.namespace = frame.f_locals
2009 self.Completer.global_namespace = frame.f_globals
1997 self.Completer.global_namespace = frame.f_globals
2010 else:
1998 else:
2011 self.Completer.namespace = self.user_ns
1999 self.Completer.namespace = self.user_ns
2012 self.Completer.global_namespace = self.user_global_ns
2000 self.Completer.global_namespace = self.user_global_ns
2013
2001
2014 #-------------------------------------------------------------------------
2002 #-------------------------------------------------------------------------
2015 # Things related to magics
2003 # Things related to magics
2016 #-------------------------------------------------------------------------
2004 #-------------------------------------------------------------------------
2017
2005
2018 def init_magics(self):
2006 def init_magics(self):
2019 from IPython.core import magics as m
2007 from IPython.core import magics as m
2020 self.magics_manager = magic.MagicsManager(shell=self,
2008 self.magics_manager = magic.MagicsManager(shell=self,
2021 parent=self,
2009 parent=self,
2022 user_magics=m.UserMagics(self))
2010 user_magics=m.UserMagics(self))
2023 self.configurables.append(self.magics_manager)
2011 self.configurables.append(self.magics_manager)
2024
2012
2025 # Expose as public API from the magics manager
2013 # Expose as public API from the magics manager
2026 self.register_magics = self.magics_manager.register
2014 self.register_magics = self.magics_manager.register
2027
2015
2028 self.register_magics(m.AutoMagics, m.BasicMagics, m.CodeMagics,
2016 self.register_magics(m.AutoMagics, m.BasicMagics, m.CodeMagics,
2029 m.ConfigMagics, m.DisplayMagics, m.ExecutionMagics,
2017 m.ConfigMagics, m.DisplayMagics, m.ExecutionMagics,
2030 m.ExtensionMagics, m.HistoryMagics, m.LoggingMagics,
2018 m.ExtensionMagics, m.HistoryMagics, m.LoggingMagics,
2031 m.NamespaceMagics, m.OSMagics, m.PylabMagics, m.ScriptMagics,
2019 m.NamespaceMagics, m.OSMagics, m.PylabMagics, m.ScriptMagics,
2032 )
2020 )
2033
2021
2034 # Register Magic Aliases
2022 # Register Magic Aliases
2035 mman = self.magics_manager
2023 mman = self.magics_manager
2036 # FIXME: magic aliases should be defined by the Magics classes
2024 # FIXME: magic aliases should be defined by the Magics classes
2037 # or in MagicsManager, not here
2025 # or in MagicsManager, not here
2038 mman.register_alias('ed', 'edit')
2026 mman.register_alias('ed', 'edit')
2039 mman.register_alias('hist', 'history')
2027 mman.register_alias('hist', 'history')
2040 mman.register_alias('rep', 'recall')
2028 mman.register_alias('rep', 'recall')
2041 mman.register_alias('SVG', 'svg', 'cell')
2029 mman.register_alias('SVG', 'svg', 'cell')
2042 mman.register_alias('HTML', 'html', 'cell')
2030 mman.register_alias('HTML', 'html', 'cell')
2043 mman.register_alias('file', 'writefile', 'cell')
2031 mman.register_alias('file', 'writefile', 'cell')
2044
2032
2045 # FIXME: Move the color initialization to the DisplayHook, which
2033 # FIXME: Move the color initialization to the DisplayHook, which
2046 # should be split into a prompt manager and displayhook. We probably
2034 # should be split into a prompt manager and displayhook. We probably
2047 # even need a centralize colors management object.
2035 # even need a centralize colors management object.
2048 self.magic('colors %s' % self.colors)
2036 self.magic('colors %s' % self.colors)
2049
2037
2050 # Defined here so that it's included in the documentation
2038 # Defined here so that it's included in the documentation
2051 @functools.wraps(magic.MagicsManager.register_function)
2039 @functools.wraps(magic.MagicsManager.register_function)
2052 def register_magic_function(self, func, magic_kind='line', magic_name=None):
2040 def register_magic_function(self, func, magic_kind='line', magic_name=None):
2053 self.magics_manager.register_function(func,
2041 self.magics_manager.register_function(func,
2054 magic_kind=magic_kind, magic_name=magic_name)
2042 magic_kind=magic_kind, magic_name=magic_name)
2055
2043
2056 def run_line_magic(self, magic_name, line):
2044 def run_line_magic(self, magic_name, line):
2057 """Execute the given line magic.
2045 """Execute the given line magic.
2058
2046
2059 Parameters
2047 Parameters
2060 ----------
2048 ----------
2061 magic_name : str
2049 magic_name : str
2062 Name of the desired magic function, without '%' prefix.
2050 Name of the desired magic function, without '%' prefix.
2063
2051
2064 line : str
2052 line : str
2065 The rest of the input line as a single string.
2053 The rest of the input line as a single string.
2066 """
2054 """
2067 fn = self.find_line_magic(magic_name)
2055 fn = self.find_line_magic(magic_name)
2068 if fn is None:
2056 if fn is None:
2069 cm = self.find_cell_magic(magic_name)
2057 cm = self.find_cell_magic(magic_name)
2070 etpl = "Line magic function `%%%s` not found%s."
2058 etpl = "Line magic function `%%%s` not found%s."
2071 extra = '' if cm is None else (' (But cell magic `%%%%%s` exists, '
2059 extra = '' if cm is None else (' (But cell magic `%%%%%s` exists, '
2072 'did you mean that instead?)' % magic_name )
2060 'did you mean that instead?)' % magic_name )
2073 error(etpl % (magic_name, extra))
2061 error(etpl % (magic_name, extra))
2074 else:
2062 else:
2075 # Note: this is the distance in the stack to the user's frame.
2063 # Note: this is the distance in the stack to the user's frame.
2076 # This will need to be updated if the internal calling logic gets
2064 # This will need to be updated if the internal calling logic gets
2077 # refactored, or else we'll be expanding the wrong variables.
2065 # refactored, or else we'll be expanding the wrong variables.
2078 stack_depth = 2
2066 stack_depth = 2
2079 magic_arg_s = self.var_expand(line, stack_depth)
2067 magic_arg_s = self.var_expand(line, stack_depth)
2080 # Put magic args in a list so we can call with f(*a) syntax
2068 # Put magic args in a list so we can call with f(*a) syntax
2081 args = [magic_arg_s]
2069 args = [magic_arg_s]
2082 kwargs = {}
2070 kwargs = {}
2083 # Grab local namespace if we need it:
2071 # Grab local namespace if we need it:
2084 if getattr(fn, "needs_local_scope", False):
2072 if getattr(fn, "needs_local_scope", False):
2085 kwargs['local_ns'] = sys._getframe(stack_depth).f_locals
2073 kwargs['local_ns'] = sys._getframe(stack_depth).f_locals
2086 with self.builtin_trap:
2074 with self.builtin_trap:
2087 result = fn(*args,**kwargs)
2075 result = fn(*args,**kwargs)
2088 return result
2076 return result
2089
2077
2090 def run_cell_magic(self, magic_name, line, cell):
2078 def run_cell_magic(self, magic_name, line, cell):
2091 """Execute the given cell magic.
2079 """Execute the given cell magic.
2092
2080
2093 Parameters
2081 Parameters
2094 ----------
2082 ----------
2095 magic_name : str
2083 magic_name : str
2096 Name of the desired magic function, without '%' prefix.
2084 Name of the desired magic function, without '%' prefix.
2097
2085
2098 line : str
2086 line : str
2099 The rest of the first input line as a single string.
2087 The rest of the first input line as a single string.
2100
2088
2101 cell : str
2089 cell : str
2102 The body of the cell as a (possibly multiline) string.
2090 The body of the cell as a (possibly multiline) string.
2103 """
2091 """
2104 fn = self.find_cell_magic(magic_name)
2092 fn = self.find_cell_magic(magic_name)
2105 if fn is None:
2093 if fn is None:
2106 lm = self.find_line_magic(magic_name)
2094 lm = self.find_line_magic(magic_name)
2107 etpl = "Cell magic `%%{0}` not found{1}."
2095 etpl = "Cell magic `%%{0}` not found{1}."
2108 extra = '' if lm is None else (' (But line magic `%{0}` exists, '
2096 extra = '' if lm is None else (' (But line magic `%{0}` exists, '
2109 'did you mean that instead?)'.format(magic_name))
2097 'did you mean that instead?)'.format(magic_name))
2110 error(etpl.format(magic_name, extra))
2098 error(etpl.format(magic_name, extra))
2111 elif cell == '':
2099 elif cell == '':
2112 message = '%%{0} is a cell magic, but the cell body is empty.'.format(magic_name)
2100 message = '%%{0} is a cell magic, but the cell body is empty.'.format(magic_name)
2113 if self.find_line_magic(magic_name) is not None:
2101 if self.find_line_magic(magic_name) is not None:
2114 message += ' Did you mean the line magic %{0} (single %)?'.format(magic_name)
2102 message += ' Did you mean the line magic %{0} (single %)?'.format(magic_name)
2115 raise UsageError(message)
2103 raise UsageError(message)
2116 else:
2104 else:
2117 # Note: this is the distance in the stack to the user's frame.
2105 # Note: this is the distance in the stack to the user's frame.
2118 # This will need to be updated if the internal calling logic gets
2106 # This will need to be updated if the internal calling logic gets
2119 # refactored, or else we'll be expanding the wrong variables.
2107 # refactored, or else we'll be expanding the wrong variables.
2120 stack_depth = 2
2108 stack_depth = 2
2121 magic_arg_s = self.var_expand(line, stack_depth)
2109 magic_arg_s = self.var_expand(line, stack_depth)
2122 with self.builtin_trap:
2110 with self.builtin_trap:
2123 result = fn(magic_arg_s, cell)
2111 result = fn(magic_arg_s, cell)
2124 return result
2112 return result
2125
2113
2126 def find_line_magic(self, magic_name):
2114 def find_line_magic(self, magic_name):
2127 """Find and return a line magic by name.
2115 """Find and return a line magic by name.
2128
2116
2129 Returns None if the magic isn't found."""
2117 Returns None if the magic isn't found."""
2130 return self.magics_manager.magics['line'].get(magic_name)
2118 return self.magics_manager.magics['line'].get(magic_name)
2131
2119
2132 def find_cell_magic(self, magic_name):
2120 def find_cell_magic(self, magic_name):
2133 """Find and return a cell magic by name.
2121 """Find and return a cell magic by name.
2134
2122
2135 Returns None if the magic isn't found."""
2123 Returns None if the magic isn't found."""
2136 return self.magics_manager.magics['cell'].get(magic_name)
2124 return self.magics_manager.magics['cell'].get(magic_name)
2137
2125
2138 def find_magic(self, magic_name, magic_kind='line'):
2126 def find_magic(self, magic_name, magic_kind='line'):
2139 """Find and return a magic of the given type by name.
2127 """Find and return a magic of the given type by name.
2140
2128
2141 Returns None if the magic isn't found."""
2129 Returns None if the magic isn't found."""
2142 return self.magics_manager.magics[magic_kind].get(magic_name)
2130 return self.magics_manager.magics[magic_kind].get(magic_name)
2143
2131
2144 def magic(self, arg_s):
2132 def magic(self, arg_s):
2145 """DEPRECATED. Use run_line_magic() instead.
2133 """DEPRECATED. Use run_line_magic() instead.
2146
2134
2147 Call a magic function by name.
2135 Call a magic function by name.
2148
2136
2149 Input: a string containing the name of the magic function to call and
2137 Input: a string containing the name of the magic function to call and
2150 any additional arguments to be passed to the magic.
2138 any additional arguments to be passed to the magic.
2151
2139
2152 magic('name -opt foo bar') is equivalent to typing at the ipython
2140 magic('name -opt foo bar') is equivalent to typing at the ipython
2153 prompt:
2141 prompt:
2154
2142
2155 In[1]: %name -opt foo bar
2143 In[1]: %name -opt foo bar
2156
2144
2157 To call a magic without arguments, simply use magic('name').
2145 To call a magic without arguments, simply use magic('name').
2158
2146
2159 This provides a proper Python function to call IPython's magics in any
2147 This provides a proper Python function to call IPython's magics in any
2160 valid Python code you can type at the interpreter, including loops and
2148 valid Python code you can type at the interpreter, including loops and
2161 compound statements.
2149 compound statements.
2162 """
2150 """
2163 # TODO: should we issue a loud deprecation warning here?
2151 # TODO: should we issue a loud deprecation warning here?
2164 magic_name, _, magic_arg_s = arg_s.partition(' ')
2152 magic_name, _, magic_arg_s = arg_s.partition(' ')
2165 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
2153 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
2166 return self.run_line_magic(magic_name, magic_arg_s)
2154 return self.run_line_magic(magic_name, magic_arg_s)
2167
2155
2168 #-------------------------------------------------------------------------
2156 #-------------------------------------------------------------------------
2169 # Things related to macros
2157 # Things related to macros
2170 #-------------------------------------------------------------------------
2158 #-------------------------------------------------------------------------
2171
2159
2172 def define_macro(self, name, themacro):
2160 def define_macro(self, name, themacro):
2173 """Define a new macro
2161 """Define a new macro
2174
2162
2175 Parameters
2163 Parameters
2176 ----------
2164 ----------
2177 name : str
2165 name : str
2178 The name of the macro.
2166 The name of the macro.
2179 themacro : str or Macro
2167 themacro : str or Macro
2180 The action to do upon invoking the macro. If a string, a new
2168 The action to do upon invoking the macro. If a string, a new
2181 Macro object is created by passing the string to it.
2169 Macro object is created by passing the string to it.
2182 """
2170 """
2183
2171
2184 from IPython.core import macro
2172 from IPython.core import macro
2185
2173
2186 if isinstance(themacro, string_types):
2174 if isinstance(themacro, string_types):
2187 themacro = macro.Macro(themacro)
2175 themacro = macro.Macro(themacro)
2188 if not isinstance(themacro, macro.Macro):
2176 if not isinstance(themacro, macro.Macro):
2189 raise ValueError('A macro must be a string or a Macro instance.')
2177 raise ValueError('A macro must be a string or a Macro instance.')
2190 self.user_ns[name] = themacro
2178 self.user_ns[name] = themacro
2191
2179
2192 #-------------------------------------------------------------------------
2180 #-------------------------------------------------------------------------
2193 # Things related to the running of system commands
2181 # Things related to the running of system commands
2194 #-------------------------------------------------------------------------
2182 #-------------------------------------------------------------------------
2195
2183
2196 def system_piped(self, cmd):
2184 def system_piped(self, cmd):
2197 """Call the given cmd in a subprocess, piping stdout/err
2185 """Call the given cmd in a subprocess, piping stdout/err
2198
2186
2199 Parameters
2187 Parameters
2200 ----------
2188 ----------
2201 cmd : str
2189 cmd : str
2202 Command to execute (can not end in '&', as background processes are
2190 Command to execute (can not end in '&', as background processes are
2203 not supported. Should not be a command that expects input
2191 not supported. Should not be a command that expects input
2204 other than simple text.
2192 other than simple text.
2205 """
2193 """
2206 if cmd.rstrip().endswith('&'):
2194 if cmd.rstrip().endswith('&'):
2207 # this is *far* from a rigorous test
2195 # this is *far* from a rigorous test
2208 # We do not support backgrounding processes because we either use
2196 # We do not support backgrounding processes because we either use
2209 # pexpect or pipes to read from. Users can always just call
2197 # pexpect or pipes to read from. Users can always just call
2210 # os.system() or use ip.system=ip.system_raw
2198 # os.system() or use ip.system=ip.system_raw
2211 # if they really want a background process.
2199 # if they really want a background process.
2212 raise OSError("Background processes not supported.")
2200 raise OSError("Background processes not supported.")
2213
2201
2214 # we explicitly do NOT return the subprocess status code, because
2202 # we explicitly do NOT return the subprocess status code, because
2215 # a non-None value would trigger :func:`sys.displayhook` calls.
2203 # a non-None value would trigger :func:`sys.displayhook` calls.
2216 # Instead, we store the exit_code in user_ns.
2204 # Instead, we store the exit_code in user_ns.
2217 self.user_ns['_exit_code'] = system(self.var_expand(cmd, depth=1))
2205 self.user_ns['_exit_code'] = system(self.var_expand(cmd, depth=1))
2218
2206
2219 def system_raw(self, cmd):
2207 def system_raw(self, cmd):
2220 """Call the given cmd in a subprocess using os.system on Windows or
2208 """Call the given cmd in a subprocess using os.system on Windows or
2221 subprocess.call using the system shell on other platforms.
2209 subprocess.call using the system shell on other platforms.
2222
2210
2223 Parameters
2211 Parameters
2224 ----------
2212 ----------
2225 cmd : str
2213 cmd : str
2226 Command to execute.
2214 Command to execute.
2227 """
2215 """
2228 cmd = self.var_expand(cmd, depth=1)
2216 cmd = self.var_expand(cmd, depth=1)
2229 # protect os.system from UNC paths on Windows, which it can't handle:
2217 # protect os.system from UNC paths on Windows, which it can't handle:
2230 if sys.platform == 'win32':
2218 if sys.platform == 'win32':
2231 from IPython.utils._process_win32 import AvoidUNCPath
2219 from IPython.utils._process_win32 import AvoidUNCPath
2232 with AvoidUNCPath() as path:
2220 with AvoidUNCPath() as path:
2233 if path is not None:
2221 if path is not None:
2234 cmd = '"pushd %s &&"%s' % (path, cmd)
2222 cmd = '"pushd %s &&"%s' % (path, cmd)
2235 cmd = py3compat.unicode_to_str(cmd)
2223 cmd = py3compat.unicode_to_str(cmd)
2236 try:
2224 try:
2237 ec = os.system(cmd)
2225 ec = os.system(cmd)
2238 except KeyboardInterrupt:
2226 except KeyboardInterrupt:
2239 print('\n' + self.get_exception_only(), file=sys.stderr)
2227 print('\n' + self.get_exception_only(), file=sys.stderr)
2240 ec = -2
2228 ec = -2
2241 else:
2229 else:
2242 cmd = py3compat.unicode_to_str(cmd)
2230 cmd = py3compat.unicode_to_str(cmd)
2243 # For posix the result of the subprocess.call() below is an exit
2231 # For posix the result of the subprocess.call() below is an exit
2244 # code, which by convention is zero for success, positive for
2232 # code, which by convention is zero for success, positive for
2245 # program failure. Exit codes above 128 are reserved for signals,
2233 # program failure. Exit codes above 128 are reserved for signals,
2246 # and the formula for converting a signal to an exit code is usually
2234 # and the formula for converting a signal to an exit code is usually
2247 # signal_number+128. To more easily differentiate between exit
2235 # signal_number+128. To more easily differentiate between exit
2248 # codes and signals, ipython uses negative numbers. For instance
2236 # codes and signals, ipython uses negative numbers. For instance
2249 # since control-c is signal 2 but exit code 130, ipython's
2237 # since control-c is signal 2 but exit code 130, ipython's
2250 # _exit_code variable will read -2. Note that some shells like
2238 # _exit_code variable will read -2. Note that some shells like
2251 # csh and fish don't follow sh/bash conventions for exit codes.
2239 # csh and fish don't follow sh/bash conventions for exit codes.
2252 executable = os.environ.get('SHELL', None)
2240 executable = os.environ.get('SHELL', None)
2253 try:
2241 try:
2254 # Use env shell instead of default /bin/sh
2242 # Use env shell instead of default /bin/sh
2255 ec = subprocess.call(cmd, shell=True, executable=executable)
2243 ec = subprocess.call(cmd, shell=True, executable=executable)
2256 except KeyboardInterrupt:
2244 except KeyboardInterrupt:
2257 # intercept control-C; a long traceback is not useful here
2245 # intercept control-C; a long traceback is not useful here
2258 print('\n' + self.get_exception_only(), file=sys.stderr)
2246 print('\n' + self.get_exception_only(), file=sys.stderr)
2259 ec = 130
2247 ec = 130
2260 if ec > 128:
2248 if ec > 128:
2261 ec = -(ec - 128)
2249 ec = -(ec - 128)
2262
2250
2263 # We explicitly do NOT return the subprocess status code, because
2251 # We explicitly do NOT return the subprocess status code, because
2264 # a non-None value would trigger :func:`sys.displayhook` calls.
2252 # a non-None value would trigger :func:`sys.displayhook` calls.
2265 # Instead, we store the exit_code in user_ns. Note the semantics
2253 # Instead, we store the exit_code in user_ns. Note the semantics
2266 # of _exit_code: for control-c, _exit_code == -signal.SIGNIT,
2254 # of _exit_code: for control-c, _exit_code == -signal.SIGNIT,
2267 # but raising SystemExit(_exit_code) will give status 254!
2255 # but raising SystemExit(_exit_code) will give status 254!
2268 self.user_ns['_exit_code'] = ec
2256 self.user_ns['_exit_code'] = ec
2269
2257
2270 # use piped system by default, because it is better behaved
2258 # use piped system by default, because it is better behaved
2271 system = system_piped
2259 system = system_piped
2272
2260
2273 def getoutput(self, cmd, split=True, depth=0):
2261 def getoutput(self, cmd, split=True, depth=0):
2274 """Get output (possibly including stderr) from a subprocess.
2262 """Get output (possibly including stderr) from a subprocess.
2275
2263
2276 Parameters
2264 Parameters
2277 ----------
2265 ----------
2278 cmd : str
2266 cmd : str
2279 Command to execute (can not end in '&', as background processes are
2267 Command to execute (can not end in '&', as background processes are
2280 not supported.
2268 not supported.
2281 split : bool, optional
2269 split : bool, optional
2282 If True, split the output into an IPython SList. Otherwise, an
2270 If True, split the output into an IPython SList. Otherwise, an
2283 IPython LSString is returned. These are objects similar to normal
2271 IPython LSString is returned. These are objects similar to normal
2284 lists and strings, with a few convenience attributes for easier
2272 lists and strings, with a few convenience attributes for easier
2285 manipulation of line-based output. You can use '?' on them for
2273 manipulation of line-based output. You can use '?' on them for
2286 details.
2274 details.
2287 depth : int, optional
2275 depth : int, optional
2288 How many frames above the caller are the local variables which should
2276 How many frames above the caller are the local variables which should
2289 be expanded in the command string? The default (0) assumes that the
2277 be expanded in the command string? The default (0) assumes that the
2290 expansion variables are in the stack frame calling this function.
2278 expansion variables are in the stack frame calling this function.
2291 """
2279 """
2292 if cmd.rstrip().endswith('&'):
2280 if cmd.rstrip().endswith('&'):
2293 # this is *far* from a rigorous test
2281 # this is *far* from a rigorous test
2294 raise OSError("Background processes not supported.")
2282 raise OSError("Background processes not supported.")
2295 out = getoutput(self.var_expand(cmd, depth=depth+1))
2283 out = getoutput(self.var_expand(cmd, depth=depth+1))
2296 if split:
2284 if split:
2297 out = SList(out.splitlines())
2285 out = SList(out.splitlines())
2298 else:
2286 else:
2299 out = LSString(out)
2287 out = LSString(out)
2300 return out
2288 return out
2301
2289
2302 #-------------------------------------------------------------------------
2290 #-------------------------------------------------------------------------
2303 # Things related to aliases
2291 # Things related to aliases
2304 #-------------------------------------------------------------------------
2292 #-------------------------------------------------------------------------
2305
2293
2306 def init_alias(self):
2294 def init_alias(self):
2307 self.alias_manager = AliasManager(shell=self, parent=self)
2295 self.alias_manager = AliasManager(shell=self, parent=self)
2308 self.configurables.append(self.alias_manager)
2296 self.configurables.append(self.alias_manager)
2309
2297
2310 #-------------------------------------------------------------------------
2298 #-------------------------------------------------------------------------
2311 # Things related to extensions
2299 # Things related to extensions
2312 #-------------------------------------------------------------------------
2300 #-------------------------------------------------------------------------
2313
2301
2314 def init_extension_manager(self):
2302 def init_extension_manager(self):
2315 self.extension_manager = ExtensionManager(shell=self, parent=self)
2303 self.extension_manager = ExtensionManager(shell=self, parent=self)
2316 self.configurables.append(self.extension_manager)
2304 self.configurables.append(self.extension_manager)
2317
2305
2318 #-------------------------------------------------------------------------
2306 #-------------------------------------------------------------------------
2319 # Things related to payloads
2307 # Things related to payloads
2320 #-------------------------------------------------------------------------
2308 #-------------------------------------------------------------------------
2321
2309
2322 def init_payload(self):
2310 def init_payload(self):
2323 self.payload_manager = PayloadManager(parent=self)
2311 self.payload_manager = PayloadManager(parent=self)
2324 self.configurables.append(self.payload_manager)
2312 self.configurables.append(self.payload_manager)
2325
2313
2326 #-------------------------------------------------------------------------
2314 #-------------------------------------------------------------------------
2327 # Things related to the prefilter
2315 # Things related to the prefilter
2328 #-------------------------------------------------------------------------
2316 #-------------------------------------------------------------------------
2329
2317
2330 def init_prefilter(self):
2318 def init_prefilter(self):
2331 self.prefilter_manager = PrefilterManager(shell=self, parent=self)
2319 self.prefilter_manager = PrefilterManager(shell=self, parent=self)
2332 self.configurables.append(self.prefilter_manager)
2320 self.configurables.append(self.prefilter_manager)
2333 # Ultimately this will be refactored in the new interpreter code, but
2321 # Ultimately this will be refactored in the new interpreter code, but
2334 # for now, we should expose the main prefilter method (there's legacy
2322 # for now, we should expose the main prefilter method (there's legacy
2335 # code out there that may rely on this).
2323 # code out there that may rely on this).
2336 self.prefilter = self.prefilter_manager.prefilter_lines
2324 self.prefilter = self.prefilter_manager.prefilter_lines
2337
2325
2338 def auto_rewrite_input(self, cmd):
2326 def auto_rewrite_input(self, cmd):
2339 """Print to the screen the rewritten form of the user's command.
2327 """Print to the screen the rewritten form of the user's command.
2340
2328
2341 This shows visual feedback by rewriting input lines that cause
2329 This shows visual feedback by rewriting input lines that cause
2342 automatic calling to kick in, like::
2330 automatic calling to kick in, like::
2343
2331
2344 /f x
2332 /f x
2345
2333
2346 into::
2334 into::
2347
2335
2348 ------> f(x)
2336 ------> f(x)
2349
2337
2350 after the user's input prompt. This helps the user understand that the
2338 after the user's input prompt. This helps the user understand that the
2351 input line was transformed automatically by IPython.
2339 input line was transformed automatically by IPython.
2352 """
2340 """
2353 if not self.show_rewritten_input:
2341 if not self.show_rewritten_input:
2354 return
2342 return
2355
2343
2356 # This is overridden in TerminalInteractiveShell to use fancy prompts
2344 # This is overridden in TerminalInteractiveShell to use fancy prompts
2357 print("------> " + cmd)
2345 print("------> " + cmd)
2358
2346
2359 #-------------------------------------------------------------------------
2347 #-------------------------------------------------------------------------
2360 # Things related to extracting values/expressions from kernel and user_ns
2348 # Things related to extracting values/expressions from kernel and user_ns
2361 #-------------------------------------------------------------------------
2349 #-------------------------------------------------------------------------
2362
2350
2363 def _user_obj_error(self):
2351 def _user_obj_error(self):
2364 """return simple exception dict
2352 """return simple exception dict
2365
2353
2366 for use in user_expressions
2354 for use in user_expressions
2367 """
2355 """
2368
2356
2369 etype, evalue, tb = self._get_exc_info()
2357 etype, evalue, tb = self._get_exc_info()
2370 stb = self.InteractiveTB.get_exception_only(etype, evalue)
2358 stb = self.InteractiveTB.get_exception_only(etype, evalue)
2371
2359
2372 exc_info = {
2360 exc_info = {
2373 u'status' : 'error',
2361 u'status' : 'error',
2374 u'traceback' : stb,
2362 u'traceback' : stb,
2375 u'ename' : unicode_type(etype.__name__),
2363 u'ename' : unicode_type(etype.__name__),
2376 u'evalue' : py3compat.safe_unicode(evalue),
2364 u'evalue' : py3compat.safe_unicode(evalue),
2377 }
2365 }
2378
2366
2379 return exc_info
2367 return exc_info
2380
2368
2381 def _format_user_obj(self, obj):
2369 def _format_user_obj(self, obj):
2382 """format a user object to display dict
2370 """format a user object to display dict
2383
2371
2384 for use in user_expressions
2372 for use in user_expressions
2385 """
2373 """
2386
2374
2387 data, md = self.display_formatter.format(obj)
2375 data, md = self.display_formatter.format(obj)
2388 value = {
2376 value = {
2389 'status' : 'ok',
2377 'status' : 'ok',
2390 'data' : data,
2378 'data' : data,
2391 'metadata' : md,
2379 'metadata' : md,
2392 }
2380 }
2393 return value
2381 return value
2394
2382
2395 def user_expressions(self, expressions):
2383 def user_expressions(self, expressions):
2396 """Evaluate a dict of expressions in the user's namespace.
2384 """Evaluate a dict of expressions in the user's namespace.
2397
2385
2398 Parameters
2386 Parameters
2399 ----------
2387 ----------
2400 expressions : dict
2388 expressions : dict
2401 A dict with string keys and string values. The expression values
2389 A dict with string keys and string values. The expression values
2402 should be valid Python expressions, each of which will be evaluated
2390 should be valid Python expressions, each of which will be evaluated
2403 in the user namespace.
2391 in the user namespace.
2404
2392
2405 Returns
2393 Returns
2406 -------
2394 -------
2407 A dict, keyed like the input expressions dict, with the rich mime-typed
2395 A dict, keyed like the input expressions dict, with the rich mime-typed
2408 display_data of each value.
2396 display_data of each value.
2409 """
2397 """
2410 out = {}
2398 out = {}
2411 user_ns = self.user_ns
2399 user_ns = self.user_ns
2412 global_ns = self.user_global_ns
2400 global_ns = self.user_global_ns
2413
2401
2414 for key, expr in iteritems(expressions):
2402 for key, expr in iteritems(expressions):
2415 try:
2403 try:
2416 value = self._format_user_obj(eval(expr, global_ns, user_ns))
2404 value = self._format_user_obj(eval(expr, global_ns, user_ns))
2417 except:
2405 except:
2418 value = self._user_obj_error()
2406 value = self._user_obj_error()
2419 out[key] = value
2407 out[key] = value
2420 return out
2408 return out
2421
2409
2422 #-------------------------------------------------------------------------
2410 #-------------------------------------------------------------------------
2423 # Things related to the running of code
2411 # Things related to the running of code
2424 #-------------------------------------------------------------------------
2412 #-------------------------------------------------------------------------
2425
2413
2426 def ex(self, cmd):
2414 def ex(self, cmd):
2427 """Execute a normal python statement in user namespace."""
2415 """Execute a normal python statement in user namespace."""
2428 with self.builtin_trap:
2416 with self.builtin_trap:
2429 exec(cmd, self.user_global_ns, self.user_ns)
2417 exec(cmd, self.user_global_ns, self.user_ns)
2430
2418
2431 def ev(self, expr):
2419 def ev(self, expr):
2432 """Evaluate python expression expr in user namespace.
2420 """Evaluate python expression expr in user namespace.
2433
2421
2434 Returns the result of evaluation
2422 Returns the result of evaluation
2435 """
2423 """
2436 with self.builtin_trap:
2424 with self.builtin_trap:
2437 return eval(expr, self.user_global_ns, self.user_ns)
2425 return eval(expr, self.user_global_ns, self.user_ns)
2438
2426
2439 def safe_execfile(self, fname, *where, **kw):
2427 def safe_execfile(self, fname, *where, **kw):
2440 """A safe version of the builtin execfile().
2428 """A safe version of the builtin execfile().
2441
2429
2442 This version will never throw an exception, but instead print
2430 This version will never throw an exception, but instead print
2443 helpful error messages to the screen. This only works on pure
2431 helpful error messages to the screen. This only works on pure
2444 Python files with the .py extension.
2432 Python files with the .py extension.
2445
2433
2446 Parameters
2434 Parameters
2447 ----------
2435 ----------
2448 fname : string
2436 fname : string
2449 The name of the file to be executed.
2437 The name of the file to be executed.
2450 where : tuple
2438 where : tuple
2451 One or two namespaces, passed to execfile() as (globals,locals).
2439 One or two namespaces, passed to execfile() as (globals,locals).
2452 If only one is given, it is passed as both.
2440 If only one is given, it is passed as both.
2453 exit_ignore : bool (False)
2441 exit_ignore : bool (False)
2454 If True, then silence SystemExit for non-zero status (it is always
2442 If True, then silence SystemExit for non-zero status (it is always
2455 silenced for zero status, as it is so common).
2443 silenced for zero status, as it is so common).
2456 raise_exceptions : bool (False)
2444 raise_exceptions : bool (False)
2457 If True raise exceptions everywhere. Meant for testing.
2445 If True raise exceptions everywhere. Meant for testing.
2458 shell_futures : bool (False)
2446 shell_futures : bool (False)
2459 If True, the code will share future statements with the interactive
2447 If True, the code will share future statements with the interactive
2460 shell. It will both be affected by previous __future__ imports, and
2448 shell. It will both be affected by previous __future__ imports, and
2461 any __future__ imports in the code will affect the shell. If False,
2449 any __future__ imports in the code will affect the shell. If False,
2462 __future__ imports are not shared in either direction.
2450 __future__ imports are not shared in either direction.
2463
2451
2464 """
2452 """
2465 kw.setdefault('exit_ignore', False)
2453 kw.setdefault('exit_ignore', False)
2466 kw.setdefault('raise_exceptions', False)
2454 kw.setdefault('raise_exceptions', False)
2467 kw.setdefault('shell_futures', False)
2455 kw.setdefault('shell_futures', False)
2468
2456
2469 fname = os.path.abspath(os.path.expanduser(fname))
2457 fname = os.path.abspath(os.path.expanduser(fname))
2470
2458
2471 # Make sure we can open the file
2459 # Make sure we can open the file
2472 try:
2460 try:
2473 with open(fname):
2461 with open(fname):
2474 pass
2462 pass
2475 except:
2463 except:
2476 warn('Could not open file <%s> for safe execution.' % fname)
2464 warn('Could not open file <%s> for safe execution.' % fname)
2477 return
2465 return
2478
2466
2479 # Find things also in current directory. This is needed to mimic the
2467 # Find things also in current directory. This is needed to mimic the
2480 # behavior of running a script from the system command line, where
2468 # behavior of running a script from the system command line, where
2481 # Python inserts the script's directory into sys.path
2469 # Python inserts the script's directory into sys.path
2482 dname = os.path.dirname(fname)
2470 dname = os.path.dirname(fname)
2483
2471
2484 with prepended_to_syspath(dname):
2472 with prepended_to_syspath(dname):
2485 try:
2473 try:
2486 glob, loc = (where + (None, ))[:2]
2474 glob, loc = (where + (None, ))[:2]
2487 py3compat.execfile(
2475 py3compat.execfile(
2488 fname, glob, loc,
2476 fname, glob, loc,
2489 self.compile if kw['shell_futures'] else None)
2477 self.compile if kw['shell_futures'] else None)
2490 except SystemExit as status:
2478 except SystemExit as status:
2491 # If the call was made with 0 or None exit status (sys.exit(0)
2479 # If the call was made with 0 or None exit status (sys.exit(0)
2492 # or sys.exit() ), don't bother showing a traceback, as both of
2480 # or sys.exit() ), don't bother showing a traceback, as both of
2493 # these are considered normal by the OS:
2481 # these are considered normal by the OS:
2494 # > python -c'import sys;sys.exit(0)'; echo $?
2482 # > python -c'import sys;sys.exit(0)'; echo $?
2495 # 0
2483 # 0
2496 # > python -c'import sys;sys.exit()'; echo $?
2484 # > python -c'import sys;sys.exit()'; echo $?
2497 # 0
2485 # 0
2498 # For other exit status, we show the exception unless
2486 # For other exit status, we show the exception unless
2499 # explicitly silenced, but only in short form.
2487 # explicitly silenced, but only in short form.
2500 if status.code:
2488 if status.code:
2501 if kw['raise_exceptions']:
2489 if kw['raise_exceptions']:
2502 raise
2490 raise
2503 if not kw['exit_ignore']:
2491 if not kw['exit_ignore']:
2504 self.showtraceback(exception_only=True)
2492 self.showtraceback(exception_only=True)
2505 except:
2493 except:
2506 if kw['raise_exceptions']:
2494 if kw['raise_exceptions']:
2507 raise
2495 raise
2508 # tb offset is 2 because we wrap execfile
2496 # tb offset is 2 because we wrap execfile
2509 self.showtraceback(tb_offset=2)
2497 self.showtraceback(tb_offset=2)
2510
2498
2511 def safe_execfile_ipy(self, fname, shell_futures=False, raise_exceptions=False):
2499 def safe_execfile_ipy(self, fname, shell_futures=False, raise_exceptions=False):
2512 """Like safe_execfile, but for .ipy or .ipynb files with IPython syntax.
2500 """Like safe_execfile, but for .ipy or .ipynb files with IPython syntax.
2513
2501
2514 Parameters
2502 Parameters
2515 ----------
2503 ----------
2516 fname : str
2504 fname : str
2517 The name of the file to execute. The filename must have a
2505 The name of the file to execute. The filename must have a
2518 .ipy or .ipynb extension.
2506 .ipy or .ipynb extension.
2519 shell_futures : bool (False)
2507 shell_futures : bool (False)
2520 If True, the code will share future statements with the interactive
2508 If True, the code will share future statements with the interactive
2521 shell. It will both be affected by previous __future__ imports, and
2509 shell. It will both be affected by previous __future__ imports, and
2522 any __future__ imports in the code will affect the shell. If False,
2510 any __future__ imports in the code will affect the shell. If False,
2523 __future__ imports are not shared in either direction.
2511 __future__ imports are not shared in either direction.
2524 raise_exceptions : bool (False)
2512 raise_exceptions : bool (False)
2525 If True raise exceptions everywhere. Meant for testing.
2513 If True raise exceptions everywhere. Meant for testing.
2526 """
2514 """
2527 fname = os.path.abspath(os.path.expanduser(fname))
2515 fname = os.path.abspath(os.path.expanduser(fname))
2528
2516
2529 # Make sure we can open the file
2517 # Make sure we can open the file
2530 try:
2518 try:
2531 with open(fname):
2519 with open(fname):
2532 pass
2520 pass
2533 except:
2521 except:
2534 warn('Could not open file <%s> for safe execution.' % fname)
2522 warn('Could not open file <%s> for safe execution.' % fname)
2535 return
2523 return
2536
2524
2537 # Find things also in current directory. This is needed to mimic the
2525 # Find things also in current directory. This is needed to mimic the
2538 # behavior of running a script from the system command line, where
2526 # behavior of running a script from the system command line, where
2539 # Python inserts the script's directory into sys.path
2527 # Python inserts the script's directory into sys.path
2540 dname = os.path.dirname(fname)
2528 dname = os.path.dirname(fname)
2541
2529
2542 def get_cells():
2530 def get_cells():
2543 """generator for sequence of code blocks to run"""
2531 """generator for sequence of code blocks to run"""
2544 if fname.endswith('.ipynb'):
2532 if fname.endswith('.ipynb'):
2545 from nbformat import read
2533 from nbformat import read
2546 with io_open(fname) as f:
2534 with io_open(fname) as f:
2547 nb = read(f, as_version=4)
2535 nb = read(f, as_version=4)
2548 if not nb.cells:
2536 if not nb.cells:
2549 return
2537 return
2550 for cell in nb.cells:
2538 for cell in nb.cells:
2551 if cell.cell_type == 'code':
2539 if cell.cell_type == 'code':
2552 yield cell.source
2540 yield cell.source
2553 else:
2541 else:
2554 with open(fname) as f:
2542 with open(fname) as f:
2555 yield f.read()
2543 yield f.read()
2556
2544
2557 with prepended_to_syspath(dname):
2545 with prepended_to_syspath(dname):
2558 try:
2546 try:
2559 for cell in get_cells():
2547 for cell in get_cells():
2560 result = self.run_cell(cell, silent=True, shell_futures=shell_futures)
2548 result = self.run_cell(cell, silent=True, shell_futures=shell_futures)
2561 if raise_exceptions:
2549 if raise_exceptions:
2562 result.raise_error()
2550 result.raise_error()
2563 elif not result.success:
2551 elif not result.success:
2564 break
2552 break
2565 except:
2553 except:
2566 if raise_exceptions:
2554 if raise_exceptions:
2567 raise
2555 raise
2568 self.showtraceback()
2556 self.showtraceback()
2569 warn('Unknown failure executing file: <%s>' % fname)
2557 warn('Unknown failure executing file: <%s>' % fname)
2570
2558
2571 def safe_run_module(self, mod_name, where):
2559 def safe_run_module(self, mod_name, where):
2572 """A safe version of runpy.run_module().
2560 """A safe version of runpy.run_module().
2573
2561
2574 This version will never throw an exception, but instead print
2562 This version will never throw an exception, but instead print
2575 helpful error messages to the screen.
2563 helpful error messages to the screen.
2576
2564
2577 `SystemExit` exceptions with status code 0 or None are ignored.
2565 `SystemExit` exceptions with status code 0 or None are ignored.
2578
2566
2579 Parameters
2567 Parameters
2580 ----------
2568 ----------
2581 mod_name : string
2569 mod_name : string
2582 The name of the module to be executed.
2570 The name of the module to be executed.
2583 where : dict
2571 where : dict
2584 The globals namespace.
2572 The globals namespace.
2585 """
2573 """
2586 try:
2574 try:
2587 try:
2575 try:
2588 where.update(
2576 where.update(
2589 runpy.run_module(str(mod_name), run_name="__main__",
2577 runpy.run_module(str(mod_name), run_name="__main__",
2590 alter_sys=True)
2578 alter_sys=True)
2591 )
2579 )
2592 except SystemExit as status:
2580 except SystemExit as status:
2593 if status.code:
2581 if status.code:
2594 raise
2582 raise
2595 except:
2583 except:
2596 self.showtraceback()
2584 self.showtraceback()
2597 warn('Unknown failure executing module: <%s>' % mod_name)
2585 warn('Unknown failure executing module: <%s>' % mod_name)
2598
2586
2599 def run_cell(self, raw_cell, store_history=False, silent=False, shell_futures=True):
2587 def run_cell(self, raw_cell, store_history=False, silent=False, shell_futures=True):
2600 """Run a complete IPython cell.
2588 """Run a complete IPython cell.
2601
2589
2602 Parameters
2590 Parameters
2603 ----------
2591 ----------
2604 raw_cell : str
2592 raw_cell : str
2605 The code (including IPython code such as %magic functions) to run.
2593 The code (including IPython code such as %magic functions) to run.
2606 store_history : bool
2594 store_history : bool
2607 If True, the raw and translated cell will be stored in IPython's
2595 If True, the raw and translated cell will be stored in IPython's
2608 history. For user code calling back into IPython's machinery, this
2596 history. For user code calling back into IPython's machinery, this
2609 should be set to False.
2597 should be set to False.
2610 silent : bool
2598 silent : bool
2611 If True, avoid side-effects, such as implicit displayhooks and
2599 If True, avoid side-effects, such as implicit displayhooks and
2612 and logging. silent=True forces store_history=False.
2600 and logging. silent=True forces store_history=False.
2613 shell_futures : bool
2601 shell_futures : bool
2614 If True, the code will share future statements with the interactive
2602 If True, the code will share future statements with the interactive
2615 shell. It will both be affected by previous __future__ imports, and
2603 shell. It will both be affected by previous __future__ imports, and
2616 any __future__ imports in the code will affect the shell. If False,
2604 any __future__ imports in the code will affect the shell. If False,
2617 __future__ imports are not shared in either direction.
2605 __future__ imports are not shared in either direction.
2618
2606
2619 Returns
2607 Returns
2620 -------
2608 -------
2621 result : :class:`ExecutionResult`
2609 result : :class:`ExecutionResult`
2622 """
2610 """
2623 result = ExecutionResult()
2611 result = ExecutionResult()
2624
2612
2625 if (not raw_cell) or raw_cell.isspace():
2613 if (not raw_cell) or raw_cell.isspace():
2626 self.last_execution_succeeded = True
2614 self.last_execution_succeeded = True
2627 return result
2615 return result
2628
2616
2629 if silent:
2617 if silent:
2630 store_history = False
2618 store_history = False
2631
2619
2632 if store_history:
2620 if store_history:
2633 result.execution_count = self.execution_count
2621 result.execution_count = self.execution_count
2634
2622
2635 def error_before_exec(value):
2623 def error_before_exec(value):
2636 result.error_before_exec = value
2624 result.error_before_exec = value
2637 self.last_execution_succeeded = False
2625 self.last_execution_succeeded = False
2638 return result
2626 return result
2639
2627
2640 self.events.trigger('pre_execute')
2628 self.events.trigger('pre_execute')
2641 if not silent:
2629 if not silent:
2642 self.events.trigger('pre_run_cell')
2630 self.events.trigger('pre_run_cell')
2643
2631
2644 # If any of our input transformation (input_transformer_manager or
2632 # If any of our input transformation (input_transformer_manager or
2645 # prefilter_manager) raises an exception, we store it in this variable
2633 # prefilter_manager) raises an exception, we store it in this variable
2646 # so that we can display the error after logging the input and storing
2634 # so that we can display the error after logging the input and storing
2647 # it in the history.
2635 # it in the history.
2648 preprocessing_exc_tuple = None
2636 preprocessing_exc_tuple = None
2649 try:
2637 try:
2650 # Static input transformations
2638 # Static input transformations
2651 cell = self.input_transformer_manager.transform_cell(raw_cell)
2639 cell = self.input_transformer_manager.transform_cell(raw_cell)
2652 except SyntaxError:
2640 except SyntaxError:
2653 preprocessing_exc_tuple = sys.exc_info()
2641 preprocessing_exc_tuple = sys.exc_info()
2654 cell = raw_cell # cell has to exist so it can be stored/logged
2642 cell = raw_cell # cell has to exist so it can be stored/logged
2655 else:
2643 else:
2656 if len(cell.splitlines()) == 1:
2644 if len(cell.splitlines()) == 1:
2657 # Dynamic transformations - only applied for single line commands
2645 # Dynamic transformations - only applied for single line commands
2658 with self.builtin_trap:
2646 with self.builtin_trap:
2659 try:
2647 try:
2660 # use prefilter_lines to handle trailing newlines
2648 # use prefilter_lines to handle trailing newlines
2661 # restore trailing newline for ast.parse
2649 # restore trailing newline for ast.parse
2662 cell = self.prefilter_manager.prefilter_lines(cell) + '\n'
2650 cell = self.prefilter_manager.prefilter_lines(cell) + '\n'
2663 except Exception:
2651 except Exception:
2664 # don't allow prefilter errors to crash IPython
2652 # don't allow prefilter errors to crash IPython
2665 preprocessing_exc_tuple = sys.exc_info()
2653 preprocessing_exc_tuple = sys.exc_info()
2666
2654
2667 # Store raw and processed history
2655 # Store raw and processed history
2668 if store_history:
2656 if store_history:
2669 self.history_manager.store_inputs(self.execution_count,
2657 self.history_manager.store_inputs(self.execution_count,
2670 cell, raw_cell)
2658 cell, raw_cell)
2671 if not silent:
2659 if not silent:
2672 self.logger.log(cell, raw_cell)
2660 self.logger.log(cell, raw_cell)
2673
2661
2674 # Display the exception if input processing failed.
2662 # Display the exception if input processing failed.
2675 if preprocessing_exc_tuple is not None:
2663 if preprocessing_exc_tuple is not None:
2676 self.showtraceback(preprocessing_exc_tuple)
2664 self.showtraceback(preprocessing_exc_tuple)
2677 if store_history:
2665 if store_history:
2678 self.execution_count += 1
2666 self.execution_count += 1
2679 return error_before_exec(preprocessing_exc_tuple[2])
2667 return error_before_exec(preprocessing_exc_tuple[2])
2680
2668
2681 # Our own compiler remembers the __future__ environment. If we want to
2669 # Our own compiler remembers the __future__ environment. If we want to
2682 # run code with a separate __future__ environment, use the default
2670 # run code with a separate __future__ environment, use the default
2683 # compiler
2671 # compiler
2684 compiler = self.compile if shell_futures else CachingCompiler()
2672 compiler = self.compile if shell_futures else CachingCompiler()
2685
2673
2686 with self.builtin_trap:
2674 with self.builtin_trap:
2687 cell_name = self.compile.cache(cell, self.execution_count)
2675 cell_name = self.compile.cache(cell, self.execution_count)
2688
2676
2689 with self.display_trap:
2677 with self.display_trap:
2690 # Compile to bytecode
2678 # Compile to bytecode
2691 try:
2679 try:
2692 code_ast = compiler.ast_parse(cell, filename=cell_name)
2680 code_ast = compiler.ast_parse(cell, filename=cell_name)
2693 except self.custom_exceptions as e:
2681 except self.custom_exceptions as e:
2694 etype, value, tb = sys.exc_info()
2682 etype, value, tb = sys.exc_info()
2695 self.CustomTB(etype, value, tb)
2683 self.CustomTB(etype, value, tb)
2696 return error_before_exec(e)
2684 return error_before_exec(e)
2697 except IndentationError as e:
2685 except IndentationError as e:
2698 self.showindentationerror()
2686 self.showindentationerror()
2699 if store_history:
2687 if store_history:
2700 self.execution_count += 1
2688 self.execution_count += 1
2701 return error_before_exec(e)
2689 return error_before_exec(e)
2702 except (OverflowError, SyntaxError, ValueError, TypeError,
2690 except (OverflowError, SyntaxError, ValueError, TypeError,
2703 MemoryError) as e:
2691 MemoryError) as e:
2704 self.showsyntaxerror()
2692 self.showsyntaxerror()
2705 if store_history:
2693 if store_history:
2706 self.execution_count += 1
2694 self.execution_count += 1
2707 return error_before_exec(e)
2695 return error_before_exec(e)
2708
2696
2709 # Apply AST transformations
2697 # Apply AST transformations
2710 try:
2698 try:
2711 code_ast = self.transform_ast(code_ast)
2699 code_ast = self.transform_ast(code_ast)
2712 except InputRejected as e:
2700 except InputRejected as e:
2713 self.showtraceback()
2701 self.showtraceback()
2714 if store_history:
2702 if store_history:
2715 self.execution_count += 1
2703 self.execution_count += 1
2716 return error_before_exec(e)
2704 return error_before_exec(e)
2717
2705
2718 # Give the displayhook a reference to our ExecutionResult so it
2706 # Give the displayhook a reference to our ExecutionResult so it
2719 # can fill in the output value.
2707 # can fill in the output value.
2720 self.displayhook.exec_result = result
2708 self.displayhook.exec_result = result
2721
2709
2722 # Execute the user code
2710 # Execute the user code
2723 interactivity = "none" if silent else self.ast_node_interactivity
2711 interactivity = "none" if silent else self.ast_node_interactivity
2724 has_raised = self.run_ast_nodes(code_ast.body, cell_name,
2712 has_raised = self.run_ast_nodes(code_ast.body, cell_name,
2725 interactivity=interactivity, compiler=compiler, result=result)
2713 interactivity=interactivity, compiler=compiler, result=result)
2726
2714
2727 self.last_execution_succeeded = not has_raised
2715 self.last_execution_succeeded = not has_raised
2728
2716
2729 # Reset this so later displayed values do not modify the
2717 # Reset this so later displayed values do not modify the
2730 # ExecutionResult
2718 # ExecutionResult
2731 self.displayhook.exec_result = None
2719 self.displayhook.exec_result = None
2732
2720
2733 self.events.trigger('post_execute')
2721 self.events.trigger('post_execute')
2734 if not silent:
2722 if not silent:
2735 self.events.trigger('post_run_cell')
2723 self.events.trigger('post_run_cell')
2736
2724
2737 if store_history:
2725 if store_history:
2738 # Write output to the database. Does nothing unless
2726 # Write output to the database. Does nothing unless
2739 # history output logging is enabled.
2727 # history output logging is enabled.
2740 self.history_manager.store_output(self.execution_count)
2728 self.history_manager.store_output(self.execution_count)
2741 # Each cell is a *single* input, regardless of how many lines it has
2729 # Each cell is a *single* input, regardless of how many lines it has
2742 self.execution_count += 1
2730 self.execution_count += 1
2743
2731
2744 return result
2732 return result
2745
2733
2746 def transform_ast(self, node):
2734 def transform_ast(self, node):
2747 """Apply the AST transformations from self.ast_transformers
2735 """Apply the AST transformations from self.ast_transformers
2748
2736
2749 Parameters
2737 Parameters
2750 ----------
2738 ----------
2751 node : ast.Node
2739 node : ast.Node
2752 The root node to be transformed. Typically called with the ast.Module
2740 The root node to be transformed. Typically called with the ast.Module
2753 produced by parsing user input.
2741 produced by parsing user input.
2754
2742
2755 Returns
2743 Returns
2756 -------
2744 -------
2757 An ast.Node corresponding to the node it was called with. Note that it
2745 An ast.Node corresponding to the node it was called with. Note that it
2758 may also modify the passed object, so don't rely on references to the
2746 may also modify the passed object, so don't rely on references to the
2759 original AST.
2747 original AST.
2760 """
2748 """
2761 for transformer in self.ast_transformers:
2749 for transformer in self.ast_transformers:
2762 try:
2750 try:
2763 node = transformer.visit(node)
2751 node = transformer.visit(node)
2764 except InputRejected:
2752 except InputRejected:
2765 # User-supplied AST transformers can reject an input by raising
2753 # User-supplied AST transformers can reject an input by raising
2766 # an InputRejected. Short-circuit in this case so that we
2754 # an InputRejected. Short-circuit in this case so that we
2767 # don't unregister the transform.
2755 # don't unregister the transform.
2768 raise
2756 raise
2769 except Exception:
2757 except Exception:
2770 warn("AST transformer %r threw an error. It will be unregistered." % transformer)
2758 warn("AST transformer %r threw an error. It will be unregistered." % transformer)
2771 self.ast_transformers.remove(transformer)
2759 self.ast_transformers.remove(transformer)
2772
2760
2773 if self.ast_transformers:
2761 if self.ast_transformers:
2774 ast.fix_missing_locations(node)
2762 ast.fix_missing_locations(node)
2775 return node
2763 return node
2776
2764
2777
2765
2778 def run_ast_nodes(self, nodelist, cell_name, interactivity='last_expr',
2766 def run_ast_nodes(self, nodelist, cell_name, interactivity='last_expr',
2779 compiler=compile, result=None):
2767 compiler=compile, result=None):
2780 """Run a sequence of AST nodes. The execution mode depends on the
2768 """Run a sequence of AST nodes. The execution mode depends on the
2781 interactivity parameter.
2769 interactivity parameter.
2782
2770
2783 Parameters
2771 Parameters
2784 ----------
2772 ----------
2785 nodelist : list
2773 nodelist : list
2786 A sequence of AST nodes to run.
2774 A sequence of AST nodes to run.
2787 cell_name : str
2775 cell_name : str
2788 Will be passed to the compiler as the filename of the cell. Typically
2776 Will be passed to the compiler as the filename of the cell. Typically
2789 the value returned by ip.compile.cache(cell).
2777 the value returned by ip.compile.cache(cell).
2790 interactivity : str
2778 interactivity : str
2791 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
2779 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
2792 run interactively (displaying output from expressions). 'last_expr'
2780 run interactively (displaying output from expressions). 'last_expr'
2793 will run the last node interactively only if it is an expression (i.e.
2781 will run the last node interactively only if it is an expression (i.e.
2794 expressions in loops or other blocks are not displayed. Other values
2782 expressions in loops or other blocks are not displayed. Other values
2795 for this parameter will raise a ValueError.
2783 for this parameter will raise a ValueError.
2796 compiler : callable
2784 compiler : callable
2797 A function with the same interface as the built-in compile(), to turn
2785 A function with the same interface as the built-in compile(), to turn
2798 the AST nodes into code objects. Default is the built-in compile().
2786 the AST nodes into code objects. Default is the built-in compile().
2799 result : ExecutionResult, optional
2787 result : ExecutionResult, optional
2800 An object to store exceptions that occur during execution.
2788 An object to store exceptions that occur during execution.
2801
2789
2802 Returns
2790 Returns
2803 -------
2791 -------
2804 True if an exception occurred while running code, False if it finished
2792 True if an exception occurred while running code, False if it finished
2805 running.
2793 running.
2806 """
2794 """
2807 if not nodelist:
2795 if not nodelist:
2808 return
2796 return
2809
2797
2810 if interactivity == 'last_expr':
2798 if interactivity == 'last_expr':
2811 if isinstance(nodelist[-1], ast.Expr):
2799 if isinstance(nodelist[-1], ast.Expr):
2812 interactivity = "last"
2800 interactivity = "last"
2813 else:
2801 else:
2814 interactivity = "none"
2802 interactivity = "none"
2815
2803
2816 if interactivity == 'none':
2804 if interactivity == 'none':
2817 to_run_exec, to_run_interactive = nodelist, []
2805 to_run_exec, to_run_interactive = nodelist, []
2818 elif interactivity == 'last':
2806 elif interactivity == 'last':
2819 to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:]
2807 to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:]
2820 elif interactivity == 'all':
2808 elif interactivity == 'all':
2821 to_run_exec, to_run_interactive = [], nodelist
2809 to_run_exec, to_run_interactive = [], nodelist
2822 else:
2810 else:
2823 raise ValueError("Interactivity was %r" % interactivity)
2811 raise ValueError("Interactivity was %r" % interactivity)
2824
2812
2825 try:
2813 try:
2826 for i, node in enumerate(to_run_exec):
2814 for i, node in enumerate(to_run_exec):
2827 mod = ast.Module([node])
2815 mod = ast.Module([node])
2828 code = compiler(mod, cell_name, "exec")
2816 code = compiler(mod, cell_name, "exec")
2829 if self.run_code(code, result):
2817 if self.run_code(code, result):
2830 return True
2818 return True
2831
2819
2832 for i, node in enumerate(to_run_interactive):
2820 for i, node in enumerate(to_run_interactive):
2833 mod = ast.Interactive([node])
2821 mod = ast.Interactive([node])
2834 code = compiler(mod, cell_name, "single")
2822 code = compiler(mod, cell_name, "single")
2835 if self.run_code(code, result):
2823 if self.run_code(code, result):
2836 return True
2824 return True
2837
2825
2838 # Flush softspace
2826 # Flush softspace
2839 if softspace(sys.stdout, 0):
2827 if softspace(sys.stdout, 0):
2840 print()
2828 print()
2841
2829
2842 except:
2830 except:
2843 # It's possible to have exceptions raised here, typically by
2831 # It's possible to have exceptions raised here, typically by
2844 # compilation of odd code (such as a naked 'return' outside a
2832 # compilation of odd code (such as a naked 'return' outside a
2845 # function) that did parse but isn't valid. Typically the exception
2833 # function) that did parse but isn't valid. Typically the exception
2846 # is a SyntaxError, but it's safest just to catch anything and show
2834 # is a SyntaxError, but it's safest just to catch anything and show
2847 # the user a traceback.
2835 # the user a traceback.
2848
2836
2849 # We do only one try/except outside the loop to minimize the impact
2837 # We do only one try/except outside the loop to minimize the impact
2850 # on runtime, and also because if any node in the node list is
2838 # on runtime, and also because if any node in the node list is
2851 # broken, we should stop execution completely.
2839 # broken, we should stop execution completely.
2852 if result:
2840 if result:
2853 result.error_before_exec = sys.exc_info()[1]
2841 result.error_before_exec = sys.exc_info()[1]
2854 self.showtraceback()
2842 self.showtraceback()
2855 return True
2843 return True
2856
2844
2857 return False
2845 return False
2858
2846
2859 def run_code(self, code_obj, result=None):
2847 def run_code(self, code_obj, result=None):
2860 """Execute a code object.
2848 """Execute a code object.
2861
2849
2862 When an exception occurs, self.showtraceback() is called to display a
2850 When an exception occurs, self.showtraceback() is called to display a
2863 traceback.
2851 traceback.
2864
2852
2865 Parameters
2853 Parameters
2866 ----------
2854 ----------
2867 code_obj : code object
2855 code_obj : code object
2868 A compiled code object, to be executed
2856 A compiled code object, to be executed
2869 result : ExecutionResult, optional
2857 result : ExecutionResult, optional
2870 An object to store exceptions that occur during execution.
2858 An object to store exceptions that occur during execution.
2871
2859
2872 Returns
2860 Returns
2873 -------
2861 -------
2874 False : successful execution.
2862 False : successful execution.
2875 True : an error occurred.
2863 True : an error occurred.
2876 """
2864 """
2877 # Set our own excepthook in case the user code tries to call it
2865 # Set our own excepthook in case the user code tries to call it
2878 # directly, so that the IPython crash handler doesn't get triggered
2866 # directly, so that the IPython crash handler doesn't get triggered
2879 old_excepthook, sys.excepthook = sys.excepthook, self.excepthook
2867 old_excepthook, sys.excepthook = sys.excepthook, self.excepthook
2880
2868
2881 # we save the original sys.excepthook in the instance, in case config
2869 # we save the original sys.excepthook in the instance, in case config
2882 # code (such as magics) needs access to it.
2870 # code (such as magics) needs access to it.
2883 self.sys_excepthook = old_excepthook
2871 self.sys_excepthook = old_excepthook
2884 outflag = 1 # happens in more places, so it's easier as default
2872 outflag = 1 # happens in more places, so it's easier as default
2885 try:
2873 try:
2886 try:
2874 try:
2887 self.hooks.pre_run_code_hook()
2875 self.hooks.pre_run_code_hook()
2888 #rprint('Running code', repr(code_obj)) # dbg
2876 #rprint('Running code', repr(code_obj)) # dbg
2889 exec(code_obj, self.user_global_ns, self.user_ns)
2877 exec(code_obj, self.user_global_ns, self.user_ns)
2890 finally:
2878 finally:
2891 # Reset our crash handler in place
2879 # Reset our crash handler in place
2892 sys.excepthook = old_excepthook
2880 sys.excepthook = old_excepthook
2893 except SystemExit as e:
2881 except SystemExit as e:
2894 if result is not None:
2882 if result is not None:
2895 result.error_in_exec = e
2883 result.error_in_exec = e
2896 self.showtraceback(exception_only=True)
2884 self.showtraceback(exception_only=True)
2897 warn("To exit: use 'exit', 'quit', or Ctrl-D.", level=1)
2885 warn("To exit: use 'exit', 'quit', or Ctrl-D.", level=1)
2898 except self.custom_exceptions:
2886 except self.custom_exceptions:
2899 etype, value, tb = sys.exc_info()
2887 etype, value, tb = sys.exc_info()
2900 if result is not None:
2888 if result is not None:
2901 result.error_in_exec = value
2889 result.error_in_exec = value
2902 self.CustomTB(etype, value, tb)
2890 self.CustomTB(etype, value, tb)
2903 except:
2891 except:
2904 if result is not None:
2892 if result is not None:
2905 result.error_in_exec = sys.exc_info()[1]
2893 result.error_in_exec = sys.exc_info()[1]
2906 self.showtraceback()
2894 self.showtraceback()
2907 else:
2895 else:
2908 outflag = 0
2896 outflag = 0
2909 return outflag
2897 return outflag
2910
2898
2911 # For backwards compatibility
2899 # For backwards compatibility
2912 runcode = run_code
2900 runcode = run_code
2913
2901
2914 #-------------------------------------------------------------------------
2902 #-------------------------------------------------------------------------
2915 # Things related to GUI support and pylab
2903 # Things related to GUI support and pylab
2916 #-------------------------------------------------------------------------
2904 #-------------------------------------------------------------------------
2917
2905
2918 def enable_gui(self, gui=None):
2906 def enable_gui(self, gui=None):
2919 raise NotImplementedError('Implement enable_gui in a subclass')
2907 raise NotImplementedError('Implement enable_gui in a subclass')
2920
2908
2921 def enable_matplotlib(self, gui=None):
2909 def enable_matplotlib(self, gui=None):
2922 """Enable interactive matplotlib and inline figure support.
2910 """Enable interactive matplotlib and inline figure support.
2923
2911
2924 This takes the following steps:
2912 This takes the following steps:
2925
2913
2926 1. select the appropriate eventloop and matplotlib backend
2914 1. select the appropriate eventloop and matplotlib backend
2927 2. set up matplotlib for interactive use with that backend
2915 2. set up matplotlib for interactive use with that backend
2928 3. configure formatters for inline figure display
2916 3. configure formatters for inline figure display
2929 4. enable the selected gui eventloop
2917 4. enable the selected gui eventloop
2930
2918
2931 Parameters
2919 Parameters
2932 ----------
2920 ----------
2933 gui : optional, string
2921 gui : optional, string
2934 If given, dictates the choice of matplotlib GUI backend to use
2922 If given, dictates the choice of matplotlib GUI backend to use
2935 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
2923 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
2936 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
2924 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
2937 matplotlib (as dictated by the matplotlib build-time options plus the
2925 matplotlib (as dictated by the matplotlib build-time options plus the
2938 user's matplotlibrc configuration file). Note that not all backends
2926 user's matplotlibrc configuration file). Note that not all backends
2939 make sense in all contexts, for example a terminal ipython can't
2927 make sense in all contexts, for example a terminal ipython can't
2940 display figures inline.
2928 display figures inline.
2941 """
2929 """
2942 from IPython.core import pylabtools as pt
2930 from IPython.core import pylabtools as pt
2943 gui, backend = pt.find_gui_and_backend(gui, self.pylab_gui_select)
2931 gui, backend = pt.find_gui_and_backend(gui, self.pylab_gui_select)
2944
2932
2945 if gui != 'inline':
2933 if gui != 'inline':
2946 # If we have our first gui selection, store it
2934 # If we have our first gui selection, store it
2947 if self.pylab_gui_select is None:
2935 if self.pylab_gui_select is None:
2948 self.pylab_gui_select = gui
2936 self.pylab_gui_select = gui
2949 # Otherwise if they are different
2937 # Otherwise if they are different
2950 elif gui != self.pylab_gui_select:
2938 elif gui != self.pylab_gui_select:
2951 print ('Warning: Cannot change to a different GUI toolkit: %s.'
2939 print ('Warning: Cannot change to a different GUI toolkit: %s.'
2952 ' Using %s instead.' % (gui, self.pylab_gui_select))
2940 ' Using %s instead.' % (gui, self.pylab_gui_select))
2953 gui, backend = pt.find_gui_and_backend(self.pylab_gui_select)
2941 gui, backend = pt.find_gui_and_backend(self.pylab_gui_select)
2954
2942
2955 pt.activate_matplotlib(backend)
2943 pt.activate_matplotlib(backend)
2956 pt.configure_inline_support(self, backend)
2944 pt.configure_inline_support(self, backend)
2957
2945
2958 # Now we must activate the gui pylab wants to use, and fix %run to take
2946 # Now we must activate the gui pylab wants to use, and fix %run to take
2959 # plot updates into account
2947 # plot updates into account
2960 self.enable_gui(gui)
2948 self.enable_gui(gui)
2961 self.magics_manager.registry['ExecutionMagics'].default_runner = \
2949 self.magics_manager.registry['ExecutionMagics'].default_runner = \
2962 pt.mpl_runner(self.safe_execfile)
2950 pt.mpl_runner(self.safe_execfile)
2963
2951
2964 return gui, backend
2952 return gui, backend
2965
2953
2966 def enable_pylab(self, gui=None, import_all=True, welcome_message=False):
2954 def enable_pylab(self, gui=None, import_all=True, welcome_message=False):
2967 """Activate pylab support at runtime.
2955 """Activate pylab support at runtime.
2968
2956
2969 This turns on support for matplotlib, preloads into the interactive
2957 This turns on support for matplotlib, preloads into the interactive
2970 namespace all of numpy and pylab, and configures IPython to correctly
2958 namespace all of numpy and pylab, and configures IPython to correctly
2971 interact with the GUI event loop. The GUI backend to be used can be
2959 interact with the GUI event loop. The GUI backend to be used can be
2972 optionally selected with the optional ``gui`` argument.
2960 optionally selected with the optional ``gui`` argument.
2973
2961
2974 This method only adds preloading the namespace to InteractiveShell.enable_matplotlib.
2962 This method only adds preloading the namespace to InteractiveShell.enable_matplotlib.
2975
2963
2976 Parameters
2964 Parameters
2977 ----------
2965 ----------
2978 gui : optional, string
2966 gui : optional, string
2979 If given, dictates the choice of matplotlib GUI backend to use
2967 If given, dictates the choice of matplotlib GUI backend to use
2980 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
2968 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
2981 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
2969 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
2982 matplotlib (as dictated by the matplotlib build-time options plus the
2970 matplotlib (as dictated by the matplotlib build-time options plus the
2983 user's matplotlibrc configuration file). Note that not all backends
2971 user's matplotlibrc configuration file). Note that not all backends
2984 make sense in all contexts, for example a terminal ipython can't
2972 make sense in all contexts, for example a terminal ipython can't
2985 display figures inline.
2973 display figures inline.
2986 import_all : optional, bool, default: True
2974 import_all : optional, bool, default: True
2987 Whether to do `from numpy import *` and `from pylab import *`
2975 Whether to do `from numpy import *` and `from pylab import *`
2988 in addition to module imports.
2976 in addition to module imports.
2989 welcome_message : deprecated
2977 welcome_message : deprecated
2990 This argument is ignored, no welcome message will be displayed.
2978 This argument is ignored, no welcome message will be displayed.
2991 """
2979 """
2992 from IPython.core.pylabtools import import_pylab
2980 from IPython.core.pylabtools import import_pylab
2993
2981
2994 gui, backend = self.enable_matplotlib(gui)
2982 gui, backend = self.enable_matplotlib(gui)
2995
2983
2996 # We want to prevent the loading of pylab to pollute the user's
2984 # We want to prevent the loading of pylab to pollute the user's
2997 # namespace as shown by the %who* magics, so we execute the activation
2985 # namespace as shown by the %who* magics, so we execute the activation
2998 # code in an empty namespace, and we update *both* user_ns and
2986 # code in an empty namespace, and we update *both* user_ns and
2999 # user_ns_hidden with this information.
2987 # user_ns_hidden with this information.
3000 ns = {}
2988 ns = {}
3001 import_pylab(ns, import_all)
2989 import_pylab(ns, import_all)
3002 # warn about clobbered names
2990 # warn about clobbered names
3003 ignored = {"__builtins__"}
2991 ignored = {"__builtins__"}
3004 both = set(ns).intersection(self.user_ns).difference(ignored)
2992 both = set(ns).intersection(self.user_ns).difference(ignored)
3005 clobbered = [ name for name in both if self.user_ns[name] is not ns[name] ]
2993 clobbered = [ name for name in both if self.user_ns[name] is not ns[name] ]
3006 self.user_ns.update(ns)
2994 self.user_ns.update(ns)
3007 self.user_ns_hidden.update(ns)
2995 self.user_ns_hidden.update(ns)
3008 return gui, backend, clobbered
2996 return gui, backend, clobbered
3009
2997
3010 #-------------------------------------------------------------------------
2998 #-------------------------------------------------------------------------
3011 # Utilities
2999 # Utilities
3012 #-------------------------------------------------------------------------
3000 #-------------------------------------------------------------------------
3013
3001
3014 def var_expand(self, cmd, depth=0, formatter=DollarFormatter()):
3002 def var_expand(self, cmd, depth=0, formatter=DollarFormatter()):
3015 """Expand python variables in a string.
3003 """Expand python variables in a string.
3016
3004
3017 The depth argument indicates how many frames above the caller should
3005 The depth argument indicates how many frames above the caller should
3018 be walked to look for the local namespace where to expand variables.
3006 be walked to look for the local namespace where to expand variables.
3019
3007
3020 The global namespace for expansion is always the user's interactive
3008 The global namespace for expansion is always the user's interactive
3021 namespace.
3009 namespace.
3022 """
3010 """
3023 ns = self.user_ns.copy()
3011 ns = self.user_ns.copy()
3024 try:
3012 try:
3025 frame = sys._getframe(depth+1)
3013 frame = sys._getframe(depth+1)
3026 except ValueError:
3014 except ValueError:
3027 # This is thrown if there aren't that many frames on the stack,
3015 # This is thrown if there aren't that many frames on the stack,
3028 # e.g. if a script called run_line_magic() directly.
3016 # e.g. if a script called run_line_magic() directly.
3029 pass
3017 pass
3030 else:
3018 else:
3031 ns.update(frame.f_locals)
3019 ns.update(frame.f_locals)
3032
3020
3033 try:
3021 try:
3034 # We have to use .vformat() here, because 'self' is a valid and common
3022 # We have to use .vformat() here, because 'self' is a valid and common
3035 # name, and expanding **ns for .format() would make it collide with
3023 # name, and expanding **ns for .format() would make it collide with
3036 # the 'self' argument of the method.
3024 # the 'self' argument of the method.
3037 cmd = formatter.vformat(cmd, args=[], kwargs=ns)
3025 cmd = formatter.vformat(cmd, args=[], kwargs=ns)
3038 except Exception:
3026 except Exception:
3039 # if formatter couldn't format, just let it go untransformed
3027 # if formatter couldn't format, just let it go untransformed
3040 pass
3028 pass
3041 return cmd
3029 return cmd
3042
3030
3043 def mktempfile(self, data=None, prefix='ipython_edit_'):
3031 def mktempfile(self, data=None, prefix='ipython_edit_'):
3044 """Make a new tempfile and return its filename.
3032 """Make a new tempfile and return its filename.
3045
3033
3046 This makes a call to tempfile.mkstemp (created in a tempfile.mkdtemp),
3034 This makes a call to tempfile.mkstemp (created in a tempfile.mkdtemp),
3047 but it registers the created filename internally so ipython cleans it up
3035 but it registers the created filename internally so ipython cleans it up
3048 at exit time.
3036 at exit time.
3049
3037
3050 Optional inputs:
3038 Optional inputs:
3051
3039
3052 - data(None): if data is given, it gets written out to the temp file
3040 - data(None): if data is given, it gets written out to the temp file
3053 immediately, and the file is closed again."""
3041 immediately, and the file is closed again."""
3054
3042
3055 dirname = tempfile.mkdtemp(prefix=prefix)
3043 dirname = tempfile.mkdtemp(prefix=prefix)
3056 self.tempdirs.append(dirname)
3044 self.tempdirs.append(dirname)
3057
3045
3058 handle, filename = tempfile.mkstemp('.py', prefix, dir=dirname)
3046 handle, filename = tempfile.mkstemp('.py', prefix, dir=dirname)
3059 os.close(handle) # On Windows, there can only be one open handle on a file
3047 os.close(handle) # On Windows, there can only be one open handle on a file
3060 self.tempfiles.append(filename)
3048 self.tempfiles.append(filename)
3061
3049
3062 if data:
3050 if data:
3063 tmp_file = open(filename,'w')
3051 tmp_file = open(filename,'w')
3064 tmp_file.write(data)
3052 tmp_file.write(data)
3065 tmp_file.close()
3053 tmp_file.close()
3066 return filename
3054 return filename
3067
3055
3068 @undoc
3056 @undoc
3069 def write(self,data):
3057 def write(self,data):
3070 """DEPRECATED: Write a string to the default output"""
3058 """DEPRECATED: Write a string to the default output"""
3071 warn('InteractiveShell.write() is deprecated, use sys.stdout instead',
3059 warn('InteractiveShell.write() is deprecated, use sys.stdout instead',
3072 DeprecationWarning, stacklevel=2)
3060 DeprecationWarning, stacklevel=2)
3073 sys.stdout.write(data)
3061 sys.stdout.write(data)
3074
3062
3075 @undoc
3063 @undoc
3076 def write_err(self,data):
3064 def write_err(self,data):
3077 """DEPRECATED: Write a string to the default error output"""
3065 """DEPRECATED: Write a string to the default error output"""
3078 warn('InteractiveShell.write_err() is deprecated, use sys.stderr instead',
3066 warn('InteractiveShell.write_err() is deprecated, use sys.stderr instead',
3079 DeprecationWarning, stacklevel=2)
3067 DeprecationWarning, stacklevel=2)
3080 sys.stderr.write(data)
3068 sys.stderr.write(data)
3081
3069
3082 def ask_yes_no(self, prompt, default=None, interrupt=None):
3070 def ask_yes_no(self, prompt, default=None, interrupt=None):
3083 if self.quiet:
3071 if self.quiet:
3084 return True
3072 return True
3085 return ask_yes_no(prompt,default,interrupt)
3073 return ask_yes_no(prompt,default,interrupt)
3086
3074
3087 def show_usage(self):
3075 def show_usage(self):
3088 """Show a usage message"""
3076 """Show a usage message"""
3089 page.page(IPython.core.usage.interactive_usage)
3077 page.page(IPython.core.usage.interactive_usage)
3090
3078
3091 def extract_input_lines(self, range_str, raw=False):
3079 def extract_input_lines(self, range_str, raw=False):
3092 """Return as a string a set of input history slices.
3080 """Return as a string a set of input history slices.
3093
3081
3094 Parameters
3082 Parameters
3095 ----------
3083 ----------
3096 range_str : string
3084 range_str : string
3097 The set of slices is given as a string, like "~5/6-~4/2 4:8 9",
3085 The set of slices is given as a string, like "~5/6-~4/2 4:8 9",
3098 since this function is for use by magic functions which get their
3086 since this function is for use by magic functions which get their
3099 arguments as strings. The number before the / is the session
3087 arguments as strings. The number before the / is the session
3100 number: ~n goes n back from the current session.
3088 number: ~n goes n back from the current session.
3101
3089
3102 raw : bool, optional
3090 raw : bool, optional
3103 By default, the processed input is used. If this is true, the raw
3091 By default, the processed input is used. If this is true, the raw
3104 input history is used instead.
3092 input history is used instead.
3105
3093
3106 Notes
3094 Notes
3107 -----
3095 -----
3108
3096
3109 Slices can be described with two notations:
3097 Slices can be described with two notations:
3110
3098
3111 * ``N:M`` -> standard python form, means including items N...(M-1).
3099 * ``N:M`` -> standard python form, means including items N...(M-1).
3112 * ``N-M`` -> include items N..M (closed endpoint).
3100 * ``N-M`` -> include items N..M (closed endpoint).
3113 """
3101 """
3114 lines = self.history_manager.get_range_by_str(range_str, raw=raw)
3102 lines = self.history_manager.get_range_by_str(range_str, raw=raw)
3115 return "\n".join(x for _, _, x in lines)
3103 return "\n".join(x for _, _, x in lines)
3116
3104
3117 def find_user_code(self, target, raw=True, py_only=False, skip_encoding_cookie=True, search_ns=False):
3105 def find_user_code(self, target, raw=True, py_only=False, skip_encoding_cookie=True, search_ns=False):
3118 """Get a code string from history, file, url, or a string or macro.
3106 """Get a code string from history, file, url, or a string or macro.
3119
3107
3120 This is mainly used by magic functions.
3108 This is mainly used by magic functions.
3121
3109
3122 Parameters
3110 Parameters
3123 ----------
3111 ----------
3124
3112
3125 target : str
3113 target : str
3126
3114
3127 A string specifying code to retrieve. This will be tried respectively
3115 A string specifying code to retrieve. This will be tried respectively
3128 as: ranges of input history (see %history for syntax), url,
3116 as: ranges of input history (see %history for syntax), url,
3129 corresponding .py file, filename, or an expression evaluating to a
3117 corresponding .py file, filename, or an expression evaluating to a
3130 string or Macro in the user namespace.
3118 string or Macro in the user namespace.
3131
3119
3132 raw : bool
3120 raw : bool
3133 If true (default), retrieve raw history. Has no effect on the other
3121 If true (default), retrieve raw history. Has no effect on the other
3134 retrieval mechanisms.
3122 retrieval mechanisms.
3135
3123
3136 py_only : bool (default False)
3124 py_only : bool (default False)
3137 Only try to fetch python code, do not try alternative methods to decode file
3125 Only try to fetch python code, do not try alternative methods to decode file
3138 if unicode fails.
3126 if unicode fails.
3139
3127
3140 Returns
3128 Returns
3141 -------
3129 -------
3142 A string of code.
3130 A string of code.
3143
3131
3144 ValueError is raised if nothing is found, and TypeError if it evaluates
3132 ValueError is raised if nothing is found, and TypeError if it evaluates
3145 to an object of another type. In each case, .args[0] is a printable
3133 to an object of another type. In each case, .args[0] is a printable
3146 message.
3134 message.
3147 """
3135 """
3148 code = self.extract_input_lines(target, raw=raw) # Grab history
3136 code = self.extract_input_lines(target, raw=raw) # Grab history
3149 if code:
3137 if code:
3150 return code
3138 return code
3151 try:
3139 try:
3152 if target.startswith(('http://', 'https://')):
3140 if target.startswith(('http://', 'https://')):
3153 return openpy.read_py_url(target, skip_encoding_cookie=skip_encoding_cookie)
3141 return openpy.read_py_url(target, skip_encoding_cookie=skip_encoding_cookie)
3154 except UnicodeDecodeError:
3142 except UnicodeDecodeError:
3155 if not py_only :
3143 if not py_only :
3156 # Deferred import
3144 # Deferred import
3157 try:
3145 try:
3158 from urllib.request import urlopen # Py3
3146 from urllib.request import urlopen # Py3
3159 except ImportError:
3147 except ImportError:
3160 from urllib import urlopen
3148 from urllib import urlopen
3161 response = urlopen(target)
3149 response = urlopen(target)
3162 return response.read().decode('latin1')
3150 return response.read().decode('latin1')
3163 raise ValueError(("'%s' seem to be unreadable.") % target)
3151 raise ValueError(("'%s' seem to be unreadable.") % target)
3164
3152
3165 potential_target = [target]
3153 potential_target = [target]
3166 try :
3154 try :
3167 potential_target.insert(0,get_py_filename(target))
3155 potential_target.insert(0,get_py_filename(target))
3168 except IOError:
3156 except IOError:
3169 pass
3157 pass
3170
3158
3171 for tgt in potential_target :
3159 for tgt in potential_target :
3172 if os.path.isfile(tgt): # Read file
3160 if os.path.isfile(tgt): # Read file
3173 try :
3161 try :
3174 return openpy.read_py_file(tgt, skip_encoding_cookie=skip_encoding_cookie)
3162 return openpy.read_py_file(tgt, skip_encoding_cookie=skip_encoding_cookie)
3175 except UnicodeDecodeError :
3163 except UnicodeDecodeError :
3176 if not py_only :
3164 if not py_only :
3177 with io_open(tgt,'r', encoding='latin1') as f :
3165 with io_open(tgt,'r', encoding='latin1') as f :
3178 return f.read()
3166 return f.read()
3179 raise ValueError(("'%s' seem to be unreadable.") % target)
3167 raise ValueError(("'%s' seem to be unreadable.") % target)
3180 elif os.path.isdir(os.path.expanduser(tgt)):
3168 elif os.path.isdir(os.path.expanduser(tgt)):
3181 raise ValueError("'%s' is a directory, not a regular file." % target)
3169 raise ValueError("'%s' is a directory, not a regular file." % target)
3182
3170
3183 if search_ns:
3171 if search_ns:
3184 # Inspect namespace to load object source
3172 # Inspect namespace to load object source
3185 object_info = self.object_inspect(target, detail_level=1)
3173 object_info = self.object_inspect(target, detail_level=1)
3186 if object_info['found'] and object_info['source']:
3174 if object_info['found'] and object_info['source']:
3187 return object_info['source']
3175 return object_info['source']
3188
3176
3189 try: # User namespace
3177 try: # User namespace
3190 codeobj = eval(target, self.user_ns)
3178 codeobj = eval(target, self.user_ns)
3191 except Exception:
3179 except Exception:
3192 raise ValueError(("'%s' was not found in history, as a file, url, "
3180 raise ValueError(("'%s' was not found in history, as a file, url, "
3193 "nor in the user namespace.") % target)
3181 "nor in the user namespace.") % target)
3194
3182
3195 if isinstance(codeobj, string_types):
3183 if isinstance(codeobj, string_types):
3196 return codeobj
3184 return codeobj
3197 elif isinstance(codeobj, Macro):
3185 elif isinstance(codeobj, Macro):
3198 return codeobj.value
3186 return codeobj.value
3199
3187
3200 raise TypeError("%s is neither a string nor a macro." % target,
3188 raise TypeError("%s is neither a string nor a macro." % target,
3201 codeobj)
3189 codeobj)
3202
3190
3203 #-------------------------------------------------------------------------
3191 #-------------------------------------------------------------------------
3204 # Things related to IPython exiting
3192 # Things related to IPython exiting
3205 #-------------------------------------------------------------------------
3193 #-------------------------------------------------------------------------
3206 def atexit_operations(self):
3194 def atexit_operations(self):
3207 """This will be executed at the time of exit.
3195 """This will be executed at the time of exit.
3208
3196
3209 Cleanup operations and saving of persistent data that is done
3197 Cleanup operations and saving of persistent data that is done
3210 unconditionally by IPython should be performed here.
3198 unconditionally by IPython should be performed here.
3211
3199
3212 For things that may depend on startup flags or platform specifics (such
3200 For things that may depend on startup flags or platform specifics (such
3213 as having readline or not), register a separate atexit function in the
3201 as having readline or not), register a separate atexit function in the
3214 code that has the appropriate information, rather than trying to
3202 code that has the appropriate information, rather than trying to
3215 clutter
3203 clutter
3216 """
3204 """
3217 # Close the history session (this stores the end time and line count)
3205 # Close the history session (this stores the end time and line count)
3218 # this must be *before* the tempfile cleanup, in case of temporary
3206 # this must be *before* the tempfile cleanup, in case of temporary
3219 # history db
3207 # history db
3220 self.history_manager.end_session()
3208 self.history_manager.end_session()
3221
3209
3222 # Cleanup all tempfiles and folders left around
3210 # Cleanup all tempfiles and folders left around
3223 for tfile in self.tempfiles:
3211 for tfile in self.tempfiles:
3224 try:
3212 try:
3225 os.unlink(tfile)
3213 os.unlink(tfile)
3226 except OSError:
3214 except OSError:
3227 pass
3215 pass
3228
3216
3229 for tdir in self.tempdirs:
3217 for tdir in self.tempdirs:
3230 try:
3218 try:
3231 os.rmdir(tdir)
3219 os.rmdir(tdir)
3232 except OSError:
3220 except OSError:
3233 pass
3221 pass
3234
3222
3235 # Clear all user namespaces to release all references cleanly.
3223 # Clear all user namespaces to release all references cleanly.
3236 self.reset(new_session=False)
3224 self.reset(new_session=False)
3237
3225
3238 # Run user hooks
3226 # Run user hooks
3239 self.hooks.shutdown_hook()
3227 self.hooks.shutdown_hook()
3240
3228
3241 def cleanup(self):
3229 def cleanup(self):
3242 self.restore_sys_module_state()
3230 self.restore_sys_module_state()
3243
3231
3244
3232
3245 # Overridden in terminal subclass to change prompts
3233 # Overridden in terminal subclass to change prompts
3246 def switch_doctest_mode(self, mode):
3234 def switch_doctest_mode(self, mode):
3247 pass
3235 pass
3248
3236
3249
3237
3250 class InteractiveShellABC(with_metaclass(abc.ABCMeta, object)):
3238 class InteractiveShellABC(with_metaclass(abc.ABCMeta, object)):
3251 """An abstract base class for InteractiveShell."""
3239 """An abstract base class for InteractiveShell."""
3252
3240
3253 InteractiveShellABC.register(InteractiveShell)
3241 InteractiveShellABC.register(InteractiveShell)
@@ -1,1362 +1,1361 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Implementation of execution-related magic functions."""
2 """Implementation of execution-related magic functions."""
3
3
4 # Copyright (c) IPython Development Team.
4 # Copyright (c) IPython Development Team.
5 # Distributed under the terms of the Modified BSD License.
5 # Distributed under the terms of the Modified BSD License.
6
6
7 from __future__ import print_function
7 from __future__ import print_function
8 from __future__ import absolute_import
8 from __future__ import absolute_import
9
9
10 import ast
10 import ast
11 import bdb
11 import bdb
12 import gc
12 import gc
13 import itertools
13 import itertools
14 import os
14 import os
15 import sys
15 import sys
16 import time
16 import time
17 import timeit
17 import timeit
18 from pdb import Restart
18 from pdb import Restart
19
19
20 # cProfile was added in Python2.5
20 # cProfile was added in Python2.5
21 try:
21 try:
22 import cProfile as profile
22 import cProfile as profile
23 import pstats
23 import pstats
24 except ImportError:
24 except ImportError:
25 # profile isn't bundled by default in Debian for license reasons
25 # profile isn't bundled by default in Debian for license reasons
26 try:
26 try:
27 import profile, pstats
27 import profile, pstats
28 except ImportError:
28 except ImportError:
29 profile = pstats = None
29 profile = pstats = None
30
30
31 from IPython.core import debugger, oinspect
31 from IPython.core import debugger, oinspect
32 from IPython.core import magic_arguments
32 from IPython.core import magic_arguments
33 from IPython.core import page
33 from IPython.core import page
34 from IPython.core.error import UsageError
34 from IPython.core.error import UsageError
35 from IPython.core.macro import Macro
35 from IPython.core.macro import Macro
36 from IPython.core.magic import (Magics, magics_class, line_magic, cell_magic,
36 from IPython.core.magic import (Magics, magics_class, line_magic, cell_magic,
37 line_cell_magic, on_off, needs_local_scope)
37 line_cell_magic, on_off, needs_local_scope)
38 from IPython.testing.skipdoctest import skip_doctest
38 from IPython.testing.skipdoctest import skip_doctest
39 from IPython.utils import py3compat
39 from IPython.utils import py3compat
40 from IPython.utils.py3compat import builtin_mod, iteritems, PY3
40 from IPython.utils.py3compat import builtin_mod, iteritems, PY3
41 from IPython.utils.contexts import preserve_keys
41 from IPython.utils.contexts import preserve_keys
42 from IPython.utils.capture import capture_output
42 from IPython.utils.capture import capture_output
43 from IPython.utils.ipstruct import Struct
43 from IPython.utils.ipstruct import Struct
44 from IPython.utils.module_paths import find_mod
44 from IPython.utils.module_paths import find_mod
45 from IPython.utils.path import get_py_filename, shellglob
45 from IPython.utils.path import get_py_filename, shellglob
46 from IPython.utils.timing import clock, clock2
46 from IPython.utils.timing import clock, clock2
47 from warnings import warn
47 from warnings import warn
48 from logging import error
48 from logging import error
49
49
50 if PY3:
50 if PY3:
51 from io import StringIO
51 from io import StringIO
52 else:
52 else:
53 from StringIO import StringIO
53 from StringIO import StringIO
54
54
55 #-----------------------------------------------------------------------------
55 #-----------------------------------------------------------------------------
56 # Magic implementation classes
56 # Magic implementation classes
57 #-----------------------------------------------------------------------------
57 #-----------------------------------------------------------------------------
58
58
59
59
60 class TimeitResult(object):
60 class TimeitResult(object):
61 """
61 """
62 Object returned by the timeit magic with info about the run.
62 Object returned by the timeit magic with info about the run.
63
63
64 Contains the following attributes :
64 Contains the following attributes :
65
65
66 loops: (int) number of loops done per measurement
66 loops: (int) number of loops done per measurement
67 repeat: (int) number of times the measurement has been repeated
67 repeat: (int) number of times the measurement has been repeated
68 best: (float) best execution time / number
68 best: (float) best execution time / number
69 all_runs: (list of float) execution time of each run (in s)
69 all_runs: (list of float) execution time of each run (in s)
70 compile_time: (float) time of statement compilation (s)
70 compile_time: (float) time of statement compilation (s)
71
71
72 """
72 """
73
73
74 def __init__(self, loops, repeat, best, worst, all_runs, compile_time, precision):
74 def __init__(self, loops, repeat, best, worst, all_runs, compile_time, precision):
75 self.loops = loops
75 self.loops = loops
76 self.repeat = repeat
76 self.repeat = repeat
77 self.best = best
77 self.best = best
78 self.worst = worst
78 self.worst = worst
79 self.all_runs = all_runs
79 self.all_runs = all_runs
80 self.compile_time = compile_time
80 self.compile_time = compile_time
81 self._precision = precision
81 self._precision = precision
82
82
83 def _repr_pretty_(self, p , cycle):
83 def _repr_pretty_(self, p , cycle):
84 if self.loops == 1: # No s at "loops" if only one loop
84 if self.loops == 1: # No s at "loops" if only one loop
85 unic = u"%d loop, best of %d: %s per loop" % (self.loops, self.repeat,
85 unic = u"%d loop, best of %d: %s per loop" % (self.loops, self.repeat,
86 _format_time(self.best, self._precision))
86 _format_time(self.best, self._precision))
87 else:
87 else:
88 unic = u"%d loops, best of %d: %s per loop" % (self.loops, self.repeat,
88 unic = u"%d loops, best of %d: %s per loop" % (self.loops, self.repeat,
89 _format_time(self.best, self._precision))
89 _format_time(self.best, self._precision))
90 p.text(u'<TimeitResult : '+unic+u'>')
90 p.text(u'<TimeitResult : '+unic+u'>')
91
91
92
92
93 class TimeitTemplateFiller(ast.NodeTransformer):
93 class TimeitTemplateFiller(ast.NodeTransformer):
94 """Fill in the AST template for timing execution.
94 """Fill in the AST template for timing execution.
95
95
96 This is quite closely tied to the template definition, which is in
96 This is quite closely tied to the template definition, which is in
97 :meth:`ExecutionMagics.timeit`.
97 :meth:`ExecutionMagics.timeit`.
98 """
98 """
99 def __init__(self, ast_setup, ast_stmt):
99 def __init__(self, ast_setup, ast_stmt):
100 self.ast_setup = ast_setup
100 self.ast_setup = ast_setup
101 self.ast_stmt = ast_stmt
101 self.ast_stmt = ast_stmt
102
102
103 def visit_FunctionDef(self, node):
103 def visit_FunctionDef(self, node):
104 "Fill in the setup statement"
104 "Fill in the setup statement"
105 self.generic_visit(node)
105 self.generic_visit(node)
106 if node.name == "inner":
106 if node.name == "inner":
107 node.body[:1] = self.ast_setup.body
107 node.body[:1] = self.ast_setup.body
108
108
109 return node
109 return node
110
110
111 def visit_For(self, node):
111 def visit_For(self, node):
112 "Fill in the statement to be timed"
112 "Fill in the statement to be timed"
113 if getattr(getattr(node.body[0], 'value', None), 'id', None) == 'stmt':
113 if getattr(getattr(node.body[0], 'value', None), 'id', None) == 'stmt':
114 node.body = self.ast_stmt.body
114 node.body = self.ast_stmt.body
115 return node
115 return node
116
116
117
117
118 class Timer(timeit.Timer):
118 class Timer(timeit.Timer):
119 """Timer class that explicitly uses self.inner
119 """Timer class that explicitly uses self.inner
120
120
121 which is an undocumented implementation detail of CPython,
121 which is an undocumented implementation detail of CPython,
122 not shared by PyPy.
122 not shared by PyPy.
123 """
123 """
124 # Timer.timeit copied from CPython 3.4.2
124 # Timer.timeit copied from CPython 3.4.2
125 def timeit(self, number=timeit.default_number):
125 def timeit(self, number=timeit.default_number):
126 """Time 'number' executions of the main statement.
126 """Time 'number' executions of the main statement.
127
127
128 To be precise, this executes the setup statement once, and
128 To be precise, this executes the setup statement once, and
129 then returns the time it takes to execute the main statement
129 then returns the time it takes to execute the main statement
130 a number of times, as a float measured in seconds. The
130 a number of times, as a float measured in seconds. The
131 argument is the number of times through the loop, defaulting
131 argument is the number of times through the loop, defaulting
132 to one million. The main statement, the setup statement and
132 to one million. The main statement, the setup statement and
133 the timer function to be used are passed to the constructor.
133 the timer function to be used are passed to the constructor.
134 """
134 """
135 it = itertools.repeat(None, number)
135 it = itertools.repeat(None, number)
136 gcold = gc.isenabled()
136 gcold = gc.isenabled()
137 gc.disable()
137 gc.disable()
138 try:
138 try:
139 timing = self.inner(it, self.timer)
139 timing = self.inner(it, self.timer)
140 finally:
140 finally:
141 if gcold:
141 if gcold:
142 gc.enable()
142 gc.enable()
143 return timing
143 return timing
144
144
145
145
146 @magics_class
146 @magics_class
147 class ExecutionMagics(Magics):
147 class ExecutionMagics(Magics):
148 """Magics related to code execution, debugging, profiling, etc.
148 """Magics related to code execution, debugging, profiling, etc.
149
149
150 """
150 """
151
151
152 def __init__(self, shell):
152 def __init__(self, shell):
153 super(ExecutionMagics, self).__init__(shell)
153 super(ExecutionMagics, self).__init__(shell)
154 if profile is None:
154 if profile is None:
155 self.prun = self.profile_missing_notice
155 self.prun = self.profile_missing_notice
156 # Default execution function used to actually run user code.
156 # Default execution function used to actually run user code.
157 self.default_runner = None
157 self.default_runner = None
158
158
159 def profile_missing_notice(self, *args, **kwargs):
159 def profile_missing_notice(self, *args, **kwargs):
160 error("""\
160 error("""\
161 The profile module could not be found. It has been removed from the standard
161 The profile module could not be found. It has been removed from the standard
162 python packages because of its non-free license. To use profiling, install the
162 python packages because of its non-free license. To use profiling, install the
163 python-profiler package from non-free.""")
163 python-profiler package from non-free.""")
164
164
165 @skip_doctest
165 @skip_doctest
166 @line_cell_magic
166 @line_cell_magic
167 def prun(self, parameter_s='', cell=None):
167 def prun(self, parameter_s='', cell=None):
168
168
169 """Run a statement through the python code profiler.
169 """Run a statement through the python code profiler.
170
170
171 Usage, in line mode:
171 Usage, in line mode:
172 %prun [options] statement
172 %prun [options] statement
173
173
174 Usage, in cell mode:
174 Usage, in cell mode:
175 %%prun [options] [statement]
175 %%prun [options] [statement]
176 code...
176 code...
177 code...
177 code...
178
178
179 In cell mode, the additional code lines are appended to the (possibly
179 In cell mode, the additional code lines are appended to the (possibly
180 empty) statement in the first line. Cell mode allows you to easily
180 empty) statement in the first line. Cell mode allows you to easily
181 profile multiline blocks without having to put them in a separate
181 profile multiline blocks without having to put them in a separate
182 function.
182 function.
183
183
184 The given statement (which doesn't require quote marks) is run via the
184 The given statement (which doesn't require quote marks) is run via the
185 python profiler in a manner similar to the profile.run() function.
185 python profiler in a manner similar to the profile.run() function.
186 Namespaces are internally managed to work correctly; profile.run
186 Namespaces are internally managed to work correctly; profile.run
187 cannot be used in IPython because it makes certain assumptions about
187 cannot be used in IPython because it makes certain assumptions about
188 namespaces which do not hold under IPython.
188 namespaces which do not hold under IPython.
189
189
190 Options:
190 Options:
191
191
192 -l <limit>
192 -l <limit>
193 you can place restrictions on what or how much of the
193 you can place restrictions on what or how much of the
194 profile gets printed. The limit value can be:
194 profile gets printed. The limit value can be:
195
195
196 * A string: only information for function names containing this string
196 * A string: only information for function names containing this string
197 is printed.
197 is printed.
198
198
199 * An integer: only these many lines are printed.
199 * An integer: only these many lines are printed.
200
200
201 * A float (between 0 and 1): this fraction of the report is printed
201 * A float (between 0 and 1): this fraction of the report is printed
202 (for example, use a limit of 0.4 to see the topmost 40% only).
202 (for example, use a limit of 0.4 to see the topmost 40% only).
203
203
204 You can combine several limits with repeated use of the option. For
204 You can combine several limits with repeated use of the option. For
205 example, ``-l __init__ -l 5`` will print only the topmost 5 lines of
205 example, ``-l __init__ -l 5`` will print only the topmost 5 lines of
206 information about class constructors.
206 information about class constructors.
207
207
208 -r
208 -r
209 return the pstats.Stats object generated by the profiling. This
209 return the pstats.Stats object generated by the profiling. This
210 object has all the information about the profile in it, and you can
210 object has all the information about the profile in it, and you can
211 later use it for further analysis or in other functions.
211 later use it for further analysis or in other functions.
212
212
213 -s <key>
213 -s <key>
214 sort profile by given key. You can provide more than one key
214 sort profile by given key. You can provide more than one key
215 by using the option several times: '-s key1 -s key2 -s key3...'. The
215 by using the option several times: '-s key1 -s key2 -s key3...'. The
216 default sorting key is 'time'.
216 default sorting key is 'time'.
217
217
218 The following is copied verbatim from the profile documentation
218 The following is copied verbatim from the profile documentation
219 referenced below:
219 referenced below:
220
220
221 When more than one key is provided, additional keys are used as
221 When more than one key is provided, additional keys are used as
222 secondary criteria when the there is equality in all keys selected
222 secondary criteria when the there is equality in all keys selected
223 before them.
223 before them.
224
224
225 Abbreviations can be used for any key names, as long as the
225 Abbreviations can be used for any key names, as long as the
226 abbreviation is unambiguous. The following are the keys currently
226 abbreviation is unambiguous. The following are the keys currently
227 defined:
227 defined:
228
228
229 ============ =====================
229 ============ =====================
230 Valid Arg Meaning
230 Valid Arg Meaning
231 ============ =====================
231 ============ =====================
232 "calls" call count
232 "calls" call count
233 "cumulative" cumulative time
233 "cumulative" cumulative time
234 "file" file name
234 "file" file name
235 "module" file name
235 "module" file name
236 "pcalls" primitive call count
236 "pcalls" primitive call count
237 "line" line number
237 "line" line number
238 "name" function name
238 "name" function name
239 "nfl" name/file/line
239 "nfl" name/file/line
240 "stdname" standard name
240 "stdname" standard name
241 "time" internal time
241 "time" internal time
242 ============ =====================
242 ============ =====================
243
243
244 Note that all sorts on statistics are in descending order (placing
244 Note that all sorts on statistics are in descending order (placing
245 most time consuming items first), where as name, file, and line number
245 most time consuming items first), where as name, file, and line number
246 searches are in ascending order (i.e., alphabetical). The subtle
246 searches are in ascending order (i.e., alphabetical). The subtle
247 distinction between "nfl" and "stdname" is that the standard name is a
247 distinction between "nfl" and "stdname" is that the standard name is a
248 sort of the name as printed, which means that the embedded line
248 sort of the name as printed, which means that the embedded line
249 numbers get compared in an odd way. For example, lines 3, 20, and 40
249 numbers get compared in an odd way. For example, lines 3, 20, and 40
250 would (if the file names were the same) appear in the string order
250 would (if the file names were the same) appear in the string order
251 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
251 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
252 line numbers. In fact, sort_stats("nfl") is the same as
252 line numbers. In fact, sort_stats("nfl") is the same as
253 sort_stats("name", "file", "line").
253 sort_stats("name", "file", "line").
254
254
255 -T <filename>
255 -T <filename>
256 save profile results as shown on screen to a text
256 save profile results as shown on screen to a text
257 file. The profile is still shown on screen.
257 file. The profile is still shown on screen.
258
258
259 -D <filename>
259 -D <filename>
260 save (via dump_stats) profile statistics to given
260 save (via dump_stats) profile statistics to given
261 filename. This data is in a format understood by the pstats module, and
261 filename. This data is in a format understood by the pstats module, and
262 is generated by a call to the dump_stats() method of profile
262 is generated by a call to the dump_stats() method of profile
263 objects. The profile is still shown on screen.
263 objects. The profile is still shown on screen.
264
264
265 -q
265 -q
266 suppress output to the pager. Best used with -T and/or -D above.
266 suppress output to the pager. Best used with -T and/or -D above.
267
267
268 If you want to run complete programs under the profiler's control, use
268 If you want to run complete programs under the profiler's control, use
269 ``%run -p [prof_opts] filename.py [args to program]`` where prof_opts
269 ``%run -p [prof_opts] filename.py [args to program]`` where prof_opts
270 contains profiler specific options as described here.
270 contains profiler specific options as described here.
271
271
272 You can read the complete documentation for the profile module with::
272 You can read the complete documentation for the profile module with::
273
273
274 In [1]: import profile; profile.help()
274 In [1]: import profile; profile.help()
275 """
275 """
276 opts, arg_str = self.parse_options(parameter_s, 'D:l:rs:T:q',
276 opts, arg_str = self.parse_options(parameter_s, 'D:l:rs:T:q',
277 list_all=True, posix=False)
277 list_all=True, posix=False)
278 if cell is not None:
278 if cell is not None:
279 arg_str += '\n' + cell
279 arg_str += '\n' + cell
280 arg_str = self.shell.input_splitter.transform_cell(arg_str)
280 arg_str = self.shell.input_splitter.transform_cell(arg_str)
281 return self._run_with_profiler(arg_str, opts, self.shell.user_ns)
281 return self._run_with_profiler(arg_str, opts, self.shell.user_ns)
282
282
283 def _run_with_profiler(self, code, opts, namespace):
283 def _run_with_profiler(self, code, opts, namespace):
284 """
284 """
285 Run `code` with profiler. Used by ``%prun`` and ``%run -p``.
285 Run `code` with profiler. Used by ``%prun`` and ``%run -p``.
286
286
287 Parameters
287 Parameters
288 ----------
288 ----------
289 code : str
289 code : str
290 Code to be executed.
290 Code to be executed.
291 opts : Struct
291 opts : Struct
292 Options parsed by `self.parse_options`.
292 Options parsed by `self.parse_options`.
293 namespace : dict
293 namespace : dict
294 A dictionary for Python namespace (e.g., `self.shell.user_ns`).
294 A dictionary for Python namespace (e.g., `self.shell.user_ns`).
295
295
296 """
296 """
297
297
298 # Fill default values for unspecified options:
298 # Fill default values for unspecified options:
299 opts.merge(Struct(D=[''], l=[], s=['time'], T=['']))
299 opts.merge(Struct(D=[''], l=[], s=['time'], T=['']))
300
300
301 prof = profile.Profile()
301 prof = profile.Profile()
302 try:
302 try:
303 prof = prof.runctx(code, namespace, namespace)
303 prof = prof.runctx(code, namespace, namespace)
304 sys_exit = ''
304 sys_exit = ''
305 except SystemExit:
305 except SystemExit:
306 sys_exit = """*** SystemExit exception caught in code being profiled."""
306 sys_exit = """*** SystemExit exception caught in code being profiled."""
307
307
308 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
308 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
309
309
310 lims = opts.l
310 lims = opts.l
311 if lims:
311 if lims:
312 lims = [] # rebuild lims with ints/floats/strings
312 lims = [] # rebuild lims with ints/floats/strings
313 for lim in opts.l:
313 for lim in opts.l:
314 try:
314 try:
315 lims.append(int(lim))
315 lims.append(int(lim))
316 except ValueError:
316 except ValueError:
317 try:
317 try:
318 lims.append(float(lim))
318 lims.append(float(lim))
319 except ValueError:
319 except ValueError:
320 lims.append(lim)
320 lims.append(lim)
321
321
322 # Trap output.
322 # Trap output.
323 stdout_trap = StringIO()
323 stdout_trap = StringIO()
324 stats_stream = stats.stream
324 stats_stream = stats.stream
325 try:
325 try:
326 stats.stream = stdout_trap
326 stats.stream = stdout_trap
327 stats.print_stats(*lims)
327 stats.print_stats(*lims)
328 finally:
328 finally:
329 stats.stream = stats_stream
329 stats.stream = stats_stream
330
330
331 output = stdout_trap.getvalue()
331 output = stdout_trap.getvalue()
332 output = output.rstrip()
332 output = output.rstrip()
333
333
334 if 'q' not in opts:
334 if 'q' not in opts:
335 page.page(output)
335 page.page(output)
336 print(sys_exit, end=' ')
336 print(sys_exit, end=' ')
337
337
338 dump_file = opts.D[0]
338 dump_file = opts.D[0]
339 text_file = opts.T[0]
339 text_file = opts.T[0]
340 if dump_file:
340 if dump_file:
341 prof.dump_stats(dump_file)
341 prof.dump_stats(dump_file)
342 print('\n*** Profile stats marshalled to file',\
342 print('\n*** Profile stats marshalled to file',\
343 repr(dump_file)+'.',sys_exit)
343 repr(dump_file)+'.',sys_exit)
344 if text_file:
344 if text_file:
345 pfile = open(text_file,'w')
345 pfile = open(text_file,'w')
346 pfile.write(output)
346 pfile.write(output)
347 pfile.close()
347 pfile.close()
348 print('\n*** Profile printout saved to text file',\
348 print('\n*** Profile printout saved to text file',\
349 repr(text_file)+'.',sys_exit)
349 repr(text_file)+'.',sys_exit)
350
350
351 if 'r' in opts:
351 if 'r' in opts:
352 return stats
352 return stats
353 else:
353 else:
354 return None
354 return None
355
355
356 @line_magic
356 @line_magic
357 def pdb(self, parameter_s=''):
357 def pdb(self, parameter_s=''):
358 """Control the automatic calling of the pdb interactive debugger.
358 """Control the automatic calling of the pdb interactive debugger.
359
359
360 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
360 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
361 argument it works as a toggle.
361 argument it works as a toggle.
362
362
363 When an exception is triggered, IPython can optionally call the
363 When an exception is triggered, IPython can optionally call the
364 interactive pdb debugger after the traceback printout. %pdb toggles
364 interactive pdb debugger after the traceback printout. %pdb toggles
365 this feature on and off.
365 this feature on and off.
366
366
367 The initial state of this feature is set in your configuration
367 The initial state of this feature is set in your configuration
368 file (the option is ``InteractiveShell.pdb``).
368 file (the option is ``InteractiveShell.pdb``).
369
369
370 If you want to just activate the debugger AFTER an exception has fired,
370 If you want to just activate the debugger AFTER an exception has fired,
371 without having to type '%pdb on' and rerunning your code, you can use
371 without having to type '%pdb on' and rerunning your code, you can use
372 the %debug magic."""
372 the %debug magic."""
373
373
374 par = parameter_s.strip().lower()
374 par = parameter_s.strip().lower()
375
375
376 if par:
376 if par:
377 try:
377 try:
378 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
378 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
379 except KeyError:
379 except KeyError:
380 print ('Incorrect argument. Use on/1, off/0, '
380 print ('Incorrect argument. Use on/1, off/0, '
381 'or nothing for a toggle.')
381 'or nothing for a toggle.')
382 return
382 return
383 else:
383 else:
384 # toggle
384 # toggle
385 new_pdb = not self.shell.call_pdb
385 new_pdb = not self.shell.call_pdb
386
386
387 # set on the shell
387 # set on the shell
388 self.shell.call_pdb = new_pdb
388 self.shell.call_pdb = new_pdb
389 print('Automatic pdb calling has been turned',on_off(new_pdb))
389 print('Automatic pdb calling has been turned',on_off(new_pdb))
390
390
391 @skip_doctest
391 @skip_doctest
392 @magic_arguments.magic_arguments()
392 @magic_arguments.magic_arguments()
393 @magic_arguments.argument('--breakpoint', '-b', metavar='FILE:LINE',
393 @magic_arguments.argument('--breakpoint', '-b', metavar='FILE:LINE',
394 help="""
394 help="""
395 Set break point at LINE in FILE.
395 Set break point at LINE in FILE.
396 """
396 """
397 )
397 )
398 @magic_arguments.argument('statement', nargs='*',
398 @magic_arguments.argument('statement', nargs='*',
399 help="""
399 help="""
400 Code to run in debugger.
400 Code to run in debugger.
401 You can omit this in cell magic mode.
401 You can omit this in cell magic mode.
402 """
402 """
403 )
403 )
404 @line_cell_magic
404 @line_cell_magic
405 def debug(self, line='', cell=None):
405 def debug(self, line='', cell=None):
406 """Activate the interactive debugger.
406 """Activate the interactive debugger.
407
407
408 This magic command support two ways of activating debugger.
408 This magic command support two ways of activating debugger.
409 One is to activate debugger before executing code. This way, you
409 One is to activate debugger before executing code. This way, you
410 can set a break point, to step through the code from the point.
410 can set a break point, to step through the code from the point.
411 You can use this mode by giving statements to execute and optionally
411 You can use this mode by giving statements to execute and optionally
412 a breakpoint.
412 a breakpoint.
413
413
414 The other one is to activate debugger in post-mortem mode. You can
414 The other one is to activate debugger in post-mortem mode. You can
415 activate this mode simply running %debug without any argument.
415 activate this mode simply running %debug without any argument.
416 If an exception has just occurred, this lets you inspect its stack
416 If an exception has just occurred, this lets you inspect its stack
417 frames interactively. Note that this will always work only on the last
417 frames interactively. Note that this will always work only on the last
418 traceback that occurred, so you must call this quickly after an
418 traceback that occurred, so you must call this quickly after an
419 exception that you wish to inspect has fired, because if another one
419 exception that you wish to inspect has fired, because if another one
420 occurs, it clobbers the previous one.
420 occurs, it clobbers the previous one.
421
421
422 If you want IPython to automatically do this on every exception, see
422 If you want IPython to automatically do this on every exception, see
423 the %pdb magic for more details.
423 the %pdb magic for more details.
424 """
424 """
425 args = magic_arguments.parse_argstring(self.debug, line)
425 args = magic_arguments.parse_argstring(self.debug, line)
426
426
427 if not (args.breakpoint or args.statement or cell):
427 if not (args.breakpoint or args.statement or cell):
428 self._debug_post_mortem()
428 self._debug_post_mortem()
429 else:
429 else:
430 code = "\n".join(args.statement)
430 code = "\n".join(args.statement)
431 if cell:
431 if cell:
432 code += "\n" + cell
432 code += "\n" + cell
433 self._debug_exec(code, args.breakpoint)
433 self._debug_exec(code, args.breakpoint)
434
434
435 def _debug_post_mortem(self):
435 def _debug_post_mortem(self):
436 self.shell.debugger(force=True)
436 self.shell.debugger(force=True)
437
437
438 def _debug_exec(self, code, breakpoint):
438 def _debug_exec(self, code, breakpoint):
439 if breakpoint:
439 if breakpoint:
440 (filename, bp_line) = breakpoint.split(':', 1)
440 (filename, bp_line) = breakpoint.split(':', 1)
441 bp_line = int(bp_line)
441 bp_line = int(bp_line)
442 else:
442 else:
443 (filename, bp_line) = (None, None)
443 (filename, bp_line) = (None, None)
444 self._run_with_debugger(code, self.shell.user_ns, filename, bp_line)
444 self._run_with_debugger(code, self.shell.user_ns, filename, bp_line)
445
445
446 @line_magic
446 @line_magic
447 def tb(self, s):
447 def tb(self, s):
448 """Print the last traceback with the currently active exception mode.
448 """Print the last traceback with the currently active exception mode.
449
449
450 See %xmode for changing exception reporting modes."""
450 See %xmode for changing exception reporting modes."""
451 self.shell.showtraceback()
451 self.shell.showtraceback()
452
452
453 @skip_doctest
453 @skip_doctest
454 @line_magic
454 @line_magic
455 def run(self, parameter_s='', runner=None,
455 def run(self, parameter_s='', runner=None,
456 file_finder=get_py_filename):
456 file_finder=get_py_filename):
457 """Run the named file inside IPython as a program.
457 """Run the named file inside IPython as a program.
458
458
459 Usage::
459 Usage::
460
460
461 %run [-n -i -e -G]
461 %run [-n -i -e -G]
462 [( -t [-N<N>] | -d [-b<N>] | -p [profile options] )]
462 [( -t [-N<N>] | -d [-b<N>] | -p [profile options] )]
463 ( -m mod | file ) [args]
463 ( -m mod | file ) [args]
464
464
465 Parameters after the filename are passed as command-line arguments to
465 Parameters after the filename are passed as command-line arguments to
466 the program (put in sys.argv). Then, control returns to IPython's
466 the program (put in sys.argv). Then, control returns to IPython's
467 prompt.
467 prompt.
468
468
469 This is similar to running at a system prompt ``python file args``,
469 This is similar to running at a system prompt ``python file args``,
470 but with the advantage of giving you IPython's tracebacks, and of
470 but with the advantage of giving you IPython's tracebacks, and of
471 loading all variables into your interactive namespace for further use
471 loading all variables into your interactive namespace for further use
472 (unless -p is used, see below).
472 (unless -p is used, see below).
473
473
474 The file is executed in a namespace initially consisting only of
474 The file is executed in a namespace initially consisting only of
475 ``__name__=='__main__'`` and sys.argv constructed as indicated. It thus
475 ``__name__=='__main__'`` and sys.argv constructed as indicated. It thus
476 sees its environment as if it were being run as a stand-alone program
476 sees its environment as if it were being run as a stand-alone program
477 (except for sharing global objects such as previously imported
477 (except for sharing global objects such as previously imported
478 modules). But after execution, the IPython interactive namespace gets
478 modules). But after execution, the IPython interactive namespace gets
479 updated with all variables defined in the program (except for __name__
479 updated with all variables defined in the program (except for __name__
480 and sys.argv). This allows for very convenient loading of code for
480 and sys.argv). This allows for very convenient loading of code for
481 interactive work, while giving each program a 'clean sheet' to run in.
481 interactive work, while giving each program a 'clean sheet' to run in.
482
482
483 Arguments are expanded using shell-like glob match. Patterns
483 Arguments are expanded using shell-like glob match. Patterns
484 '*', '?', '[seq]' and '[!seq]' can be used. Additionally,
484 '*', '?', '[seq]' and '[!seq]' can be used. Additionally,
485 tilde '~' will be expanded into user's home directory. Unlike
485 tilde '~' will be expanded into user's home directory. Unlike
486 real shells, quotation does not suppress expansions. Use
486 real shells, quotation does not suppress expansions. Use
487 *two* back slashes (e.g. ``\\\\*``) to suppress expansions.
487 *two* back slashes (e.g. ``\\\\*``) to suppress expansions.
488 To completely disable these expansions, you can use -G flag.
488 To completely disable these expansions, you can use -G flag.
489
489
490 Options:
490 Options:
491
491
492 -n
492 -n
493 __name__ is NOT set to '__main__', but to the running file's name
493 __name__ is NOT set to '__main__', but to the running file's name
494 without extension (as python does under import). This allows running
494 without extension (as python does under import). This allows running
495 scripts and reloading the definitions in them without calling code
495 scripts and reloading the definitions in them without calling code
496 protected by an ``if __name__ == "__main__"`` clause.
496 protected by an ``if __name__ == "__main__"`` clause.
497
497
498 -i
498 -i
499 run the file in IPython's namespace instead of an empty one. This
499 run the file in IPython's namespace instead of an empty one. This
500 is useful if you are experimenting with code written in a text editor
500 is useful if you are experimenting with code written in a text editor
501 which depends on variables defined interactively.
501 which depends on variables defined interactively.
502
502
503 -e
503 -e
504 ignore sys.exit() calls or SystemExit exceptions in the script
504 ignore sys.exit() calls or SystemExit exceptions in the script
505 being run. This is particularly useful if IPython is being used to
505 being run. This is particularly useful if IPython is being used to
506 run unittests, which always exit with a sys.exit() call. In such
506 run unittests, which always exit with a sys.exit() call. In such
507 cases you are interested in the output of the test results, not in
507 cases you are interested in the output of the test results, not in
508 seeing a traceback of the unittest module.
508 seeing a traceback of the unittest module.
509
509
510 -t
510 -t
511 print timing information at the end of the run. IPython will give
511 print timing information at the end of the run. IPython will give
512 you an estimated CPU time consumption for your script, which under
512 you an estimated CPU time consumption for your script, which under
513 Unix uses the resource module to avoid the wraparound problems of
513 Unix uses the resource module to avoid the wraparound problems of
514 time.clock(). Under Unix, an estimate of time spent on system tasks
514 time.clock(). Under Unix, an estimate of time spent on system tasks
515 is also given (for Windows platforms this is reported as 0.0).
515 is also given (for Windows platforms this is reported as 0.0).
516
516
517 If -t is given, an additional ``-N<N>`` option can be given, where <N>
517 If -t is given, an additional ``-N<N>`` option can be given, where <N>
518 must be an integer indicating how many times you want the script to
518 must be an integer indicating how many times you want the script to
519 run. The final timing report will include total and per run results.
519 run. The final timing report will include total and per run results.
520
520
521 For example (testing the script uniq_stable.py)::
521 For example (testing the script uniq_stable.py)::
522
522
523 In [1]: run -t uniq_stable
523 In [1]: run -t uniq_stable
524
524
525 IPython CPU timings (estimated):
525 IPython CPU timings (estimated):
526 User : 0.19597 s.
526 User : 0.19597 s.
527 System: 0.0 s.
527 System: 0.0 s.
528
528
529 In [2]: run -t -N5 uniq_stable
529 In [2]: run -t -N5 uniq_stable
530
530
531 IPython CPU timings (estimated):
531 IPython CPU timings (estimated):
532 Total runs performed: 5
532 Total runs performed: 5
533 Times : Total Per run
533 Times : Total Per run
534 User : 0.910862 s, 0.1821724 s.
534 User : 0.910862 s, 0.1821724 s.
535 System: 0.0 s, 0.0 s.
535 System: 0.0 s, 0.0 s.
536
536
537 -d
537 -d
538 run your program under the control of pdb, the Python debugger.
538 run your program under the control of pdb, the Python debugger.
539 This allows you to execute your program step by step, watch variables,
539 This allows you to execute your program step by step, watch variables,
540 etc. Internally, what IPython does is similar to calling::
540 etc. Internally, what IPython does is similar to calling::
541
541
542 pdb.run('execfile("YOURFILENAME")')
542 pdb.run('execfile("YOURFILENAME")')
543
543
544 with a breakpoint set on line 1 of your file. You can change the line
544 with a breakpoint set on line 1 of your file. You can change the line
545 number for this automatic breakpoint to be <N> by using the -bN option
545 number for this automatic breakpoint to be <N> by using the -bN option
546 (where N must be an integer). For example::
546 (where N must be an integer). For example::
547
547
548 %run -d -b40 myscript
548 %run -d -b40 myscript
549
549
550 will set the first breakpoint at line 40 in myscript.py. Note that
550 will set the first breakpoint at line 40 in myscript.py. Note that
551 the first breakpoint must be set on a line which actually does
551 the first breakpoint must be set on a line which actually does
552 something (not a comment or docstring) for it to stop execution.
552 something (not a comment or docstring) for it to stop execution.
553
553
554 Or you can specify a breakpoint in a different file::
554 Or you can specify a breakpoint in a different file::
555
555
556 %run -d -b myotherfile.py:20 myscript
556 %run -d -b myotherfile.py:20 myscript
557
557
558 When the pdb debugger starts, you will see a (Pdb) prompt. You must
558 When the pdb debugger starts, you will see a (Pdb) prompt. You must
559 first enter 'c' (without quotes) to start execution up to the first
559 first enter 'c' (without quotes) to start execution up to the first
560 breakpoint.
560 breakpoint.
561
561
562 Entering 'help' gives information about the use of the debugger. You
562 Entering 'help' gives information about the use of the debugger. You
563 can easily see pdb's full documentation with "import pdb;pdb.help()"
563 can easily see pdb's full documentation with "import pdb;pdb.help()"
564 at a prompt.
564 at a prompt.
565
565
566 -p
566 -p
567 run program under the control of the Python profiler module (which
567 run program under the control of the Python profiler module (which
568 prints a detailed report of execution times, function calls, etc).
568 prints a detailed report of execution times, function calls, etc).
569
569
570 You can pass other options after -p which affect the behavior of the
570 You can pass other options after -p which affect the behavior of the
571 profiler itself. See the docs for %prun for details.
571 profiler itself. See the docs for %prun for details.
572
572
573 In this mode, the program's variables do NOT propagate back to the
573 In this mode, the program's variables do NOT propagate back to the
574 IPython interactive namespace (because they remain in the namespace
574 IPython interactive namespace (because they remain in the namespace
575 where the profiler executes them).
575 where the profiler executes them).
576
576
577 Internally this triggers a call to %prun, see its documentation for
577 Internally this triggers a call to %prun, see its documentation for
578 details on the options available specifically for profiling.
578 details on the options available specifically for profiling.
579
579
580 There is one special usage for which the text above doesn't apply:
580 There is one special usage for which the text above doesn't apply:
581 if the filename ends with .ipy[nb], the file is run as ipython script,
581 if the filename ends with .ipy[nb], the file is run as ipython script,
582 just as if the commands were written on IPython prompt.
582 just as if the commands were written on IPython prompt.
583
583
584 -m
584 -m
585 specify module name to load instead of script path. Similar to
585 specify module name to load instead of script path. Similar to
586 the -m option for the python interpreter. Use this option last if you
586 the -m option for the python interpreter. Use this option last if you
587 want to combine with other %run options. Unlike the python interpreter
587 want to combine with other %run options. Unlike the python interpreter
588 only source modules are allowed no .pyc or .pyo files.
588 only source modules are allowed no .pyc or .pyo files.
589 For example::
589 For example::
590
590
591 %run -m example
591 %run -m example
592
592
593 will run the example module.
593 will run the example module.
594
594
595 -G
595 -G
596 disable shell-like glob expansion of arguments.
596 disable shell-like glob expansion of arguments.
597
597
598 """
598 """
599
599
600 # get arguments and set sys.argv for program to be run.
600 # get arguments and set sys.argv for program to be run.
601 opts, arg_lst = self.parse_options(parameter_s,
601 opts, arg_lst = self.parse_options(parameter_s,
602 'nidtN:b:pD:l:rs:T:em:G',
602 'nidtN:b:pD:l:rs:T:em:G',
603 mode='list', list_all=1)
603 mode='list', list_all=1)
604 if "m" in opts:
604 if "m" in opts:
605 modulename = opts["m"][0]
605 modulename = opts["m"][0]
606 modpath = find_mod(modulename)
606 modpath = find_mod(modulename)
607 if modpath is None:
607 if modpath is None:
608 warn('%r is not a valid modulename on sys.path'%modulename)
608 warn('%r is not a valid modulename on sys.path'%modulename)
609 return
609 return
610 arg_lst = [modpath] + arg_lst
610 arg_lst = [modpath] + arg_lst
611 try:
611 try:
612 filename = file_finder(arg_lst[0])
612 filename = file_finder(arg_lst[0])
613 except IndexError:
613 except IndexError:
614 warn('you must provide at least a filename.')
614 warn('you must provide at least a filename.')
615 print('\n%run:\n', oinspect.getdoc(self.run))
615 print('\n%run:\n', oinspect.getdoc(self.run))
616 return
616 return
617 except IOError as e:
617 except IOError as e:
618 try:
618 try:
619 msg = str(e)
619 msg = str(e)
620 except UnicodeError:
620 except UnicodeError:
621 msg = e.message
621 msg = e.message
622 error(msg)
622 error(msg)
623 return
623 return
624
624
625 if filename.lower().endswith(('.ipy', '.ipynb')):
625 if filename.lower().endswith(('.ipy', '.ipynb')):
626 with preserve_keys(self.shell.user_ns, '__file__'):
626 with preserve_keys(self.shell.user_ns, '__file__'):
627 self.shell.user_ns['__file__'] = filename
627 self.shell.user_ns['__file__'] = filename
628 self.shell.safe_execfile_ipy(filename)
628 self.shell.safe_execfile_ipy(filename)
629 return
629 return
630
630
631 # Control the response to exit() calls made by the script being run
631 # Control the response to exit() calls made by the script being run
632 exit_ignore = 'e' in opts
632 exit_ignore = 'e' in opts
633
633
634 # Make sure that the running script gets a proper sys.argv as if it
634 # Make sure that the running script gets a proper sys.argv as if it
635 # were run from a system shell.
635 # were run from a system shell.
636 save_argv = sys.argv # save it for later restoring
636 save_argv = sys.argv # save it for later restoring
637
637
638 if 'G' in opts:
638 if 'G' in opts:
639 args = arg_lst[1:]
639 args = arg_lst[1:]
640 else:
640 else:
641 # tilde and glob expansion
641 # tilde and glob expansion
642 args = shellglob(map(os.path.expanduser, arg_lst[1:]))
642 args = shellglob(map(os.path.expanduser, arg_lst[1:]))
643
643
644 sys.argv = [filename] + args # put in the proper filename
644 sys.argv = [filename] + args # put in the proper filename
645 # protect sys.argv from potential unicode strings on Python 2:
645 # protect sys.argv from potential unicode strings on Python 2:
646 if not py3compat.PY3:
646 if not py3compat.PY3:
647 sys.argv = [ py3compat.cast_bytes(a) for a in sys.argv ]
647 sys.argv = [ py3compat.cast_bytes(a) for a in sys.argv ]
648
648
649 if 'i' in opts:
649 if 'i' in opts:
650 # Run in user's interactive namespace
650 # Run in user's interactive namespace
651 prog_ns = self.shell.user_ns
651 prog_ns = self.shell.user_ns
652 __name__save = self.shell.user_ns['__name__']
652 __name__save = self.shell.user_ns['__name__']
653 prog_ns['__name__'] = '__main__'
653 prog_ns['__name__'] = '__main__'
654 main_mod = self.shell.user_module
654 main_mod = self.shell.user_module
655
655
656 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
656 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
657 # set the __file__ global in the script's namespace
657 # set the __file__ global in the script's namespace
658 # TK: Is this necessary in interactive mode?
658 # TK: Is this necessary in interactive mode?
659 prog_ns['__file__'] = filename
659 prog_ns['__file__'] = filename
660 else:
660 else:
661 # Run in a fresh, empty namespace
661 # Run in a fresh, empty namespace
662 if 'n' in opts:
662 if 'n' in opts:
663 name = os.path.splitext(os.path.basename(filename))[0]
663 name = os.path.splitext(os.path.basename(filename))[0]
664 else:
664 else:
665 name = '__main__'
665 name = '__main__'
666
666
667 # The shell MUST hold a reference to prog_ns so after %run
667 # The shell MUST hold a reference to prog_ns so after %run
668 # exits, the python deletion mechanism doesn't zero it out
668 # exits, the python deletion mechanism doesn't zero it out
669 # (leaving dangling references). See interactiveshell for details
669 # (leaving dangling references). See interactiveshell for details
670 main_mod = self.shell.new_main_mod(filename, name)
670 main_mod = self.shell.new_main_mod(filename, name)
671 prog_ns = main_mod.__dict__
671 prog_ns = main_mod.__dict__
672
672
673 # pickle fix. See interactiveshell for an explanation. But we need to
673 # pickle fix. See interactiveshell for an explanation. But we need to
674 # make sure that, if we overwrite __main__, we replace it at the end
674 # make sure that, if we overwrite __main__, we replace it at the end
675 main_mod_name = prog_ns['__name__']
675 main_mod_name = prog_ns['__name__']
676
676
677 if main_mod_name == '__main__':
677 if main_mod_name == '__main__':
678 restore_main = sys.modules['__main__']
678 restore_main = sys.modules['__main__']
679 else:
679 else:
680 restore_main = False
680 restore_main = False
681
681
682 # This needs to be undone at the end to prevent holding references to
682 # This needs to be undone at the end to prevent holding references to
683 # every single object ever created.
683 # every single object ever created.
684 sys.modules[main_mod_name] = main_mod
684 sys.modules[main_mod_name] = main_mod
685
685
686 if 'p' in opts or 'd' in opts:
686 if 'p' in opts or 'd' in opts:
687 if 'm' in opts:
687 if 'm' in opts:
688 code = 'run_module(modulename, prog_ns)'
688 code = 'run_module(modulename, prog_ns)'
689 code_ns = {
689 code_ns = {
690 'run_module': self.shell.safe_run_module,
690 'run_module': self.shell.safe_run_module,
691 'prog_ns': prog_ns,
691 'prog_ns': prog_ns,
692 'modulename': modulename,
692 'modulename': modulename,
693 }
693 }
694 else:
694 else:
695 if 'd' in opts:
695 if 'd' in opts:
696 # allow exceptions to raise in debug mode
696 # allow exceptions to raise in debug mode
697 code = 'execfile(filename, prog_ns, raise_exceptions=True)'
697 code = 'execfile(filename, prog_ns, raise_exceptions=True)'
698 else:
698 else:
699 code = 'execfile(filename, prog_ns)'
699 code = 'execfile(filename, prog_ns)'
700 code_ns = {
700 code_ns = {
701 'execfile': self.shell.safe_execfile,
701 'execfile': self.shell.safe_execfile,
702 'prog_ns': prog_ns,
702 'prog_ns': prog_ns,
703 'filename': get_py_filename(filename),
703 'filename': get_py_filename(filename),
704 }
704 }
705
705
706 try:
706 try:
707 stats = None
707 stats = None
708 with self.shell.readline_no_record:
708 if 'p' in opts:
709 if 'p' in opts:
709 stats = self._run_with_profiler(code, opts, code_ns)
710 stats = self._run_with_profiler(code, opts, code_ns)
710 else:
711 if 'd' in opts:
712 bp_file, bp_line = parse_breakpoint(
713 opts.get('b', ['1'])[0], filename)
714 self._run_with_debugger(
715 code, code_ns, filename, bp_line, bp_file)
711 else:
716 else:
712 if 'd' in opts:
717 if 'm' in opts:
713 bp_file, bp_line = parse_breakpoint(
718 def run():
714 opts.get('b', ['1'])[0], filename)
719 self.shell.safe_run_module(modulename, prog_ns)
715 self._run_with_debugger(
716 code, code_ns, filename, bp_line, bp_file)
717 else:
720 else:
718 if 'm' in opts:
721 if runner is None:
719 def run():
722 runner = self.default_runner
720 self.shell.safe_run_module(modulename, prog_ns)
723 if runner is None:
721 else:
724 runner = self.shell.safe_execfile
722 if runner is None:
725
723 runner = self.default_runner
726 def run():
724 if runner is None:
727 runner(filename, prog_ns, prog_ns,
725 runner = self.shell.safe_execfile
728 exit_ignore=exit_ignore)
726
729
727 def run():
730 if 't' in opts:
728 runner(filename, prog_ns, prog_ns,
731 # timed execution
729 exit_ignore=exit_ignore)
732 try:
730
733 nruns = int(opts['N'][0])
731 if 't' in opts:
734 if nruns < 1:
732 # timed execution
735 error('Number of runs must be >=1')
733 try:
736 return
734 nruns = int(opts['N'][0])
737 except (KeyError):
735 if nruns < 1:
738 nruns = 1
736 error('Number of runs must be >=1')
739 self._run_with_timing(run, nruns)
737 return
740 else:
738 except (KeyError):
741 # regular execution
739 nruns = 1
742 run()
740 self._run_with_timing(run, nruns)
743
741 else:
744 if 'i' in opts:
742 # regular execution
745 self.shell.user_ns['__name__'] = __name__save
743 run()
746 else:
744
747 # update IPython interactive namespace
745 if 'i' in opts:
746 self.shell.user_ns['__name__'] = __name__save
747 else:
748 # update IPython interactive namespace
749
748
750 # Some forms of read errors on the file may mean the
749 # Some forms of read errors on the file may mean the
751 # __name__ key was never set; using pop we don't have to
750 # __name__ key was never set; using pop we don't have to
752 # worry about a possible KeyError.
751 # worry about a possible KeyError.
753 prog_ns.pop('__name__', None)
752 prog_ns.pop('__name__', None)
754
753
755 with preserve_keys(self.shell.user_ns, '__file__'):
754 with preserve_keys(self.shell.user_ns, '__file__'):
756 self.shell.user_ns.update(prog_ns)
755 self.shell.user_ns.update(prog_ns)
757 finally:
756 finally:
758 # It's a bit of a mystery why, but __builtins__ can change from
757 # It's a bit of a mystery why, but __builtins__ can change from
759 # being a module to becoming a dict missing some key data after
758 # being a module to becoming a dict missing some key data after
760 # %run. As best I can see, this is NOT something IPython is doing
759 # %run. As best I can see, this is NOT something IPython is doing
761 # at all, and similar problems have been reported before:
760 # at all, and similar problems have been reported before:
762 # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html
761 # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html
763 # Since this seems to be done by the interpreter itself, the best
762 # Since this seems to be done by the interpreter itself, the best
764 # we can do is to at least restore __builtins__ for the user on
763 # we can do is to at least restore __builtins__ for the user on
765 # exit.
764 # exit.
766 self.shell.user_ns['__builtins__'] = builtin_mod
765 self.shell.user_ns['__builtins__'] = builtin_mod
767
766
768 # Ensure key global structures are restored
767 # Ensure key global structures are restored
769 sys.argv = save_argv
768 sys.argv = save_argv
770 if restore_main:
769 if restore_main:
771 sys.modules['__main__'] = restore_main
770 sys.modules['__main__'] = restore_main
772 else:
771 else:
773 # Remove from sys.modules the reference to main_mod we'd
772 # Remove from sys.modules the reference to main_mod we'd
774 # added. Otherwise it will trap references to objects
773 # added. Otherwise it will trap references to objects
775 # contained therein.
774 # contained therein.
776 del sys.modules[main_mod_name]
775 del sys.modules[main_mod_name]
777
776
778 return stats
777 return stats
779
778
780 def _run_with_debugger(self, code, code_ns, filename=None,
779 def _run_with_debugger(self, code, code_ns, filename=None,
781 bp_line=None, bp_file=None):
780 bp_line=None, bp_file=None):
782 """
781 """
783 Run `code` in debugger with a break point.
782 Run `code` in debugger with a break point.
784
783
785 Parameters
784 Parameters
786 ----------
785 ----------
787 code : str
786 code : str
788 Code to execute.
787 Code to execute.
789 code_ns : dict
788 code_ns : dict
790 A namespace in which `code` is executed.
789 A namespace in which `code` is executed.
791 filename : str
790 filename : str
792 `code` is ran as if it is in `filename`.
791 `code` is ran as if it is in `filename`.
793 bp_line : int, optional
792 bp_line : int, optional
794 Line number of the break point.
793 Line number of the break point.
795 bp_file : str, optional
794 bp_file : str, optional
796 Path to the file in which break point is specified.
795 Path to the file in which break point is specified.
797 `filename` is used if not given.
796 `filename` is used if not given.
798
797
799 Raises
798 Raises
800 ------
799 ------
801 UsageError
800 UsageError
802 If the break point given by `bp_line` is not valid.
801 If the break point given by `bp_line` is not valid.
803
802
804 """
803 """
805 deb = debugger.Pdb(self.shell.colors)
804 deb = debugger.Pdb(self.shell.colors)
806 # reset Breakpoint state, which is moronically kept
805 # reset Breakpoint state, which is moronically kept
807 # in a class
806 # in a class
808 bdb.Breakpoint.next = 1
807 bdb.Breakpoint.next = 1
809 bdb.Breakpoint.bplist = {}
808 bdb.Breakpoint.bplist = {}
810 bdb.Breakpoint.bpbynumber = [None]
809 bdb.Breakpoint.bpbynumber = [None]
811 if bp_line is not None:
810 if bp_line is not None:
812 # Set an initial breakpoint to stop execution
811 # Set an initial breakpoint to stop execution
813 maxtries = 10
812 maxtries = 10
814 bp_file = bp_file or filename
813 bp_file = bp_file or filename
815 checkline = deb.checkline(bp_file, bp_line)
814 checkline = deb.checkline(bp_file, bp_line)
816 if not checkline:
815 if not checkline:
817 for bp in range(bp_line + 1, bp_line + maxtries + 1):
816 for bp in range(bp_line + 1, bp_line + maxtries + 1):
818 if deb.checkline(bp_file, bp):
817 if deb.checkline(bp_file, bp):
819 break
818 break
820 else:
819 else:
821 msg = ("\nI failed to find a valid line to set "
820 msg = ("\nI failed to find a valid line to set "
822 "a breakpoint\n"
821 "a breakpoint\n"
823 "after trying up to line: %s.\n"
822 "after trying up to line: %s.\n"
824 "Please set a valid breakpoint manually "
823 "Please set a valid breakpoint manually "
825 "with the -b option." % bp)
824 "with the -b option." % bp)
826 raise UsageError(msg)
825 raise UsageError(msg)
827 # if we find a good linenumber, set the breakpoint
826 # if we find a good linenumber, set the breakpoint
828 deb.do_break('%s:%s' % (bp_file, bp_line))
827 deb.do_break('%s:%s' % (bp_file, bp_line))
829
828
830 if filename:
829 if filename:
831 # Mimic Pdb._runscript(...)
830 # Mimic Pdb._runscript(...)
832 deb._wait_for_mainpyfile = True
831 deb._wait_for_mainpyfile = True
833 deb.mainpyfile = deb.canonic(filename)
832 deb.mainpyfile = deb.canonic(filename)
834
833
835 # Start file run
834 # Start file run
836 print("NOTE: Enter 'c' at the %s prompt to continue execution." % deb.prompt)
835 print("NOTE: Enter 'c' at the %s prompt to continue execution." % deb.prompt)
837 try:
836 try:
838 if filename:
837 if filename:
839 # save filename so it can be used by methods on the deb object
838 # save filename so it can be used by methods on the deb object
840 deb._exec_filename = filename
839 deb._exec_filename = filename
841 while True:
840 while True:
842 try:
841 try:
843 deb.run(code, code_ns)
842 deb.run(code, code_ns)
844 except Restart:
843 except Restart:
845 print("Restarting")
844 print("Restarting")
846 if filename:
845 if filename:
847 deb._wait_for_mainpyfile = True
846 deb._wait_for_mainpyfile = True
848 deb.mainpyfile = deb.canonic(filename)
847 deb.mainpyfile = deb.canonic(filename)
849 continue
848 continue
850 else:
849 else:
851 break
850 break
852
851
853
852
854 except:
853 except:
855 etype, value, tb = sys.exc_info()
854 etype, value, tb = sys.exc_info()
856 # Skip three frames in the traceback: the %run one,
855 # Skip three frames in the traceback: the %run one,
857 # one inside bdb.py, and the command-line typed by the
856 # one inside bdb.py, and the command-line typed by the
858 # user (run by exec in pdb itself).
857 # user (run by exec in pdb itself).
859 self.shell.InteractiveTB(etype, value, tb, tb_offset=3)
858 self.shell.InteractiveTB(etype, value, tb, tb_offset=3)
860
859
861 @staticmethod
860 @staticmethod
862 def _run_with_timing(run, nruns):
861 def _run_with_timing(run, nruns):
863 """
862 """
864 Run function `run` and print timing information.
863 Run function `run` and print timing information.
865
864
866 Parameters
865 Parameters
867 ----------
866 ----------
868 run : callable
867 run : callable
869 Any callable object which takes no argument.
868 Any callable object which takes no argument.
870 nruns : int
869 nruns : int
871 Number of times to execute `run`.
870 Number of times to execute `run`.
872
871
873 """
872 """
874 twall0 = time.time()
873 twall0 = time.time()
875 if nruns == 1:
874 if nruns == 1:
876 t0 = clock2()
875 t0 = clock2()
877 run()
876 run()
878 t1 = clock2()
877 t1 = clock2()
879 t_usr = t1[0] - t0[0]
878 t_usr = t1[0] - t0[0]
880 t_sys = t1[1] - t0[1]
879 t_sys = t1[1] - t0[1]
881 print("\nIPython CPU timings (estimated):")
880 print("\nIPython CPU timings (estimated):")
882 print(" User : %10.2f s." % t_usr)
881 print(" User : %10.2f s." % t_usr)
883 print(" System : %10.2f s." % t_sys)
882 print(" System : %10.2f s." % t_sys)
884 else:
883 else:
885 runs = range(nruns)
884 runs = range(nruns)
886 t0 = clock2()
885 t0 = clock2()
887 for nr in runs:
886 for nr in runs:
888 run()
887 run()
889 t1 = clock2()
888 t1 = clock2()
890 t_usr = t1[0] - t0[0]
889 t_usr = t1[0] - t0[0]
891 t_sys = t1[1] - t0[1]
890 t_sys = t1[1] - t0[1]
892 print("\nIPython CPU timings (estimated):")
891 print("\nIPython CPU timings (estimated):")
893 print("Total runs performed:", nruns)
892 print("Total runs performed:", nruns)
894 print(" Times : %10s %10s" % ('Total', 'Per run'))
893 print(" Times : %10s %10s" % ('Total', 'Per run'))
895 print(" User : %10.2f s, %10.2f s." % (t_usr, t_usr / nruns))
894 print(" User : %10.2f s, %10.2f s." % (t_usr, t_usr / nruns))
896 print(" System : %10.2f s, %10.2f s." % (t_sys, t_sys / nruns))
895 print(" System : %10.2f s, %10.2f s." % (t_sys, t_sys / nruns))
897 twall1 = time.time()
896 twall1 = time.time()
898 print("Wall time: %10.2f s." % (twall1 - twall0))
897 print("Wall time: %10.2f s." % (twall1 - twall0))
899
898
900 @skip_doctest
899 @skip_doctest
901 @line_cell_magic
900 @line_cell_magic
902 def timeit(self, line='', cell=None):
901 def timeit(self, line='', cell=None):
903 """Time execution of a Python statement or expression
902 """Time execution of a Python statement or expression
904
903
905 Usage, in line mode:
904 Usage, in line mode:
906 %timeit [-n<N> -r<R> [-t|-c] -q -p<P> -o] statement
905 %timeit [-n<N> -r<R> [-t|-c] -q -p<P> -o] statement
907 or in cell mode:
906 or in cell mode:
908 %%timeit [-n<N> -r<R> [-t|-c] -q -p<P> -o] setup_code
907 %%timeit [-n<N> -r<R> [-t|-c] -q -p<P> -o] setup_code
909 code
908 code
910 code...
909 code...
911
910
912 Time execution of a Python statement or expression using the timeit
911 Time execution of a Python statement or expression using the timeit
913 module. This function can be used both as a line and cell magic:
912 module. This function can be used both as a line and cell magic:
914
913
915 - In line mode you can time a single-line statement (though multiple
914 - In line mode you can time a single-line statement (though multiple
916 ones can be chained with using semicolons).
915 ones can be chained with using semicolons).
917
916
918 - In cell mode, the statement in the first line is used as setup code
917 - In cell mode, the statement in the first line is used as setup code
919 (executed but not timed) and the body of the cell is timed. The cell
918 (executed but not timed) and the body of the cell is timed. The cell
920 body has access to any variables created in the setup code.
919 body has access to any variables created in the setup code.
921
920
922 Options:
921 Options:
923 -n<N>: execute the given statement <N> times in a loop. If this value
922 -n<N>: execute the given statement <N> times in a loop. If this value
924 is not given, a fitting value is chosen.
923 is not given, a fitting value is chosen.
925
924
926 -r<R>: repeat the loop iteration <R> times and take the best result.
925 -r<R>: repeat the loop iteration <R> times and take the best result.
927 Default: 3
926 Default: 3
928
927
929 -t: use time.time to measure the time, which is the default on Unix.
928 -t: use time.time to measure the time, which is the default on Unix.
930 This function measures wall time.
929 This function measures wall time.
931
930
932 -c: use time.clock to measure the time, which is the default on
931 -c: use time.clock to measure the time, which is the default on
933 Windows and measures wall time. On Unix, resource.getrusage is used
932 Windows and measures wall time. On Unix, resource.getrusage is used
934 instead and returns the CPU user time.
933 instead and returns the CPU user time.
935
934
936 -p<P>: use a precision of <P> digits to display the timing result.
935 -p<P>: use a precision of <P> digits to display the timing result.
937 Default: 3
936 Default: 3
938
937
939 -q: Quiet, do not print result.
938 -q: Quiet, do not print result.
940
939
941 -o: return a TimeitResult that can be stored in a variable to inspect
940 -o: return a TimeitResult that can be stored in a variable to inspect
942 the result in more details.
941 the result in more details.
943
942
944
943
945 Examples
944 Examples
946 --------
945 --------
947 ::
946 ::
948
947
949 In [1]: %timeit pass
948 In [1]: %timeit pass
950 10000000 loops, best of 3: 53.3 ns per loop
949 10000000 loops, best of 3: 53.3 ns per loop
951
950
952 In [2]: u = None
951 In [2]: u = None
953
952
954 In [3]: %timeit u is None
953 In [3]: %timeit u is None
955 10000000 loops, best of 3: 184 ns per loop
954 10000000 loops, best of 3: 184 ns per loop
956
955
957 In [4]: %timeit -r 4 u == None
956 In [4]: %timeit -r 4 u == None
958 1000000 loops, best of 4: 242 ns per loop
957 1000000 loops, best of 4: 242 ns per loop
959
958
960 In [5]: import time
959 In [5]: import time
961
960
962 In [6]: %timeit -n1 time.sleep(2)
961 In [6]: %timeit -n1 time.sleep(2)
963 1 loop, best of 3: 2 s per loop
962 1 loop, best of 3: 2 s per loop
964
963
965
964
966 The times reported by %timeit will be slightly higher than those
965 The times reported by %timeit will be slightly higher than those
967 reported by the timeit.py script when variables are accessed. This is
966 reported by the timeit.py script when variables are accessed. This is
968 due to the fact that %timeit executes the statement in the namespace
967 due to the fact that %timeit executes the statement in the namespace
969 of the shell, compared with timeit.py, which uses a single setup
968 of the shell, compared with timeit.py, which uses a single setup
970 statement to import function or create variables. Generally, the bias
969 statement to import function or create variables. Generally, the bias
971 does not matter as long as results from timeit.py are not mixed with
970 does not matter as long as results from timeit.py are not mixed with
972 those from %timeit."""
971 those from %timeit."""
973
972
974 opts, stmt = self.parse_options(line,'n:r:tcp:qo',
973 opts, stmt = self.parse_options(line,'n:r:tcp:qo',
975 posix=False, strict=False)
974 posix=False, strict=False)
976 if stmt == "" and cell is None:
975 if stmt == "" and cell is None:
977 return
976 return
978
977
979 timefunc = timeit.default_timer
978 timefunc = timeit.default_timer
980 number = int(getattr(opts, "n", 0))
979 number = int(getattr(opts, "n", 0))
981 repeat = int(getattr(opts, "r", timeit.default_repeat))
980 repeat = int(getattr(opts, "r", timeit.default_repeat))
982 precision = int(getattr(opts, "p", 3))
981 precision = int(getattr(opts, "p", 3))
983 quiet = 'q' in opts
982 quiet = 'q' in opts
984 return_result = 'o' in opts
983 return_result = 'o' in opts
985 if hasattr(opts, "t"):
984 if hasattr(opts, "t"):
986 timefunc = time.time
985 timefunc = time.time
987 if hasattr(opts, "c"):
986 if hasattr(opts, "c"):
988 timefunc = clock
987 timefunc = clock
989
988
990 timer = Timer(timer=timefunc)
989 timer = Timer(timer=timefunc)
991 # this code has tight coupling to the inner workings of timeit.Timer,
990 # this code has tight coupling to the inner workings of timeit.Timer,
992 # but is there a better way to achieve that the code stmt has access
991 # but is there a better way to achieve that the code stmt has access
993 # to the shell namespace?
992 # to the shell namespace?
994 transform = self.shell.input_splitter.transform_cell
993 transform = self.shell.input_splitter.transform_cell
995
994
996 if cell is None:
995 if cell is None:
997 # called as line magic
996 # called as line magic
998 ast_setup = self.shell.compile.ast_parse("pass")
997 ast_setup = self.shell.compile.ast_parse("pass")
999 ast_stmt = self.shell.compile.ast_parse(transform(stmt))
998 ast_stmt = self.shell.compile.ast_parse(transform(stmt))
1000 else:
999 else:
1001 ast_setup = self.shell.compile.ast_parse(transform(stmt))
1000 ast_setup = self.shell.compile.ast_parse(transform(stmt))
1002 ast_stmt = self.shell.compile.ast_parse(transform(cell))
1001 ast_stmt = self.shell.compile.ast_parse(transform(cell))
1003
1002
1004 ast_setup = self.shell.transform_ast(ast_setup)
1003 ast_setup = self.shell.transform_ast(ast_setup)
1005 ast_stmt = self.shell.transform_ast(ast_stmt)
1004 ast_stmt = self.shell.transform_ast(ast_stmt)
1006
1005
1007 # This codestring is taken from timeit.template - we fill it in as an
1006 # This codestring is taken from timeit.template - we fill it in as an
1008 # AST, so that we can apply our AST transformations to the user code
1007 # AST, so that we can apply our AST transformations to the user code
1009 # without affecting the timing code.
1008 # without affecting the timing code.
1010 timeit_ast_template = ast.parse('def inner(_it, _timer):\n'
1009 timeit_ast_template = ast.parse('def inner(_it, _timer):\n'
1011 ' setup\n'
1010 ' setup\n'
1012 ' _t0 = _timer()\n'
1011 ' _t0 = _timer()\n'
1013 ' for _i in _it:\n'
1012 ' for _i in _it:\n'
1014 ' stmt\n'
1013 ' stmt\n'
1015 ' _t1 = _timer()\n'
1014 ' _t1 = _timer()\n'
1016 ' return _t1 - _t0\n')
1015 ' return _t1 - _t0\n')
1017
1016
1018 timeit_ast = TimeitTemplateFiller(ast_setup, ast_stmt).visit(timeit_ast_template)
1017 timeit_ast = TimeitTemplateFiller(ast_setup, ast_stmt).visit(timeit_ast_template)
1019 timeit_ast = ast.fix_missing_locations(timeit_ast)
1018 timeit_ast = ast.fix_missing_locations(timeit_ast)
1020
1019
1021 # Track compilation time so it can be reported if too long
1020 # Track compilation time so it can be reported if too long
1022 # Minimum time above which compilation time will be reported
1021 # Minimum time above which compilation time will be reported
1023 tc_min = 0.1
1022 tc_min = 0.1
1024
1023
1025 t0 = clock()
1024 t0 = clock()
1026 code = self.shell.compile(timeit_ast, "<magic-timeit>", "exec")
1025 code = self.shell.compile(timeit_ast, "<magic-timeit>", "exec")
1027 tc = clock()-t0
1026 tc = clock()-t0
1028
1027
1029 ns = {}
1028 ns = {}
1030 exec(code, self.shell.user_ns, ns)
1029 exec(code, self.shell.user_ns, ns)
1031 timer.inner = ns["inner"]
1030 timer.inner = ns["inner"]
1032
1031
1033 # This is used to check if there is a huge difference between the
1032 # This is used to check if there is a huge difference between the
1034 # best and worst timings.
1033 # best and worst timings.
1035 # Issue: https://github.com/ipython/ipython/issues/6471
1034 # Issue: https://github.com/ipython/ipython/issues/6471
1036 worst_tuning = 0
1035 worst_tuning = 0
1037 if number == 0:
1036 if number == 0:
1038 # determine number so that 0.2 <= total time < 2.0
1037 # determine number so that 0.2 <= total time < 2.0
1039 number = 1
1038 number = 1
1040 for _ in range(1, 10):
1039 for _ in range(1, 10):
1041 time_number = timer.timeit(number)
1040 time_number = timer.timeit(number)
1042 worst_tuning = max(worst_tuning, time_number / number)
1041 worst_tuning = max(worst_tuning, time_number / number)
1043 if time_number >= 0.2:
1042 if time_number >= 0.2:
1044 break
1043 break
1045 number *= 10
1044 number *= 10
1046 all_runs = timer.repeat(repeat, number)
1045 all_runs = timer.repeat(repeat, number)
1047 best = min(all_runs) / number
1046 best = min(all_runs) / number
1048
1047
1049 worst = max(all_runs) / number
1048 worst = max(all_runs) / number
1050 if worst_tuning:
1049 if worst_tuning:
1051 worst = max(worst, worst_tuning)
1050 worst = max(worst, worst_tuning)
1052
1051
1053 if not quiet :
1052 if not quiet :
1054 # Check best timing is greater than zero to avoid a
1053 # Check best timing is greater than zero to avoid a
1055 # ZeroDivisionError.
1054 # ZeroDivisionError.
1056 # In cases where the slowest timing is lesser than a micosecond
1055 # In cases where the slowest timing is lesser than a micosecond
1057 # we assume that it does not really matter if the fastest
1056 # we assume that it does not really matter if the fastest
1058 # timing is 4 times faster than the slowest timing or not.
1057 # timing is 4 times faster than the slowest timing or not.
1059 if worst > 4 * best and best > 0 and worst > 1e-6:
1058 if worst > 4 * best and best > 0 and worst > 1e-6:
1060 print("The slowest run took %0.2f times longer than the "
1059 print("The slowest run took %0.2f times longer than the "
1061 "fastest. This could mean that an intermediate result "
1060 "fastest. This could mean that an intermediate result "
1062 "is being cached." % (worst / best))
1061 "is being cached." % (worst / best))
1063 if number == 1: # No s at "loops" if only one loop
1062 if number == 1: # No s at "loops" if only one loop
1064 print(u"%d loop, best of %d: %s per loop" % (number, repeat,
1063 print(u"%d loop, best of %d: %s per loop" % (number, repeat,
1065 _format_time(best, precision)))
1064 _format_time(best, precision)))
1066 else:
1065 else:
1067 print(u"%d loops, best of %d: %s per loop" % (number, repeat,
1066 print(u"%d loops, best of %d: %s per loop" % (number, repeat,
1068 _format_time(best, precision)))
1067 _format_time(best, precision)))
1069 if tc > tc_min:
1068 if tc > tc_min:
1070 print("Compiler time: %.2f s" % tc)
1069 print("Compiler time: %.2f s" % tc)
1071 if return_result:
1070 if return_result:
1072 return TimeitResult(number, repeat, best, worst, all_runs, tc, precision)
1071 return TimeitResult(number, repeat, best, worst, all_runs, tc, precision)
1073
1072
1074 @skip_doctest
1073 @skip_doctest
1075 @needs_local_scope
1074 @needs_local_scope
1076 @line_cell_magic
1075 @line_cell_magic
1077 def time(self,line='', cell=None, local_ns=None):
1076 def time(self,line='', cell=None, local_ns=None):
1078 """Time execution of a Python statement or expression.
1077 """Time execution of a Python statement or expression.
1079
1078
1080 The CPU and wall clock times are printed, and the value of the
1079 The CPU and wall clock times are printed, and the value of the
1081 expression (if any) is returned. Note that under Win32, system time
1080 expression (if any) is returned. Note that under Win32, system time
1082 is always reported as 0, since it can not be measured.
1081 is always reported as 0, since it can not be measured.
1083
1082
1084 This function can be used both as a line and cell magic:
1083 This function can be used both as a line and cell magic:
1085
1084
1086 - In line mode you can time a single-line statement (though multiple
1085 - In line mode you can time a single-line statement (though multiple
1087 ones can be chained with using semicolons).
1086 ones can be chained with using semicolons).
1088
1087
1089 - In cell mode, you can time the cell body (a directly
1088 - In cell mode, you can time the cell body (a directly
1090 following statement raises an error).
1089 following statement raises an error).
1091
1090
1092 This function provides very basic timing functionality. Use the timeit
1091 This function provides very basic timing functionality. Use the timeit
1093 magic for more control over the measurement.
1092 magic for more control over the measurement.
1094
1093
1095 Examples
1094 Examples
1096 --------
1095 --------
1097 ::
1096 ::
1098
1097
1099 In [1]: %time 2**128
1098 In [1]: %time 2**128
1100 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1099 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1101 Wall time: 0.00
1100 Wall time: 0.00
1102 Out[1]: 340282366920938463463374607431768211456L
1101 Out[1]: 340282366920938463463374607431768211456L
1103
1102
1104 In [2]: n = 1000000
1103 In [2]: n = 1000000
1105
1104
1106 In [3]: %time sum(range(n))
1105 In [3]: %time sum(range(n))
1107 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1106 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1108 Wall time: 1.37
1107 Wall time: 1.37
1109 Out[3]: 499999500000L
1108 Out[3]: 499999500000L
1110
1109
1111 In [4]: %time print 'hello world'
1110 In [4]: %time print 'hello world'
1112 hello world
1111 hello world
1113 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1112 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1114 Wall time: 0.00
1113 Wall time: 0.00
1115
1114
1116 Note that the time needed by Python to compile the given expression
1115 Note that the time needed by Python to compile the given expression
1117 will be reported if it is more than 0.1s. In this example, the
1116 will be reported if it is more than 0.1s. In this example, the
1118 actual exponentiation is done by Python at compilation time, so while
1117 actual exponentiation is done by Python at compilation time, so while
1119 the expression can take a noticeable amount of time to compute, that
1118 the expression can take a noticeable amount of time to compute, that
1120 time is purely due to the compilation:
1119 time is purely due to the compilation:
1121
1120
1122 In [5]: %time 3**9999;
1121 In [5]: %time 3**9999;
1123 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1122 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1124 Wall time: 0.00 s
1123 Wall time: 0.00 s
1125
1124
1126 In [6]: %time 3**999999;
1125 In [6]: %time 3**999999;
1127 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1126 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1128 Wall time: 0.00 s
1127 Wall time: 0.00 s
1129 Compiler : 0.78 s
1128 Compiler : 0.78 s
1130 """
1129 """
1131
1130
1132 # fail immediately if the given expression can't be compiled
1131 # fail immediately if the given expression can't be compiled
1133
1132
1134 if line and cell:
1133 if line and cell:
1135 raise UsageError("Can't use statement directly after '%%time'!")
1134 raise UsageError("Can't use statement directly after '%%time'!")
1136
1135
1137 if cell:
1136 if cell:
1138 expr = self.shell.input_transformer_manager.transform_cell(cell)
1137 expr = self.shell.input_transformer_manager.transform_cell(cell)
1139 else:
1138 else:
1140 expr = self.shell.input_transformer_manager.transform_cell(line)
1139 expr = self.shell.input_transformer_manager.transform_cell(line)
1141
1140
1142 # Minimum time above which parse time will be reported
1141 # Minimum time above which parse time will be reported
1143 tp_min = 0.1
1142 tp_min = 0.1
1144
1143
1145 t0 = clock()
1144 t0 = clock()
1146 expr_ast = self.shell.compile.ast_parse(expr)
1145 expr_ast = self.shell.compile.ast_parse(expr)
1147 tp = clock()-t0
1146 tp = clock()-t0
1148
1147
1149 # Apply AST transformations
1148 # Apply AST transformations
1150 expr_ast = self.shell.transform_ast(expr_ast)
1149 expr_ast = self.shell.transform_ast(expr_ast)
1151
1150
1152 # Minimum time above which compilation time will be reported
1151 # Minimum time above which compilation time will be reported
1153 tc_min = 0.1
1152 tc_min = 0.1
1154
1153
1155 if len(expr_ast.body)==1 and isinstance(expr_ast.body[0], ast.Expr):
1154 if len(expr_ast.body)==1 and isinstance(expr_ast.body[0], ast.Expr):
1156 mode = 'eval'
1155 mode = 'eval'
1157 source = '<timed eval>'
1156 source = '<timed eval>'
1158 expr_ast = ast.Expression(expr_ast.body[0].value)
1157 expr_ast = ast.Expression(expr_ast.body[0].value)
1159 else:
1158 else:
1160 mode = 'exec'
1159 mode = 'exec'
1161 source = '<timed exec>'
1160 source = '<timed exec>'
1162 t0 = clock()
1161 t0 = clock()
1163 code = self.shell.compile(expr_ast, source, mode)
1162 code = self.shell.compile(expr_ast, source, mode)
1164 tc = clock()-t0
1163 tc = clock()-t0
1165
1164
1166 # skew measurement as little as possible
1165 # skew measurement as little as possible
1167 glob = self.shell.user_ns
1166 glob = self.shell.user_ns
1168 wtime = time.time
1167 wtime = time.time
1169 # time execution
1168 # time execution
1170 wall_st = wtime()
1169 wall_st = wtime()
1171 if mode=='eval':
1170 if mode=='eval':
1172 st = clock2()
1171 st = clock2()
1173 out = eval(code, glob, local_ns)
1172 out = eval(code, glob, local_ns)
1174 end = clock2()
1173 end = clock2()
1175 else:
1174 else:
1176 st = clock2()
1175 st = clock2()
1177 exec(code, glob, local_ns)
1176 exec(code, glob, local_ns)
1178 end = clock2()
1177 end = clock2()
1179 out = None
1178 out = None
1180 wall_end = wtime()
1179 wall_end = wtime()
1181 # Compute actual times and report
1180 # Compute actual times and report
1182 wall_time = wall_end-wall_st
1181 wall_time = wall_end-wall_st
1183 cpu_user = end[0]-st[0]
1182 cpu_user = end[0]-st[0]
1184 cpu_sys = end[1]-st[1]
1183 cpu_sys = end[1]-st[1]
1185 cpu_tot = cpu_user+cpu_sys
1184 cpu_tot = cpu_user+cpu_sys
1186 # On windows cpu_sys is always zero, so no new information to the next print
1185 # On windows cpu_sys is always zero, so no new information to the next print
1187 if sys.platform != 'win32':
1186 if sys.platform != 'win32':
1188 print("CPU times: user %s, sys: %s, total: %s" % \
1187 print("CPU times: user %s, sys: %s, total: %s" % \
1189 (_format_time(cpu_user),_format_time(cpu_sys),_format_time(cpu_tot)))
1188 (_format_time(cpu_user),_format_time(cpu_sys),_format_time(cpu_tot)))
1190 print("Wall time: %s" % _format_time(wall_time))
1189 print("Wall time: %s" % _format_time(wall_time))
1191 if tc > tc_min:
1190 if tc > tc_min:
1192 print("Compiler : %s" % _format_time(tc))
1191 print("Compiler : %s" % _format_time(tc))
1193 if tp > tp_min:
1192 if tp > tp_min:
1194 print("Parser : %s" % _format_time(tp))
1193 print("Parser : %s" % _format_time(tp))
1195 return out
1194 return out
1196
1195
1197 @skip_doctest
1196 @skip_doctest
1198 @line_magic
1197 @line_magic
1199 def macro(self, parameter_s=''):
1198 def macro(self, parameter_s=''):
1200 """Define a macro for future re-execution. It accepts ranges of history,
1199 """Define a macro for future re-execution. It accepts ranges of history,
1201 filenames or string objects.
1200 filenames or string objects.
1202
1201
1203 Usage:\\
1202 Usage:\\
1204 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
1203 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
1205
1204
1206 Options:
1205 Options:
1207
1206
1208 -r: use 'raw' input. By default, the 'processed' history is used,
1207 -r: use 'raw' input. By default, the 'processed' history is used,
1209 so that magics are loaded in their transformed version to valid
1208 so that magics are loaded in their transformed version to valid
1210 Python. If this option is given, the raw input as typed at the
1209 Python. If this option is given, the raw input as typed at the
1211 command line is used instead.
1210 command line is used instead.
1212
1211
1213 -q: quiet macro definition. By default, a tag line is printed
1212 -q: quiet macro definition. By default, a tag line is printed
1214 to indicate the macro has been created, and then the contents of
1213 to indicate the macro has been created, and then the contents of
1215 the macro are printed. If this option is given, then no printout
1214 the macro are printed. If this option is given, then no printout
1216 is produced once the macro is created.
1215 is produced once the macro is created.
1217
1216
1218 This will define a global variable called `name` which is a string
1217 This will define a global variable called `name` which is a string
1219 made of joining the slices and lines you specify (n1,n2,... numbers
1218 made of joining the slices and lines you specify (n1,n2,... numbers
1220 above) from your input history into a single string. This variable
1219 above) from your input history into a single string. This variable
1221 acts like an automatic function which re-executes those lines as if
1220 acts like an automatic function which re-executes those lines as if
1222 you had typed them. You just type 'name' at the prompt and the code
1221 you had typed them. You just type 'name' at the prompt and the code
1223 executes.
1222 executes.
1224
1223
1225 The syntax for indicating input ranges is described in %history.
1224 The syntax for indicating input ranges is described in %history.
1226
1225
1227 Note: as a 'hidden' feature, you can also use traditional python slice
1226 Note: as a 'hidden' feature, you can also use traditional python slice
1228 notation, where N:M means numbers N through M-1.
1227 notation, where N:M means numbers N through M-1.
1229
1228
1230 For example, if your history contains (print using %hist -n )::
1229 For example, if your history contains (print using %hist -n )::
1231
1230
1232 44: x=1
1231 44: x=1
1233 45: y=3
1232 45: y=3
1234 46: z=x+y
1233 46: z=x+y
1235 47: print x
1234 47: print x
1236 48: a=5
1235 48: a=5
1237 49: print 'x',x,'y',y
1236 49: print 'x',x,'y',y
1238
1237
1239 you can create a macro with lines 44 through 47 (included) and line 49
1238 you can create a macro with lines 44 through 47 (included) and line 49
1240 called my_macro with::
1239 called my_macro with::
1241
1240
1242 In [55]: %macro my_macro 44-47 49
1241 In [55]: %macro my_macro 44-47 49
1243
1242
1244 Now, typing `my_macro` (without quotes) will re-execute all this code
1243 Now, typing `my_macro` (without quotes) will re-execute all this code
1245 in one pass.
1244 in one pass.
1246
1245
1247 You don't need to give the line-numbers in order, and any given line
1246 You don't need to give the line-numbers in order, and any given line
1248 number can appear multiple times. You can assemble macros with any
1247 number can appear multiple times. You can assemble macros with any
1249 lines from your input history in any order.
1248 lines from your input history in any order.
1250
1249
1251 The macro is a simple object which holds its value in an attribute,
1250 The macro is a simple object which holds its value in an attribute,
1252 but IPython's display system checks for macros and executes them as
1251 but IPython's display system checks for macros and executes them as
1253 code instead of printing them when you type their name.
1252 code instead of printing them when you type their name.
1254
1253
1255 You can view a macro's contents by explicitly printing it with::
1254 You can view a macro's contents by explicitly printing it with::
1256
1255
1257 print macro_name
1256 print macro_name
1258
1257
1259 """
1258 """
1260 opts,args = self.parse_options(parameter_s,'rq',mode='list')
1259 opts,args = self.parse_options(parameter_s,'rq',mode='list')
1261 if not args: # List existing macros
1260 if not args: # List existing macros
1262 return sorted(k for k,v in iteritems(self.shell.user_ns) if\
1261 return sorted(k for k,v in iteritems(self.shell.user_ns) if\
1263 isinstance(v, Macro))
1262 isinstance(v, Macro))
1264 if len(args) == 1:
1263 if len(args) == 1:
1265 raise UsageError(
1264 raise UsageError(
1266 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
1265 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
1267 name, codefrom = args[0], " ".join(args[1:])
1266 name, codefrom = args[0], " ".join(args[1:])
1268
1267
1269 #print 'rng',ranges # dbg
1268 #print 'rng',ranges # dbg
1270 try:
1269 try:
1271 lines = self.shell.find_user_code(codefrom, 'r' in opts)
1270 lines = self.shell.find_user_code(codefrom, 'r' in opts)
1272 except (ValueError, TypeError) as e:
1271 except (ValueError, TypeError) as e:
1273 print(e.args[0])
1272 print(e.args[0])
1274 return
1273 return
1275 macro = Macro(lines)
1274 macro = Macro(lines)
1276 self.shell.define_macro(name, macro)
1275 self.shell.define_macro(name, macro)
1277 if not ( 'q' in opts) :
1276 if not ( 'q' in opts) :
1278 print('Macro `%s` created. To execute, type its name (without quotes).' % name)
1277 print('Macro `%s` created. To execute, type its name (without quotes).' % name)
1279 print('=== Macro contents: ===')
1278 print('=== Macro contents: ===')
1280 print(macro, end=' ')
1279 print(macro, end=' ')
1281
1280
1282 @magic_arguments.magic_arguments()
1281 @magic_arguments.magic_arguments()
1283 @magic_arguments.argument('output', type=str, default='', nargs='?',
1282 @magic_arguments.argument('output', type=str, default='', nargs='?',
1284 help="""The name of the variable in which to store output.
1283 help="""The name of the variable in which to store output.
1285 This is a utils.io.CapturedIO object with stdout/err attributes
1284 This is a utils.io.CapturedIO object with stdout/err attributes
1286 for the text of the captured output.
1285 for the text of the captured output.
1287
1286
1288 CapturedOutput also has a show() method for displaying the output,
1287 CapturedOutput also has a show() method for displaying the output,
1289 and __call__ as well, so you can use that to quickly display the
1288 and __call__ as well, so you can use that to quickly display the
1290 output.
1289 output.
1291
1290
1292 If unspecified, captured output is discarded.
1291 If unspecified, captured output is discarded.
1293 """
1292 """
1294 )
1293 )
1295 @magic_arguments.argument('--no-stderr', action="store_true",
1294 @magic_arguments.argument('--no-stderr', action="store_true",
1296 help="""Don't capture stderr."""
1295 help="""Don't capture stderr."""
1297 )
1296 )
1298 @magic_arguments.argument('--no-stdout', action="store_true",
1297 @magic_arguments.argument('--no-stdout', action="store_true",
1299 help="""Don't capture stdout."""
1298 help="""Don't capture stdout."""
1300 )
1299 )
1301 @magic_arguments.argument('--no-display', action="store_true",
1300 @magic_arguments.argument('--no-display', action="store_true",
1302 help="""Don't capture IPython's rich display."""
1301 help="""Don't capture IPython's rich display."""
1303 )
1302 )
1304 @cell_magic
1303 @cell_magic
1305 def capture(self, line, cell):
1304 def capture(self, line, cell):
1306 """run the cell, capturing stdout, stderr, and IPython's rich display() calls."""
1305 """run the cell, capturing stdout, stderr, and IPython's rich display() calls."""
1307 args = magic_arguments.parse_argstring(self.capture, line)
1306 args = magic_arguments.parse_argstring(self.capture, line)
1308 out = not args.no_stdout
1307 out = not args.no_stdout
1309 err = not args.no_stderr
1308 err = not args.no_stderr
1310 disp = not args.no_display
1309 disp = not args.no_display
1311 with capture_output(out, err, disp) as io:
1310 with capture_output(out, err, disp) as io:
1312 self.shell.run_cell(cell)
1311 self.shell.run_cell(cell)
1313 if args.output:
1312 if args.output:
1314 self.shell.user_ns[args.output] = io
1313 self.shell.user_ns[args.output] = io
1315
1314
1316 def parse_breakpoint(text, current_file):
1315 def parse_breakpoint(text, current_file):
1317 '''Returns (file, line) for file:line and (current_file, line) for line'''
1316 '''Returns (file, line) for file:line and (current_file, line) for line'''
1318 colon = text.find(':')
1317 colon = text.find(':')
1319 if colon == -1:
1318 if colon == -1:
1320 return current_file, int(text)
1319 return current_file, int(text)
1321 else:
1320 else:
1322 return text[:colon], int(text[colon+1:])
1321 return text[:colon], int(text[colon+1:])
1323
1322
1324 def _format_time(timespan, precision=3):
1323 def _format_time(timespan, precision=3):
1325 """Formats the timespan in a human readable form"""
1324 """Formats the timespan in a human readable form"""
1326 import math
1325 import math
1327
1326
1328 if timespan >= 60.0:
1327 if timespan >= 60.0:
1329 # we have more than a minute, format that in a human readable form
1328 # we have more than a minute, format that in a human readable form
1330 # Idea from http://snipplr.com/view/5713/
1329 # Idea from http://snipplr.com/view/5713/
1331 parts = [("d", 60*60*24),("h", 60*60),("min", 60), ("s", 1)]
1330 parts = [("d", 60*60*24),("h", 60*60),("min", 60), ("s", 1)]
1332 time = []
1331 time = []
1333 leftover = timespan
1332 leftover = timespan
1334 for suffix, length in parts:
1333 for suffix, length in parts:
1335 value = int(leftover / length)
1334 value = int(leftover / length)
1336 if value > 0:
1335 if value > 0:
1337 leftover = leftover % length
1336 leftover = leftover % length
1338 time.append(u'%s%s' % (str(value), suffix))
1337 time.append(u'%s%s' % (str(value), suffix))
1339 if leftover < 1:
1338 if leftover < 1:
1340 break
1339 break
1341 return " ".join(time)
1340 return " ".join(time)
1342
1341
1343
1342
1344 # Unfortunately the unicode 'micro' symbol can cause problems in
1343 # Unfortunately the unicode 'micro' symbol can cause problems in
1345 # certain terminals.
1344 # certain terminals.
1346 # See bug: https://bugs.launchpad.net/ipython/+bug/348466
1345 # See bug: https://bugs.launchpad.net/ipython/+bug/348466
1347 # Try to prevent crashes by being more secure than it needs to
1346 # Try to prevent crashes by being more secure than it needs to
1348 # E.g. eclipse is able to print a Β΅, but has no sys.stdout.encoding set.
1347 # E.g. eclipse is able to print a Β΅, but has no sys.stdout.encoding set.
1349 units = [u"s", u"ms",u'us',"ns"] # the save value
1348 units = [u"s", u"ms",u'us',"ns"] # the save value
1350 if hasattr(sys.stdout, 'encoding') and sys.stdout.encoding:
1349 if hasattr(sys.stdout, 'encoding') and sys.stdout.encoding:
1351 try:
1350 try:
1352 u'\xb5'.encode(sys.stdout.encoding)
1351 u'\xb5'.encode(sys.stdout.encoding)
1353 units = [u"s", u"ms",u'\xb5s',"ns"]
1352 units = [u"s", u"ms",u'\xb5s',"ns"]
1354 except:
1353 except:
1355 pass
1354 pass
1356 scaling = [1, 1e3, 1e6, 1e9]
1355 scaling = [1, 1e3, 1e6, 1e9]
1357
1356
1358 if timespan > 0.0:
1357 if timespan > 0.0:
1359 order = min(-int(math.floor(math.log10(timespan)) // 3), 3)
1358 order = min(-int(math.floor(math.log10(timespan)) // 3), 3)
1360 else:
1359 else:
1361 order = 3
1360 order = 3
1362 return u"%.*g %s" % (precision, timespan * scaling[order], units[order])
1361 return u"%.*g %s" % (precision, timespan * scaling[order], units[order])
@@ -1,415 +1,409 b''
1 # encoding: utf-8
1 # encoding: utf-8
2 """
2 """
3 A mixin for :class:`~IPython.core.application.Application` classes that
3 A mixin for :class:`~IPython.core.application.Application` classes that
4 launch InteractiveShell instances, load extensions, etc.
4 launch InteractiveShell instances, load extensions, etc.
5 """
5 """
6
6
7 # Copyright (c) IPython Development Team.
7 # Copyright (c) IPython Development Team.
8 # Distributed under the terms of the Modified BSD License.
8 # Distributed under the terms of the Modified BSD License.
9
9
10 from __future__ import absolute_import
10 from __future__ import absolute_import
11 from __future__ import print_function
11 from __future__ import print_function
12
12
13 import glob
13 import glob
14 import os
14 import os
15 import sys
15 import sys
16
16
17 from traitlets.config.application import boolean_flag
17 from traitlets.config.application import boolean_flag
18 from traitlets.config.configurable import Configurable
18 from traitlets.config.configurable import Configurable
19 from traitlets.config.loader import Config
19 from traitlets.config.loader import Config
20 from IPython.core import pylabtools
20 from IPython.core import pylabtools
21 from IPython.utils import py3compat
21 from IPython.utils import py3compat
22 from IPython.utils.contexts import preserve_keys
22 from IPython.utils.contexts import preserve_keys
23 from IPython.utils.path import filefind
23 from IPython.utils.path import filefind
24 from traitlets import (
24 from traitlets import (
25 Unicode, Instance, List, Bool, CaselessStrEnum, observe,
25 Unicode, Instance, List, Bool, CaselessStrEnum, observe,
26 )
26 )
27 from IPython.lib.inputhook import guis
27 from IPython.lib.inputhook import guis
28
28
29 #-----------------------------------------------------------------------------
29 #-----------------------------------------------------------------------------
30 # Aliases and Flags
30 # Aliases and Flags
31 #-----------------------------------------------------------------------------
31 #-----------------------------------------------------------------------------
32
32
33 gui_keys = tuple(sorted([ key for key in guis if key is not None ]))
33 gui_keys = tuple(sorted([ key for key in guis if key is not None ]))
34
34
35 backend_keys = sorted(pylabtools.backends.keys())
35 backend_keys = sorted(pylabtools.backends.keys())
36 backend_keys.insert(0, 'auto')
36 backend_keys.insert(0, 'auto')
37
37
38 shell_flags = {}
38 shell_flags = {}
39
39
40 addflag = lambda *args: shell_flags.update(boolean_flag(*args))
40 addflag = lambda *args: shell_flags.update(boolean_flag(*args))
41 addflag('autoindent', 'InteractiveShell.autoindent',
41 addflag('autoindent', 'InteractiveShell.autoindent',
42 'Turn on autoindenting.', 'Turn off autoindenting.'
42 'Turn on autoindenting.', 'Turn off autoindenting.'
43 )
43 )
44 addflag('automagic', 'InteractiveShell.automagic',
44 addflag('automagic', 'InteractiveShell.automagic',
45 """Turn on the auto calling of magic commands. Type %%magic at the
45 """Turn on the auto calling of magic commands. Type %%magic at the
46 IPython prompt for more information.""",
46 IPython prompt for more information.""",
47 'Turn off the auto calling of magic commands.'
47 'Turn off the auto calling of magic commands.'
48 )
48 )
49 addflag('pdb', 'InteractiveShell.pdb',
49 addflag('pdb', 'InteractiveShell.pdb',
50 "Enable auto calling the pdb debugger after every exception.",
50 "Enable auto calling the pdb debugger after every exception.",
51 "Disable auto calling the pdb debugger after every exception."
51 "Disable auto calling the pdb debugger after every exception."
52 )
52 )
53 addflag('pprint', 'PlainTextFormatter.pprint',
53 addflag('pprint', 'PlainTextFormatter.pprint',
54 "Enable auto pretty printing of results.",
54 "Enable auto pretty printing of results.",
55 "Disable auto pretty printing of results."
55 "Disable auto pretty printing of results."
56 )
56 )
57 addflag('color-info', 'InteractiveShell.color_info',
57 addflag('color-info', 'InteractiveShell.color_info',
58 """IPython can display information about objects via a set of functions,
58 """IPython can display information about objects via a set of functions,
59 and optionally can use colors for this, syntax highlighting
59 and optionally can use colors for this, syntax highlighting
60 source code and various other elements. This is on by default, but can cause
60 source code and various other elements. This is on by default, but can cause
61 problems with some pagers. If you see such problems, you can disable the
61 problems with some pagers. If you see such problems, you can disable the
62 colours.""",
62 colours.""",
63 "Disable using colors for info related things."
63 "Disable using colors for info related things."
64 )
64 )
65 nosep_config = Config()
65 nosep_config = Config()
66 nosep_config.InteractiveShell.separate_in = ''
66 nosep_config.InteractiveShell.separate_in = ''
67 nosep_config.InteractiveShell.separate_out = ''
67 nosep_config.InteractiveShell.separate_out = ''
68 nosep_config.InteractiveShell.separate_out2 = ''
68 nosep_config.InteractiveShell.separate_out2 = ''
69
69
70 shell_flags['nosep']=(nosep_config, "Eliminate all spacing between prompts.")
70 shell_flags['nosep']=(nosep_config, "Eliminate all spacing between prompts.")
71 shell_flags['pylab'] = (
71 shell_flags['pylab'] = (
72 {'InteractiveShellApp' : {'pylab' : 'auto'}},
72 {'InteractiveShellApp' : {'pylab' : 'auto'}},
73 """Pre-load matplotlib and numpy for interactive use with
73 """Pre-load matplotlib and numpy for interactive use with
74 the default matplotlib backend."""
74 the default matplotlib backend."""
75 )
75 )
76 shell_flags['matplotlib'] = (
76 shell_flags['matplotlib'] = (
77 {'InteractiveShellApp' : {'matplotlib' : 'auto'}},
77 {'InteractiveShellApp' : {'matplotlib' : 'auto'}},
78 """Configure matplotlib for interactive use with
78 """Configure matplotlib for interactive use with
79 the default matplotlib backend."""
79 the default matplotlib backend."""
80 )
80 )
81
81
82 # it's possible we don't want short aliases for *all* of these:
82 # it's possible we don't want short aliases for *all* of these:
83 shell_aliases = dict(
83 shell_aliases = dict(
84 autocall='InteractiveShell.autocall',
84 autocall='InteractiveShell.autocall',
85 colors='InteractiveShell.colors',
85 colors='InteractiveShell.colors',
86 logfile='InteractiveShell.logfile',
86 logfile='InteractiveShell.logfile',
87 logappend='InteractiveShell.logappend',
87 logappend='InteractiveShell.logappend',
88 c='InteractiveShellApp.code_to_run',
88 c='InteractiveShellApp.code_to_run',
89 m='InteractiveShellApp.module_to_run',
89 m='InteractiveShellApp.module_to_run',
90 ext='InteractiveShellApp.extra_extension',
90 ext='InteractiveShellApp.extra_extension',
91 gui='InteractiveShellApp.gui',
91 gui='InteractiveShellApp.gui',
92 pylab='InteractiveShellApp.pylab',
92 pylab='InteractiveShellApp.pylab',
93 matplotlib='InteractiveShellApp.matplotlib',
93 matplotlib='InteractiveShellApp.matplotlib',
94 )
94 )
95 shell_aliases['cache-size'] = 'InteractiveShell.cache_size'
95 shell_aliases['cache-size'] = 'InteractiveShell.cache_size'
96
96
97 #-----------------------------------------------------------------------------
97 #-----------------------------------------------------------------------------
98 # Main classes and functions
98 # Main classes and functions
99 #-----------------------------------------------------------------------------
99 #-----------------------------------------------------------------------------
100
100
101 class InteractiveShellApp(Configurable):
101 class InteractiveShellApp(Configurable):
102 """A Mixin for applications that start InteractiveShell instances.
102 """A Mixin for applications that start InteractiveShell instances.
103
103
104 Provides configurables for loading extensions and executing files
104 Provides configurables for loading extensions and executing files
105 as part of configuring a Shell environment.
105 as part of configuring a Shell environment.
106
106
107 The following methods should be called by the :meth:`initialize` method
107 The following methods should be called by the :meth:`initialize` method
108 of the subclass:
108 of the subclass:
109
109
110 - :meth:`init_path`
110 - :meth:`init_path`
111 - :meth:`init_shell` (to be implemented by the subclass)
111 - :meth:`init_shell` (to be implemented by the subclass)
112 - :meth:`init_gui_pylab`
112 - :meth:`init_gui_pylab`
113 - :meth:`init_extensions`
113 - :meth:`init_extensions`
114 - :meth:`init_code`
114 - :meth:`init_code`
115 """
115 """
116 extensions = List(Unicode(),
116 extensions = List(Unicode(),
117 help="A list of dotted module names of IPython extensions to load."
117 help="A list of dotted module names of IPython extensions to load."
118 ).tag(config=True)
118 ).tag(config=True)
119 extra_extension = Unicode('',
119 extra_extension = Unicode('',
120 help="dotted module name of an IPython extension to load."
120 help="dotted module name of an IPython extension to load."
121 ).tag(config=True)
121 ).tag(config=True)
122
122
123 reraise_ipython_extension_failures = Bool(False,
123 reraise_ipython_extension_failures = Bool(False,
124 help="Reraise exceptions encountered loading IPython extensions?",
124 help="Reraise exceptions encountered loading IPython extensions?",
125 ).tag(config=True)
125 ).tag(config=True)
126
126
127 # Extensions that are always loaded (not configurable)
127 # Extensions that are always loaded (not configurable)
128 default_extensions = List(Unicode(), [u'storemagic']).tag(config=False)
128 default_extensions = List(Unicode(), [u'storemagic']).tag(config=False)
129
129
130 hide_initial_ns = Bool(True,
130 hide_initial_ns = Bool(True,
131 help="""Should variables loaded at startup (by startup files, exec_lines, etc.)
131 help="""Should variables loaded at startup (by startup files, exec_lines, etc.)
132 be hidden from tools like %who?"""
132 be hidden from tools like %who?"""
133 ).tag(config=True)
133 ).tag(config=True)
134
134
135 exec_files = List(Unicode(),
135 exec_files = List(Unicode(),
136 help="""List of files to run at IPython startup."""
136 help="""List of files to run at IPython startup."""
137 ).tag(config=True)
137 ).tag(config=True)
138 exec_PYTHONSTARTUP = Bool(True,
138 exec_PYTHONSTARTUP = Bool(True,
139 help="""Run the file referenced by the PYTHONSTARTUP environment
139 help="""Run the file referenced by the PYTHONSTARTUP environment
140 variable at IPython startup."""
140 variable at IPython startup."""
141 ).tag(config=True)
141 ).tag(config=True)
142 file_to_run = Unicode('',
142 file_to_run = Unicode('',
143 help="""A file to be run""").tag(config=True)
143 help="""A file to be run""").tag(config=True)
144
144
145 exec_lines = List(Unicode(),
145 exec_lines = List(Unicode(),
146 help="""lines of code to run at IPython startup."""
146 help="""lines of code to run at IPython startup."""
147 ).tag(config=True)
147 ).tag(config=True)
148 code_to_run = Unicode('',
148 code_to_run = Unicode('',
149 help="Execute the given command string."
149 help="Execute the given command string."
150 ).tag(config=True)
150 ).tag(config=True)
151 module_to_run = Unicode('',
151 module_to_run = Unicode('',
152 help="Run the module as a script."
152 help="Run the module as a script."
153 ).tag(config=True)
153 ).tag(config=True)
154 gui = CaselessStrEnum(gui_keys, allow_none=True,
154 gui = CaselessStrEnum(gui_keys, allow_none=True,
155 help="Enable GUI event loop integration with any of {0}.".format(gui_keys)
155 help="Enable GUI event loop integration with any of {0}.".format(gui_keys)
156 ).tag(config=True)
156 ).tag(config=True)
157 matplotlib = CaselessStrEnum(backend_keys, allow_none=True,
157 matplotlib = CaselessStrEnum(backend_keys, allow_none=True,
158 help="""Configure matplotlib for interactive use with
158 help="""Configure matplotlib for interactive use with
159 the default matplotlib backend."""
159 the default matplotlib backend."""
160 ).tag(config=True)
160 ).tag(config=True)
161 pylab = CaselessStrEnum(backend_keys, allow_none=True,
161 pylab = CaselessStrEnum(backend_keys, allow_none=True,
162 help="""Pre-load matplotlib and numpy for interactive use,
162 help="""Pre-load matplotlib and numpy for interactive use,
163 selecting a particular matplotlib backend and loop integration.
163 selecting a particular matplotlib backend and loop integration.
164 """
164 """
165 ).tag(config=True)
165 ).tag(config=True)
166 pylab_import_all = Bool(True,
166 pylab_import_all = Bool(True,
167 help="""If true, IPython will populate the user namespace with numpy, pylab, etc.
167 help="""If true, IPython will populate the user namespace with numpy, pylab, etc.
168 and an ``import *`` is done from numpy and pylab, when using pylab mode.
168 and an ``import *`` is done from numpy and pylab, when using pylab mode.
169
169
170 When False, pylab mode should not import any names into the user namespace.
170 When False, pylab mode should not import any names into the user namespace.
171 """
171 """
172 ).tag(config=True)
172 ).tag(config=True)
173 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC',
173 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC',
174 allow_none=True)
174 allow_none=True)
175 # whether interact-loop should start
175 # whether interact-loop should start
176 interact = Bool(True)
176 interact = Bool(True)
177
177
178 user_ns = Instance(dict, args=None, allow_none=True)
178 user_ns = Instance(dict, args=None, allow_none=True)
179 @observe('user_ns')
179 @observe('user_ns')
180 def _user_ns_changed(self, change):
180 def _user_ns_changed(self, change):
181 if self.shell is not None:
181 if self.shell is not None:
182 self.shell.user_ns = change['new']
182 self.shell.user_ns = change['new']
183 self.shell.init_user_ns()
183 self.shell.init_user_ns()
184
184
185 def init_path(self):
185 def init_path(self):
186 """Add current working directory, '', to sys.path"""
186 """Add current working directory, '', to sys.path"""
187 if sys.path[0] != '':
187 if sys.path[0] != '':
188 sys.path.insert(0, '')
188 sys.path.insert(0, '')
189
189
190 def init_shell(self):
190 def init_shell(self):
191 raise NotImplementedError("Override in subclasses")
191 raise NotImplementedError("Override in subclasses")
192
192
193 def init_gui_pylab(self):
193 def init_gui_pylab(self):
194 """Enable GUI event loop integration, taking pylab into account."""
194 """Enable GUI event loop integration, taking pylab into account."""
195 enable = False
195 enable = False
196 shell = self.shell
196 shell = self.shell
197 if self.pylab:
197 if self.pylab:
198 enable = lambda key: shell.enable_pylab(key, import_all=self.pylab_import_all)
198 enable = lambda key: shell.enable_pylab(key, import_all=self.pylab_import_all)
199 key = self.pylab
199 key = self.pylab
200 elif self.matplotlib:
200 elif self.matplotlib:
201 enable = shell.enable_matplotlib
201 enable = shell.enable_matplotlib
202 key = self.matplotlib
202 key = self.matplotlib
203 elif self.gui:
203 elif self.gui:
204 enable = shell.enable_gui
204 enable = shell.enable_gui
205 key = self.gui
205 key = self.gui
206
206
207 if not enable:
207 if not enable:
208 return
208 return
209
209
210 try:
210 try:
211 r = enable(key)
211 r = enable(key)
212 except ImportError:
212 except ImportError:
213 self.log.warning("Eventloop or matplotlib integration failed. Is matplotlib installed?")
213 self.log.warning("Eventloop or matplotlib integration failed. Is matplotlib installed?")
214 self.shell.showtraceback()
214 self.shell.showtraceback()
215 return
215 return
216 except Exception:
216 except Exception:
217 self.log.warning("GUI event loop or pylab initialization failed")
217 self.log.warning("GUI event loop or pylab initialization failed")
218 self.shell.showtraceback()
218 self.shell.showtraceback()
219 return
219 return
220
220
221 if isinstance(r, tuple):
221 if isinstance(r, tuple):
222 gui, backend = r[:2]
222 gui, backend = r[:2]
223 self.log.info("Enabling GUI event loop integration, "
223 self.log.info("Enabling GUI event loop integration, "
224 "eventloop=%s, matplotlib=%s", gui, backend)
224 "eventloop=%s, matplotlib=%s", gui, backend)
225 if key == "auto":
225 if key == "auto":
226 print("Using matplotlib backend: %s" % backend)
226 print("Using matplotlib backend: %s" % backend)
227 else:
227 else:
228 gui = r
228 gui = r
229 self.log.info("Enabling GUI event loop integration, "
229 self.log.info("Enabling GUI event loop integration, "
230 "eventloop=%s", gui)
230 "eventloop=%s", gui)
231
231
232 def init_extensions(self):
232 def init_extensions(self):
233 """Load all IPython extensions in IPythonApp.extensions.
233 """Load all IPython extensions in IPythonApp.extensions.
234
234
235 This uses the :meth:`ExtensionManager.load_extensions` to load all
235 This uses the :meth:`ExtensionManager.load_extensions` to load all
236 the extensions listed in ``self.extensions``.
236 the extensions listed in ``self.extensions``.
237 """
237 """
238 try:
238 try:
239 self.log.debug("Loading IPython extensions...")
239 self.log.debug("Loading IPython extensions...")
240 extensions = self.default_extensions + self.extensions
240 extensions = self.default_extensions + self.extensions
241 if self.extra_extension:
241 if self.extra_extension:
242 extensions.append(self.extra_extension)
242 extensions.append(self.extra_extension)
243 for ext in extensions:
243 for ext in extensions:
244 try:
244 try:
245 self.log.info("Loading IPython extension: %s" % ext)
245 self.log.info("Loading IPython extension: %s" % ext)
246 self.shell.extension_manager.load_extension(ext)
246 self.shell.extension_manager.load_extension(ext)
247 except:
247 except:
248 if self.reraise_ipython_extension_failures:
248 if self.reraise_ipython_extension_failures:
249 raise
249 raise
250 msg = ("Error in loading extension: {ext}\n"
250 msg = ("Error in loading extension: {ext}\n"
251 "Check your config files in {location}".format(
251 "Check your config files in {location}".format(
252 ext=ext,
252 ext=ext,
253 location=self.profile_dir.location
253 location=self.profile_dir.location
254 ))
254 ))
255 self.log.warning(msg, exc_info=True)
255 self.log.warning(msg, exc_info=True)
256 except:
256 except:
257 if self.reraise_ipython_extension_failures:
257 if self.reraise_ipython_extension_failures:
258 raise
258 raise
259 self.log.warning("Unknown error in loading extensions:", exc_info=True)
259 self.log.warning("Unknown error in loading extensions:", exc_info=True)
260
260
261 def init_code(self):
261 def init_code(self):
262 """run the pre-flight code, specified via exec_lines"""
262 """run the pre-flight code, specified via exec_lines"""
263 self._run_startup_files()
263 self._run_startup_files()
264 self._run_exec_lines()
264 self._run_exec_lines()
265 self._run_exec_files()
265 self._run_exec_files()
266
266
267 # Hide variables defined here from %who etc.
267 # Hide variables defined here from %who etc.
268 if self.hide_initial_ns:
268 if self.hide_initial_ns:
269 self.shell.user_ns_hidden.update(self.shell.user_ns)
269 self.shell.user_ns_hidden.update(self.shell.user_ns)
270
270
271 # command-line execution (ipython -i script.py, ipython -m module)
271 # command-line execution (ipython -i script.py, ipython -m module)
272 # should *not* be excluded from %whos
272 # should *not* be excluded from %whos
273 self._run_cmd_line_code()
273 self._run_cmd_line_code()
274 self._run_module()
274 self._run_module()
275
275
276 # flush output, so itwon't be attached to the first cell
276 # flush output, so itwon't be attached to the first cell
277 sys.stdout.flush()
277 sys.stdout.flush()
278 sys.stderr.flush()
278 sys.stderr.flush()
279
279
280 def _run_exec_lines(self):
280 def _run_exec_lines(self):
281 """Run lines of code in IPythonApp.exec_lines in the user's namespace."""
281 """Run lines of code in IPythonApp.exec_lines in the user's namespace."""
282 if not self.exec_lines:
282 if not self.exec_lines:
283 return
283 return
284 try:
284 try:
285 self.log.debug("Running code from IPythonApp.exec_lines...")
285 self.log.debug("Running code from IPythonApp.exec_lines...")
286 for line in self.exec_lines:
286 for line in self.exec_lines:
287 try:
287 try:
288 self.log.info("Running code in user namespace: %s" %
288 self.log.info("Running code in user namespace: %s" %
289 line)
289 line)
290 self.shell.run_cell(line, store_history=False)
290 self.shell.run_cell(line, store_history=False)
291 except:
291 except:
292 self.log.warning("Error in executing line in user "
292 self.log.warning("Error in executing line in user "
293 "namespace: %s" % line)
293 "namespace: %s" % line)
294 self.shell.showtraceback()
294 self.shell.showtraceback()
295 except:
295 except:
296 self.log.warning("Unknown error in handling IPythonApp.exec_lines:")
296 self.log.warning("Unknown error in handling IPythonApp.exec_lines:")
297 self.shell.showtraceback()
297 self.shell.showtraceback()
298
298
299 def _exec_file(self, fname, shell_futures=False):
299 def _exec_file(self, fname, shell_futures=False):
300 try:
300 try:
301 full_filename = filefind(fname, [u'.', self.ipython_dir])
301 full_filename = filefind(fname, [u'.', self.ipython_dir])
302 except IOError:
302 except IOError:
303 self.log.warning("File not found: %r"%fname)
303 self.log.warning("File not found: %r"%fname)
304 return
304 return
305 # Make sure that the running script gets a proper sys.argv as if it
305 # Make sure that the running script gets a proper sys.argv as if it
306 # were run from a system shell.
306 # were run from a system shell.
307 save_argv = sys.argv
307 save_argv = sys.argv
308 sys.argv = [full_filename] + self.extra_args[1:]
308 sys.argv = [full_filename] + self.extra_args[1:]
309 # protect sys.argv from potential unicode strings on Python 2:
309 # protect sys.argv from potential unicode strings on Python 2:
310 if not py3compat.PY3:
310 if not py3compat.PY3:
311 sys.argv = [ py3compat.cast_bytes(a) for a in sys.argv ]
311 sys.argv = [ py3compat.cast_bytes(a) for a in sys.argv ]
312 try:
312 try:
313 if os.path.isfile(full_filename):
313 if os.path.isfile(full_filename):
314 self.log.info("Running file in user namespace: %s" %
314 self.log.info("Running file in user namespace: %s" %
315 full_filename)
315 full_filename)
316 # Ensure that __file__ is always defined to match Python
316 # Ensure that __file__ is always defined to match Python
317 # behavior.
317 # behavior.
318 with preserve_keys(self.shell.user_ns, '__file__'):
318 with preserve_keys(self.shell.user_ns, '__file__'):
319 self.shell.user_ns['__file__'] = fname
319 self.shell.user_ns['__file__'] = fname
320 if full_filename.endswith('.ipy'):
320 if full_filename.endswith('.ipy'):
321 self.shell.safe_execfile_ipy(full_filename,
321 self.shell.safe_execfile_ipy(full_filename,
322 shell_futures=shell_futures)
322 shell_futures=shell_futures)
323 else:
323 else:
324 # default to python, even without extension
324 # default to python, even without extension
325 self.shell.safe_execfile(full_filename,
325 self.shell.safe_execfile(full_filename,
326 self.shell.user_ns,
326 self.shell.user_ns,
327 shell_futures=shell_futures,
327 shell_futures=shell_futures,
328 raise_exceptions=True)
328 raise_exceptions=True)
329 finally:
329 finally:
330 sys.argv = save_argv
330 sys.argv = save_argv
331
331
332 def _run_startup_files(self):
332 def _run_startup_files(self):
333 """Run files from profile startup directory"""
333 """Run files from profile startup directory"""
334 startup_dir = self.profile_dir.startup_dir
334 startup_dir = self.profile_dir.startup_dir
335 startup_files = []
335 startup_files = []
336
336
337 if self.exec_PYTHONSTARTUP and os.environ.get('PYTHONSTARTUP', False) and \
337 if self.exec_PYTHONSTARTUP and os.environ.get('PYTHONSTARTUP', False) and \
338 not (self.file_to_run or self.code_to_run or self.module_to_run):
338 not (self.file_to_run or self.code_to_run or self.module_to_run):
339 python_startup = os.environ['PYTHONSTARTUP']
339 python_startup = os.environ['PYTHONSTARTUP']
340 self.log.debug("Running PYTHONSTARTUP file %s...", python_startup)
340 self.log.debug("Running PYTHONSTARTUP file %s...", python_startup)
341 try:
341 try:
342 self._exec_file(python_startup)
342 self._exec_file(python_startup)
343 except:
343 except:
344 self.log.warning("Unknown error in handling PYTHONSTARTUP file %s:", python_startup)
344 self.log.warning("Unknown error in handling PYTHONSTARTUP file %s:", python_startup)
345 self.shell.showtraceback()
345 self.shell.showtraceback()
346 finally:
347 # Many PYTHONSTARTUP files set up the readline completions,
348 # but this is often at odds with IPython's own completions.
349 # Do not allow PYTHONSTARTUP to set up readline.
350 if self.shell.has_readline:
351 self.shell.set_readline_completer()
352
346
353 startup_files += glob.glob(os.path.join(startup_dir, '*.py'))
347 startup_files += glob.glob(os.path.join(startup_dir, '*.py'))
354 startup_files += glob.glob(os.path.join(startup_dir, '*.ipy'))
348 startup_files += glob.glob(os.path.join(startup_dir, '*.ipy'))
355 if not startup_files:
349 if not startup_files:
356 return
350 return
357
351
358 self.log.debug("Running startup files from %s...", startup_dir)
352 self.log.debug("Running startup files from %s...", startup_dir)
359 try:
353 try:
360 for fname in sorted(startup_files):
354 for fname in sorted(startup_files):
361 self._exec_file(fname)
355 self._exec_file(fname)
362 except:
356 except:
363 self.log.warning("Unknown error in handling startup files:")
357 self.log.warning("Unknown error in handling startup files:")
364 self.shell.showtraceback()
358 self.shell.showtraceback()
365
359
366 def _run_exec_files(self):
360 def _run_exec_files(self):
367 """Run files from IPythonApp.exec_files"""
361 """Run files from IPythonApp.exec_files"""
368 if not self.exec_files:
362 if not self.exec_files:
369 return
363 return
370
364
371 self.log.debug("Running files in IPythonApp.exec_files...")
365 self.log.debug("Running files in IPythonApp.exec_files...")
372 try:
366 try:
373 for fname in self.exec_files:
367 for fname in self.exec_files:
374 self._exec_file(fname)
368 self._exec_file(fname)
375 except:
369 except:
376 self.log.warning("Unknown error in handling IPythonApp.exec_files:")
370 self.log.warning("Unknown error in handling IPythonApp.exec_files:")
377 self.shell.showtraceback()
371 self.shell.showtraceback()
378
372
379 def _run_cmd_line_code(self):
373 def _run_cmd_line_code(self):
380 """Run code or file specified at the command-line"""
374 """Run code or file specified at the command-line"""
381 if self.code_to_run:
375 if self.code_to_run:
382 line = self.code_to_run
376 line = self.code_to_run
383 try:
377 try:
384 self.log.info("Running code given at command line (c=): %s" %
378 self.log.info("Running code given at command line (c=): %s" %
385 line)
379 line)
386 self.shell.run_cell(line, store_history=False)
380 self.shell.run_cell(line, store_history=False)
387 except:
381 except:
388 self.log.warning("Error in executing line in user namespace: %s" %
382 self.log.warning("Error in executing line in user namespace: %s" %
389 line)
383 line)
390 self.shell.showtraceback()
384 self.shell.showtraceback()
391 if not self.interact:
385 if not self.interact:
392 self.exit(1)
386 self.exit(1)
393
387
394 # Like Python itself, ignore the second if the first of these is present
388 # Like Python itself, ignore the second if the first of these is present
395 elif self.file_to_run:
389 elif self.file_to_run:
396 fname = self.file_to_run
390 fname = self.file_to_run
397 try:
391 try:
398 self._exec_file(fname, shell_futures=True)
392 self._exec_file(fname, shell_futures=True)
399 except:
393 except:
400 self.shell.showtraceback(tb_offset=4)
394 self.shell.showtraceback(tb_offset=4)
401 if not self.interact:
395 if not self.interact:
402 self.exit(1)
396 self.exit(1)
403
397
404 def _run_module(self):
398 def _run_module(self):
405 """Run module specified at the command-line."""
399 """Run module specified at the command-line."""
406 if self.module_to_run:
400 if self.module_to_run:
407 # Make sure that the module gets a proper sys.argv as if it were
401 # Make sure that the module gets a proper sys.argv as if it were
408 # run using `python -m`.
402 # run using `python -m`.
409 save_argv = sys.argv
403 save_argv = sys.argv
410 sys.argv = [sys.executable] + self.extra_args
404 sys.argv = [sys.executable] + self.extra_args
411 try:
405 try:
412 self.shell.safe_run_module(self.module_to_run,
406 self.shell.safe_run_module(self.module_to_run,
413 self.shell.user_ns)
407 self.shell.user_ns)
414 finally:
408 finally:
415 sys.argv = save_argv
409 sys.argv = save_argv
@@ -1,1495 +1,1494 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """
2 """
3 Verbose and colourful traceback formatting.
3 Verbose and colourful traceback formatting.
4
4
5 **ColorTB**
5 **ColorTB**
6
6
7 I've always found it a bit hard to visually parse tracebacks in Python. The
7 I've always found it a bit hard to visually parse tracebacks in Python. The
8 ColorTB class is a solution to that problem. It colors the different parts of a
8 ColorTB class is a solution to that problem. It colors the different parts of a
9 traceback in a manner similar to what you would expect from a syntax-highlighting
9 traceback in a manner similar to what you would expect from a syntax-highlighting
10 text editor.
10 text editor.
11
11
12 Installation instructions for ColorTB::
12 Installation instructions for ColorTB::
13
13
14 import sys,ultratb
14 import sys,ultratb
15 sys.excepthook = ultratb.ColorTB()
15 sys.excepthook = ultratb.ColorTB()
16
16
17 **VerboseTB**
17 **VerboseTB**
18
18
19 I've also included a port of Ka-Ping Yee's "cgitb.py" that produces all kinds
19 I've also included a port of Ka-Ping Yee's "cgitb.py" that produces all kinds
20 of useful info when a traceback occurs. Ping originally had it spit out HTML
20 of useful info when a traceback occurs. Ping originally had it spit out HTML
21 and intended it for CGI programmers, but why should they have all the fun? I
21 and intended it for CGI programmers, but why should they have all the fun? I
22 altered it to spit out colored text to the terminal. It's a bit overwhelming,
22 altered it to spit out colored text to the terminal. It's a bit overwhelming,
23 but kind of neat, and maybe useful for long-running programs that you believe
23 but kind of neat, and maybe useful for long-running programs that you believe
24 are bug-free. If a crash *does* occur in that type of program you want details.
24 are bug-free. If a crash *does* occur in that type of program you want details.
25 Give it a shot--you'll love it or you'll hate it.
25 Give it a shot--you'll love it or you'll hate it.
26
26
27 .. note::
27 .. note::
28
28
29 The Verbose mode prints the variables currently visible where the exception
29 The Verbose mode prints the variables currently visible where the exception
30 happened (shortening their strings if too long). This can potentially be
30 happened (shortening their strings if too long). This can potentially be
31 very slow, if you happen to have a huge data structure whose string
31 very slow, if you happen to have a huge data structure whose string
32 representation is complex to compute. Your computer may appear to freeze for
32 representation is complex to compute. Your computer may appear to freeze for
33 a while with cpu usage at 100%. If this occurs, you can cancel the traceback
33 a while with cpu usage at 100%. If this occurs, you can cancel the traceback
34 with Ctrl-C (maybe hitting it more than once).
34 with Ctrl-C (maybe hitting it more than once).
35
35
36 If you encounter this kind of situation often, you may want to use the
36 If you encounter this kind of situation often, you may want to use the
37 Verbose_novars mode instead of the regular Verbose, which avoids formatting
37 Verbose_novars mode instead of the regular Verbose, which avoids formatting
38 variables (but otherwise includes the information and context given by
38 variables (but otherwise includes the information and context given by
39 Verbose).
39 Verbose).
40
40
41 .. note::
41 .. note::
42
42
43 The verbose mode print all variables in the stack, which means it can
43 The verbose mode print all variables in the stack, which means it can
44 potentially leak sensitive information like access keys, or unencryted
44 potentially leak sensitive information like access keys, or unencryted
45 password.
45 password.
46
46
47 Installation instructions for VerboseTB::
47 Installation instructions for VerboseTB::
48
48
49 import sys,ultratb
49 import sys,ultratb
50 sys.excepthook = ultratb.VerboseTB()
50 sys.excepthook = ultratb.VerboseTB()
51
51
52 Note: Much of the code in this module was lifted verbatim from the standard
52 Note: Much of the code in this module was lifted verbatim from the standard
53 library module 'traceback.py' and Ka-Ping Yee's 'cgitb.py'.
53 library module 'traceback.py' and Ka-Ping Yee's 'cgitb.py'.
54
54
55 Color schemes
55 Color schemes
56 -------------
56 -------------
57
57
58 The colors are defined in the class TBTools through the use of the
58 The colors are defined in the class TBTools through the use of the
59 ColorSchemeTable class. Currently the following exist:
59 ColorSchemeTable class. Currently the following exist:
60
60
61 - NoColor: allows all of this module to be used in any terminal (the color
61 - NoColor: allows all of this module to be used in any terminal (the color
62 escapes are just dummy blank strings).
62 escapes are just dummy blank strings).
63
63
64 - Linux: is meant to look good in a terminal like the Linux console (black
64 - Linux: is meant to look good in a terminal like the Linux console (black
65 or very dark background).
65 or very dark background).
66
66
67 - LightBG: similar to Linux but swaps dark/light colors to be more readable
67 - LightBG: similar to Linux but swaps dark/light colors to be more readable
68 in light background terminals.
68 in light background terminals.
69
69
70 - Neutral: a neutral color scheme that should be readable on both light and
70 - Neutral: a neutral color scheme that should be readable on both light and
71 dark background
71 dark background
72
72
73 You can implement other color schemes easily, the syntax is fairly
73 You can implement other color schemes easily, the syntax is fairly
74 self-explanatory. Please send back new schemes you develop to the author for
74 self-explanatory. Please send back new schemes you develop to the author for
75 possible inclusion in future releases.
75 possible inclusion in future releases.
76
76
77 Inheritance diagram:
77 Inheritance diagram:
78
78
79 .. inheritance-diagram:: IPython.core.ultratb
79 .. inheritance-diagram:: IPython.core.ultratb
80 :parts: 3
80 :parts: 3
81 """
81 """
82
82
83 #*****************************************************************************
83 #*****************************************************************************
84 # Copyright (C) 2001 Nathaniel Gray <n8gray@caltech.edu>
84 # Copyright (C) 2001 Nathaniel Gray <n8gray@caltech.edu>
85 # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
85 # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
86 #
86 #
87 # Distributed under the terms of the BSD License. The full license is in
87 # Distributed under the terms of the BSD License. The full license is in
88 # the file COPYING, distributed as part of this software.
88 # the file COPYING, distributed as part of this software.
89 #*****************************************************************************
89 #*****************************************************************************
90
90
91 from __future__ import absolute_import
91 from __future__ import absolute_import
92 from __future__ import unicode_literals
92 from __future__ import unicode_literals
93 from __future__ import print_function
93 from __future__ import print_function
94
94
95 import dis
95 import dis
96 import inspect
96 import inspect
97 import keyword
97 import keyword
98 import linecache
98 import linecache
99 import os
99 import os
100 import pydoc
100 import pydoc
101 import re
101 import re
102 import sys
102 import sys
103 import time
103 import time
104 import tokenize
104 import tokenize
105 import traceback
105 import traceback
106 import types
106 import types
107
107
108 try: # Python 2
108 try: # Python 2
109 generate_tokens = tokenize.generate_tokens
109 generate_tokens = tokenize.generate_tokens
110 except AttributeError: # Python 3
110 except AttributeError: # Python 3
111 generate_tokens = tokenize.tokenize
111 generate_tokens = tokenize.tokenize
112
112
113 # For purposes of monkeypatching inspect to fix a bug in it.
113 # For purposes of monkeypatching inspect to fix a bug in it.
114 from inspect import getsourcefile, getfile, getmodule, \
114 from inspect import getsourcefile, getfile, getmodule, \
115 ismodule, isclass, ismethod, isfunction, istraceback, isframe, iscode
115 ismodule, isclass, ismethod, isfunction, istraceback, isframe, iscode
116
116
117 # IPython's own modules
117 # IPython's own modules
118 # Modified pdb which doesn't damage IPython's readline handling
119 from IPython import get_ipython
118 from IPython import get_ipython
120 from IPython.core import debugger
119 from IPython.core import debugger
121 from IPython.core.display_trap import DisplayTrap
120 from IPython.core.display_trap import DisplayTrap
122 from IPython.core.excolors import exception_colors
121 from IPython.core.excolors import exception_colors
123 from IPython.utils import PyColorize
122 from IPython.utils import PyColorize
124 from IPython.utils import openpy
123 from IPython.utils import openpy
125 from IPython.utils import path as util_path
124 from IPython.utils import path as util_path
126 from IPython.utils import py3compat
125 from IPython.utils import py3compat
127 from IPython.utils import ulinecache
126 from IPython.utils import ulinecache
128 from IPython.utils.data import uniq_stable
127 from IPython.utils.data import uniq_stable
129 from IPython.utils.terminal import get_terminal_size
128 from IPython.utils.terminal import get_terminal_size
130 from logging import info, error
129 from logging import info, error
131
130
132 import IPython.utils.colorable as colorable
131 import IPython.utils.colorable as colorable
133
132
134 # Globals
133 # Globals
135 # amount of space to put line numbers before verbose tracebacks
134 # amount of space to put line numbers before verbose tracebacks
136 INDENT_SIZE = 8
135 INDENT_SIZE = 8
137
136
138 # Default color scheme. This is used, for example, by the traceback
137 # Default color scheme. This is used, for example, by the traceback
139 # formatter. When running in an actual IPython instance, the user's rc.colors
138 # formatter. When running in an actual IPython instance, the user's rc.colors
140 # value is used, but having a module global makes this functionality available
139 # value is used, but having a module global makes this functionality available
141 # to users of ultratb who are NOT running inside ipython.
140 # to users of ultratb who are NOT running inside ipython.
142 DEFAULT_SCHEME = 'NoColor'
141 DEFAULT_SCHEME = 'NoColor'
143
142
144 # ---------------------------------------------------------------------------
143 # ---------------------------------------------------------------------------
145 # Code begins
144 # Code begins
146
145
147 # Utility functions
146 # Utility functions
148 def inspect_error():
147 def inspect_error():
149 """Print a message about internal inspect errors.
148 """Print a message about internal inspect errors.
150
149
151 These are unfortunately quite common."""
150 These are unfortunately quite common."""
152
151
153 error('Internal Python error in the inspect module.\n'
152 error('Internal Python error in the inspect module.\n'
154 'Below is the traceback from this internal error.\n')
153 'Below is the traceback from this internal error.\n')
155
154
156
155
157 # This function is a monkeypatch we apply to the Python inspect module. We have
156 # This function is a monkeypatch we apply to the Python inspect module. We have
158 # now found when it's needed (see discussion on issue gh-1456), and we have a
157 # now found when it's needed (see discussion on issue gh-1456), and we have a
159 # test case (IPython.core.tests.test_ultratb.ChangedPyFileTest) that fails if
158 # test case (IPython.core.tests.test_ultratb.ChangedPyFileTest) that fails if
160 # the monkeypatch is not applied. TK, Aug 2012.
159 # the monkeypatch is not applied. TK, Aug 2012.
161 def findsource(object):
160 def findsource(object):
162 """Return the entire source file and starting line number for an object.
161 """Return the entire source file and starting line number for an object.
163
162
164 The argument may be a module, class, method, function, traceback, frame,
163 The argument may be a module, class, method, function, traceback, frame,
165 or code object. The source code is returned as a list of all the lines
164 or code object. The source code is returned as a list of all the lines
166 in the file and the line number indexes a line in that list. An IOError
165 in the file and the line number indexes a line in that list. An IOError
167 is raised if the source code cannot be retrieved.
166 is raised if the source code cannot be retrieved.
168
167
169 FIXED version with which we monkeypatch the stdlib to work around a bug."""
168 FIXED version with which we monkeypatch the stdlib to work around a bug."""
170
169
171 file = getsourcefile(object) or getfile(object)
170 file = getsourcefile(object) or getfile(object)
172 # If the object is a frame, then trying to get the globals dict from its
171 # If the object is a frame, then trying to get the globals dict from its
173 # module won't work. Instead, the frame object itself has the globals
172 # module won't work. Instead, the frame object itself has the globals
174 # dictionary.
173 # dictionary.
175 globals_dict = None
174 globals_dict = None
176 if inspect.isframe(object):
175 if inspect.isframe(object):
177 # XXX: can this ever be false?
176 # XXX: can this ever be false?
178 globals_dict = object.f_globals
177 globals_dict = object.f_globals
179 else:
178 else:
180 module = getmodule(object, file)
179 module = getmodule(object, file)
181 if module:
180 if module:
182 globals_dict = module.__dict__
181 globals_dict = module.__dict__
183 lines = linecache.getlines(file, globals_dict)
182 lines = linecache.getlines(file, globals_dict)
184 if not lines:
183 if not lines:
185 raise IOError('could not get source code')
184 raise IOError('could not get source code')
186
185
187 if ismodule(object):
186 if ismodule(object):
188 return lines, 0
187 return lines, 0
189
188
190 if isclass(object):
189 if isclass(object):
191 name = object.__name__
190 name = object.__name__
192 pat = re.compile(r'^(\s*)class\s*' + name + r'\b')
191 pat = re.compile(r'^(\s*)class\s*' + name + r'\b')
193 # make some effort to find the best matching class definition:
192 # make some effort to find the best matching class definition:
194 # use the one with the least indentation, which is the one
193 # use the one with the least indentation, which is the one
195 # that's most probably not inside a function definition.
194 # that's most probably not inside a function definition.
196 candidates = []
195 candidates = []
197 for i in range(len(lines)):
196 for i in range(len(lines)):
198 match = pat.match(lines[i])
197 match = pat.match(lines[i])
199 if match:
198 if match:
200 # if it's at toplevel, it's already the best one
199 # if it's at toplevel, it's already the best one
201 if lines[i][0] == 'c':
200 if lines[i][0] == 'c':
202 return lines, i
201 return lines, i
203 # else add whitespace to candidate list
202 # else add whitespace to candidate list
204 candidates.append((match.group(1), i))
203 candidates.append((match.group(1), i))
205 if candidates:
204 if candidates:
206 # this will sort by whitespace, and by line number,
205 # this will sort by whitespace, and by line number,
207 # less whitespace first
206 # less whitespace first
208 candidates.sort()
207 candidates.sort()
209 return lines, candidates[0][1]
208 return lines, candidates[0][1]
210 else:
209 else:
211 raise IOError('could not find class definition')
210 raise IOError('could not find class definition')
212
211
213 if ismethod(object):
212 if ismethod(object):
214 object = object.__func__
213 object = object.__func__
215 if isfunction(object):
214 if isfunction(object):
216 object = object.__code__
215 object = object.__code__
217 if istraceback(object):
216 if istraceback(object):
218 object = object.tb_frame
217 object = object.tb_frame
219 if isframe(object):
218 if isframe(object):
220 object = object.f_code
219 object = object.f_code
221 if iscode(object):
220 if iscode(object):
222 if not hasattr(object, 'co_firstlineno'):
221 if not hasattr(object, 'co_firstlineno'):
223 raise IOError('could not find function definition')
222 raise IOError('could not find function definition')
224 pat = re.compile(r'^(\s*def\s)|(.*(?<!\w)lambda(:|\s))|^(\s*@)')
223 pat = re.compile(r'^(\s*def\s)|(.*(?<!\w)lambda(:|\s))|^(\s*@)')
225 pmatch = pat.match
224 pmatch = pat.match
226 # fperez - fix: sometimes, co_firstlineno can give a number larger than
225 # fperez - fix: sometimes, co_firstlineno can give a number larger than
227 # the length of lines, which causes an error. Safeguard against that.
226 # the length of lines, which causes an error. Safeguard against that.
228 lnum = min(object.co_firstlineno, len(lines)) - 1
227 lnum = min(object.co_firstlineno, len(lines)) - 1
229 while lnum > 0:
228 while lnum > 0:
230 if pmatch(lines[lnum]):
229 if pmatch(lines[lnum]):
231 break
230 break
232 lnum -= 1
231 lnum -= 1
233
232
234 return lines, lnum
233 return lines, lnum
235 raise IOError('could not find code object')
234 raise IOError('could not find code object')
236
235
237
236
238 # This is a patched version of inspect.getargs that applies the (unmerged)
237 # This is a patched version of inspect.getargs that applies the (unmerged)
239 # patch for http://bugs.python.org/issue14611 by Stefano Taschini. This fixes
238 # patch for http://bugs.python.org/issue14611 by Stefano Taschini. This fixes
240 # https://github.com/ipython/ipython/issues/8205 and
239 # https://github.com/ipython/ipython/issues/8205 and
241 # https://github.com/ipython/ipython/issues/8293
240 # https://github.com/ipython/ipython/issues/8293
242 def getargs(co):
241 def getargs(co):
243 """Get information about the arguments accepted by a code object.
242 """Get information about the arguments accepted by a code object.
244
243
245 Three things are returned: (args, varargs, varkw), where 'args' is
244 Three things are returned: (args, varargs, varkw), where 'args' is
246 a list of argument names (possibly containing nested lists), and
245 a list of argument names (possibly containing nested lists), and
247 'varargs' and 'varkw' are the names of the * and ** arguments or None."""
246 'varargs' and 'varkw' are the names of the * and ** arguments or None."""
248 if not iscode(co):
247 if not iscode(co):
249 raise TypeError('{!r} is not a code object'.format(co))
248 raise TypeError('{!r} is not a code object'.format(co))
250
249
251 nargs = co.co_argcount
250 nargs = co.co_argcount
252 names = co.co_varnames
251 names = co.co_varnames
253 args = list(names[:nargs])
252 args = list(names[:nargs])
254 step = 0
253 step = 0
255
254
256 # The following acrobatics are for anonymous (tuple) arguments.
255 # The following acrobatics are for anonymous (tuple) arguments.
257 for i in range(nargs):
256 for i in range(nargs):
258 if args[i][:1] in ('', '.'):
257 if args[i][:1] in ('', '.'):
259 stack, remain, count = [], [], []
258 stack, remain, count = [], [], []
260 while step < len(co.co_code):
259 while step < len(co.co_code):
261 op = ord(co.co_code[step])
260 op = ord(co.co_code[step])
262 step = step + 1
261 step = step + 1
263 if op >= dis.HAVE_ARGUMENT:
262 if op >= dis.HAVE_ARGUMENT:
264 opname = dis.opname[op]
263 opname = dis.opname[op]
265 value = ord(co.co_code[step]) + ord(co.co_code[step+1])*256
264 value = ord(co.co_code[step]) + ord(co.co_code[step+1])*256
266 step = step + 2
265 step = step + 2
267 if opname in ('UNPACK_TUPLE', 'UNPACK_SEQUENCE'):
266 if opname in ('UNPACK_TUPLE', 'UNPACK_SEQUENCE'):
268 remain.append(value)
267 remain.append(value)
269 count.append(value)
268 count.append(value)
270 elif opname in ('STORE_FAST', 'STORE_DEREF'):
269 elif opname in ('STORE_FAST', 'STORE_DEREF'):
271 if op in dis.haslocal:
270 if op in dis.haslocal:
272 stack.append(co.co_varnames[value])
271 stack.append(co.co_varnames[value])
273 elif op in dis.hasfree:
272 elif op in dis.hasfree:
274 stack.append((co.co_cellvars + co.co_freevars)[value])
273 stack.append((co.co_cellvars + co.co_freevars)[value])
275 # Special case for sublists of length 1: def foo((bar))
274 # Special case for sublists of length 1: def foo((bar))
276 # doesn't generate the UNPACK_TUPLE bytecode, so if
275 # doesn't generate the UNPACK_TUPLE bytecode, so if
277 # `remain` is empty here, we have such a sublist.
276 # `remain` is empty here, we have such a sublist.
278 if not remain:
277 if not remain:
279 stack[0] = [stack[0]]
278 stack[0] = [stack[0]]
280 break
279 break
281 else:
280 else:
282 remain[-1] = remain[-1] - 1
281 remain[-1] = remain[-1] - 1
283 while remain[-1] == 0:
282 while remain[-1] == 0:
284 remain.pop()
283 remain.pop()
285 size = count.pop()
284 size = count.pop()
286 stack[-size:] = [stack[-size:]]
285 stack[-size:] = [stack[-size:]]
287 if not remain:
286 if not remain:
288 break
287 break
289 remain[-1] = remain[-1] - 1
288 remain[-1] = remain[-1] - 1
290 if not remain:
289 if not remain:
291 break
290 break
292 args[i] = stack[0]
291 args[i] = stack[0]
293
292
294 varargs = None
293 varargs = None
295 if co.co_flags & inspect.CO_VARARGS:
294 if co.co_flags & inspect.CO_VARARGS:
296 varargs = co.co_varnames[nargs]
295 varargs = co.co_varnames[nargs]
297 nargs = nargs + 1
296 nargs = nargs + 1
298 varkw = None
297 varkw = None
299 if co.co_flags & inspect.CO_VARKEYWORDS:
298 if co.co_flags & inspect.CO_VARKEYWORDS:
300 varkw = co.co_varnames[nargs]
299 varkw = co.co_varnames[nargs]
301 return inspect.Arguments(args, varargs, varkw)
300 return inspect.Arguments(args, varargs, varkw)
302
301
303
302
304 # Monkeypatch inspect to apply our bugfix.
303 # Monkeypatch inspect to apply our bugfix.
305 def with_patch_inspect(f):
304 def with_patch_inspect(f):
306 """decorator for monkeypatching inspect.findsource"""
305 """decorator for monkeypatching inspect.findsource"""
307
306
308 def wrapped(*args, **kwargs):
307 def wrapped(*args, **kwargs):
309 save_findsource = inspect.findsource
308 save_findsource = inspect.findsource
310 save_getargs = inspect.getargs
309 save_getargs = inspect.getargs
311 inspect.findsource = findsource
310 inspect.findsource = findsource
312 inspect.getargs = getargs
311 inspect.getargs = getargs
313 try:
312 try:
314 return f(*args, **kwargs)
313 return f(*args, **kwargs)
315 finally:
314 finally:
316 inspect.findsource = save_findsource
315 inspect.findsource = save_findsource
317 inspect.getargs = save_getargs
316 inspect.getargs = save_getargs
318
317
319 return wrapped
318 return wrapped
320
319
321
320
322 if py3compat.PY3:
321 if py3compat.PY3:
323 fixed_getargvalues = inspect.getargvalues
322 fixed_getargvalues = inspect.getargvalues
324 else:
323 else:
325 # Fixes for https://github.com/ipython/ipython/issues/8293
324 # Fixes for https://github.com/ipython/ipython/issues/8293
326 # and https://github.com/ipython/ipython/issues/8205.
325 # and https://github.com/ipython/ipython/issues/8205.
327 # The relevant bug is caused by failure to correctly handle anonymous tuple
326 # The relevant bug is caused by failure to correctly handle anonymous tuple
328 # unpacking, which only exists in Python 2.
327 # unpacking, which only exists in Python 2.
329 fixed_getargvalues = with_patch_inspect(inspect.getargvalues)
328 fixed_getargvalues = with_patch_inspect(inspect.getargvalues)
330
329
331
330
332 def fix_frame_records_filenames(records):
331 def fix_frame_records_filenames(records):
333 """Try to fix the filenames in each record from inspect.getinnerframes().
332 """Try to fix the filenames in each record from inspect.getinnerframes().
334
333
335 Particularly, modules loaded from within zip files have useless filenames
334 Particularly, modules loaded from within zip files have useless filenames
336 attached to their code object, and inspect.getinnerframes() just uses it.
335 attached to their code object, and inspect.getinnerframes() just uses it.
337 """
336 """
338 fixed_records = []
337 fixed_records = []
339 for frame, filename, line_no, func_name, lines, index in records:
338 for frame, filename, line_no, func_name, lines, index in records:
340 # Look inside the frame's globals dictionary for __file__,
339 # Look inside the frame's globals dictionary for __file__,
341 # which should be better. However, keep Cython filenames since
340 # which should be better. However, keep Cython filenames since
342 # we prefer the source filenames over the compiled .so file.
341 # we prefer the source filenames over the compiled .so file.
343 filename = py3compat.cast_unicode_py2(filename, "utf-8")
342 filename = py3compat.cast_unicode_py2(filename, "utf-8")
344 if not filename.endswith(('.pyx', '.pxd', '.pxi')):
343 if not filename.endswith(('.pyx', '.pxd', '.pxi')):
345 better_fn = frame.f_globals.get('__file__', None)
344 better_fn = frame.f_globals.get('__file__', None)
346 if isinstance(better_fn, str):
345 if isinstance(better_fn, str):
347 # Check the type just in case someone did something weird with
346 # Check the type just in case someone did something weird with
348 # __file__. It might also be None if the error occurred during
347 # __file__. It might also be None if the error occurred during
349 # import.
348 # import.
350 filename = better_fn
349 filename = better_fn
351 fixed_records.append((frame, filename, line_no, func_name, lines, index))
350 fixed_records.append((frame, filename, line_no, func_name, lines, index))
352 return fixed_records
351 return fixed_records
353
352
354
353
355 @with_patch_inspect
354 @with_patch_inspect
356 def _fixed_getinnerframes(etb, context=1, tb_offset=0):
355 def _fixed_getinnerframes(etb, context=1, tb_offset=0):
357 LNUM_POS, LINES_POS, INDEX_POS = 2, 4, 5
356 LNUM_POS, LINES_POS, INDEX_POS = 2, 4, 5
358
357
359 records = fix_frame_records_filenames(inspect.getinnerframes(etb, context))
358 records = fix_frame_records_filenames(inspect.getinnerframes(etb, context))
360 # If the error is at the console, don't build any context, since it would
359 # If the error is at the console, don't build any context, since it would
361 # otherwise produce 5 blank lines printed out (there is no file at the
360 # otherwise produce 5 blank lines printed out (there is no file at the
362 # console)
361 # console)
363 rec_check = records[tb_offset:]
362 rec_check = records[tb_offset:]
364 try:
363 try:
365 rname = rec_check[0][1]
364 rname = rec_check[0][1]
366 if rname == '<ipython console>' or rname.endswith('<string>'):
365 if rname == '<ipython console>' or rname.endswith('<string>'):
367 return rec_check
366 return rec_check
368 except IndexError:
367 except IndexError:
369 pass
368 pass
370
369
371 aux = traceback.extract_tb(etb)
370 aux = traceback.extract_tb(etb)
372 assert len(records) == len(aux)
371 assert len(records) == len(aux)
373 for i, (file, lnum, _, _) in zip(range(len(records)), aux):
372 for i, (file, lnum, _, _) in zip(range(len(records)), aux):
374 maybeStart = lnum - 1 - context // 2
373 maybeStart = lnum - 1 - context // 2
375 start = max(maybeStart, 0)
374 start = max(maybeStart, 0)
376 end = start + context
375 end = start + context
377 lines = ulinecache.getlines(file)[start:end]
376 lines = ulinecache.getlines(file)[start:end]
378 buf = list(records[i])
377 buf = list(records[i])
379 buf[LNUM_POS] = lnum
378 buf[LNUM_POS] = lnum
380 buf[INDEX_POS] = lnum - 1 - start
379 buf[INDEX_POS] = lnum - 1 - start
381 buf[LINES_POS] = lines
380 buf[LINES_POS] = lines
382 records[i] = tuple(buf)
381 records[i] = tuple(buf)
383 return records[tb_offset:]
382 return records[tb_offset:]
384
383
385 # Helper function -- largely belongs to VerboseTB, but we need the same
384 # Helper function -- largely belongs to VerboseTB, but we need the same
386 # functionality to produce a pseudo verbose TB for SyntaxErrors, so that they
385 # functionality to produce a pseudo verbose TB for SyntaxErrors, so that they
387 # can be recognized properly by ipython.el's py-traceback-line-re
386 # can be recognized properly by ipython.el's py-traceback-line-re
388 # (SyntaxErrors have to be treated specially because they have no traceback)
387 # (SyntaxErrors have to be treated specially because they have no traceback)
389
388
390 _parser = PyColorize.Parser()
389 _parser = PyColorize.Parser()
391
390
392
391
393 def _format_traceback_lines(lnum, index, lines, Colors, lvals=None, scheme=None):
392 def _format_traceback_lines(lnum, index, lines, Colors, lvals=None, scheme=None):
394 numbers_width = INDENT_SIZE - 1
393 numbers_width = INDENT_SIZE - 1
395 res = []
394 res = []
396 i = lnum - index
395 i = lnum - index
397
396
398 # This lets us get fully syntax-highlighted tracebacks.
397 # This lets us get fully syntax-highlighted tracebacks.
399 if scheme is None:
398 if scheme is None:
400 ipinst = get_ipython()
399 ipinst = get_ipython()
401 if ipinst is not None:
400 if ipinst is not None:
402 scheme = ipinst.colors
401 scheme = ipinst.colors
403 else:
402 else:
404 scheme = DEFAULT_SCHEME
403 scheme = DEFAULT_SCHEME
405
404
406 _line_format = _parser.format2
405 _line_format = _parser.format2
407
406
408 for line in lines:
407 for line in lines:
409 line = py3compat.cast_unicode(line)
408 line = py3compat.cast_unicode(line)
410
409
411 new_line, err = _line_format(line, 'str', scheme)
410 new_line, err = _line_format(line, 'str', scheme)
412 if not err: line = new_line
411 if not err: line = new_line
413
412
414 if i == lnum:
413 if i == lnum:
415 # This is the line with the error
414 # This is the line with the error
416 pad = numbers_width - len(str(i))
415 pad = numbers_width - len(str(i))
417 num = '%s%s' % (debugger.make_arrow(pad), str(lnum))
416 num = '%s%s' % (debugger.make_arrow(pad), str(lnum))
418 line = '%s%s%s %s%s' % (Colors.linenoEm, num,
417 line = '%s%s%s %s%s' % (Colors.linenoEm, num,
419 Colors.line, line, Colors.Normal)
418 Colors.line, line, Colors.Normal)
420 else:
419 else:
421 num = '%*s' % (numbers_width, i)
420 num = '%*s' % (numbers_width, i)
422 line = '%s%s%s %s' % (Colors.lineno, num,
421 line = '%s%s%s %s' % (Colors.lineno, num,
423 Colors.Normal, line)
422 Colors.Normal, line)
424
423
425 res.append(line)
424 res.append(line)
426 if lvals and i == lnum:
425 if lvals and i == lnum:
427 res.append(lvals + '\n')
426 res.append(lvals + '\n')
428 i = i + 1
427 i = i + 1
429 return res
428 return res
430
429
431 def is_recursion_error(etype, value, records):
430 def is_recursion_error(etype, value, records):
432 try:
431 try:
433 # RecursionError is new in Python 3.5
432 # RecursionError is new in Python 3.5
434 recursion_error_type = RecursionError
433 recursion_error_type = RecursionError
435 except NameError:
434 except NameError:
436 recursion_error_type = RuntimeError
435 recursion_error_type = RuntimeError
437
436
438 # The default recursion limit is 1000, but some of that will be taken up
437 # The default recursion limit is 1000, but some of that will be taken up
439 # by stack frames in IPython itself. >500 frames probably indicates
438 # by stack frames in IPython itself. >500 frames probably indicates
440 # a recursion error.
439 # a recursion error.
441 return (etype is recursion_error_type) \
440 return (etype is recursion_error_type) \
442 and "recursion" in str(value).lower() \
441 and "recursion" in str(value).lower() \
443 and len(records) > 500
442 and len(records) > 500
444
443
445 def find_recursion(etype, value, records):
444 def find_recursion(etype, value, records):
446 """Identify the repeating stack frames from a RecursionError traceback
445 """Identify the repeating stack frames from a RecursionError traceback
447
446
448 'records' is a list as returned by VerboseTB.get_records()
447 'records' is a list as returned by VerboseTB.get_records()
449
448
450 Returns (last_unique, repeat_length)
449 Returns (last_unique, repeat_length)
451 """
450 """
452 # This involves a bit of guesswork - we want to show enough of the traceback
451 # This involves a bit of guesswork - we want to show enough of the traceback
453 # to indicate where the recursion is occurring. We guess that the innermost
452 # to indicate where the recursion is occurring. We guess that the innermost
454 # quarter of the traceback (250 frames by default) is repeats, and find the
453 # quarter of the traceback (250 frames by default) is repeats, and find the
455 # first frame (from in to out) that looks different.
454 # first frame (from in to out) that looks different.
456 if not is_recursion_error(etype, value, records):
455 if not is_recursion_error(etype, value, records):
457 return len(records), 0
456 return len(records), 0
458
457
459 # Select filename, lineno, func_name to track frames with
458 # Select filename, lineno, func_name to track frames with
460 records = [r[1:4] for r in records]
459 records = [r[1:4] for r in records]
461 inner_frames = records[-(len(records)//4):]
460 inner_frames = records[-(len(records)//4):]
462 frames_repeated = set(inner_frames)
461 frames_repeated = set(inner_frames)
463
462
464 last_seen_at = {}
463 last_seen_at = {}
465 longest_repeat = 0
464 longest_repeat = 0
466 i = len(records)
465 i = len(records)
467 for frame in reversed(records):
466 for frame in reversed(records):
468 i -= 1
467 i -= 1
469 if frame not in frames_repeated:
468 if frame not in frames_repeated:
470 last_unique = i
469 last_unique = i
471 break
470 break
472
471
473 if frame in last_seen_at:
472 if frame in last_seen_at:
474 distance = last_seen_at[frame] - i
473 distance = last_seen_at[frame] - i
475 longest_repeat = max(longest_repeat, distance)
474 longest_repeat = max(longest_repeat, distance)
476
475
477 last_seen_at[frame] = i
476 last_seen_at[frame] = i
478 else:
477 else:
479 last_unique = 0 # The whole traceback was recursion
478 last_unique = 0 # The whole traceback was recursion
480
479
481 return last_unique, longest_repeat
480 return last_unique, longest_repeat
482
481
483 #---------------------------------------------------------------------------
482 #---------------------------------------------------------------------------
484 # Module classes
483 # Module classes
485 class TBTools(colorable.Colorable):
484 class TBTools(colorable.Colorable):
486 """Basic tools used by all traceback printer classes."""
485 """Basic tools used by all traceback printer classes."""
487
486
488 # Number of frames to skip when reporting tracebacks
487 # Number of frames to skip when reporting tracebacks
489 tb_offset = 0
488 tb_offset = 0
490
489
491 def __init__(self, color_scheme='NoColor', call_pdb=False, ostream=None, parent=None, config=None):
490 def __init__(self, color_scheme='NoColor', call_pdb=False, ostream=None, parent=None, config=None):
492 # Whether to call the interactive pdb debugger after printing
491 # Whether to call the interactive pdb debugger after printing
493 # tracebacks or not
492 # tracebacks or not
494 super(TBTools, self).__init__(parent=parent, config=config)
493 super(TBTools, self).__init__(parent=parent, config=config)
495 self.call_pdb = call_pdb
494 self.call_pdb = call_pdb
496
495
497 # Output stream to write to. Note that we store the original value in
496 # Output stream to write to. Note that we store the original value in
498 # a private attribute and then make the public ostream a property, so
497 # a private attribute and then make the public ostream a property, so
499 # that we can delay accessing io.stdout until runtime. The way
498 # that we can delay accessing io.stdout until runtime. The way
500 # things are written now, the io.stdout object is dynamically managed
499 # things are written now, the io.stdout object is dynamically managed
501 # so a reference to it should NEVER be stored statically. This
500 # so a reference to it should NEVER be stored statically. This
502 # property approach confines this detail to a single location, and all
501 # property approach confines this detail to a single location, and all
503 # subclasses can simply access self.ostream for writing.
502 # subclasses can simply access self.ostream for writing.
504 self._ostream = ostream
503 self._ostream = ostream
505
504
506 # Create color table
505 # Create color table
507 self.color_scheme_table = exception_colors()
506 self.color_scheme_table = exception_colors()
508
507
509 self.set_colors(color_scheme)
508 self.set_colors(color_scheme)
510 self.old_scheme = color_scheme # save initial value for toggles
509 self.old_scheme = color_scheme # save initial value for toggles
511
510
512 if call_pdb:
511 if call_pdb:
513 self.pdb = debugger.Pdb(self.color_scheme_table.active_scheme_name)
512 self.pdb = debugger.Pdb(self.color_scheme_table.active_scheme_name)
514 else:
513 else:
515 self.pdb = None
514 self.pdb = None
516
515
517 def _get_ostream(self):
516 def _get_ostream(self):
518 """Output stream that exceptions are written to.
517 """Output stream that exceptions are written to.
519
518
520 Valid values are:
519 Valid values are:
521
520
522 - None: the default, which means that IPython will dynamically resolve
521 - None: the default, which means that IPython will dynamically resolve
523 to io.stdout. This ensures compatibility with most tools, including
522 to io.stdout. This ensures compatibility with most tools, including
524 Windows (where plain stdout doesn't recognize ANSI escapes).
523 Windows (where plain stdout doesn't recognize ANSI escapes).
525
524
526 - Any object with 'write' and 'flush' attributes.
525 - Any object with 'write' and 'flush' attributes.
527 """
526 """
528 return sys.stdout if self._ostream is None else self._ostream
527 return sys.stdout if self._ostream is None else self._ostream
529
528
530 def _set_ostream(self, val):
529 def _set_ostream(self, val):
531 assert val is None or (hasattr(val, 'write') and hasattr(val, 'flush'))
530 assert val is None or (hasattr(val, 'write') and hasattr(val, 'flush'))
532 self._ostream = val
531 self._ostream = val
533
532
534 ostream = property(_get_ostream, _set_ostream)
533 ostream = property(_get_ostream, _set_ostream)
535
534
536 def set_colors(self, *args, **kw):
535 def set_colors(self, *args, **kw):
537 """Shorthand access to the color table scheme selector method."""
536 """Shorthand access to the color table scheme selector method."""
538
537
539 # Set own color table
538 # Set own color table
540 self.color_scheme_table.set_active_scheme(*args, **kw)
539 self.color_scheme_table.set_active_scheme(*args, **kw)
541 # for convenience, set Colors to the active scheme
540 # for convenience, set Colors to the active scheme
542 self.Colors = self.color_scheme_table.active_colors
541 self.Colors = self.color_scheme_table.active_colors
543 # Also set colors of debugger
542 # Also set colors of debugger
544 if hasattr(self, 'pdb') and self.pdb is not None:
543 if hasattr(self, 'pdb') and self.pdb is not None:
545 self.pdb.set_colors(*args, **kw)
544 self.pdb.set_colors(*args, **kw)
546
545
547 def color_toggle(self):
546 def color_toggle(self):
548 """Toggle between the currently active color scheme and NoColor."""
547 """Toggle between the currently active color scheme and NoColor."""
549
548
550 if self.color_scheme_table.active_scheme_name == 'NoColor':
549 if self.color_scheme_table.active_scheme_name == 'NoColor':
551 self.color_scheme_table.set_active_scheme(self.old_scheme)
550 self.color_scheme_table.set_active_scheme(self.old_scheme)
552 self.Colors = self.color_scheme_table.active_colors
551 self.Colors = self.color_scheme_table.active_colors
553 else:
552 else:
554 self.old_scheme = self.color_scheme_table.active_scheme_name
553 self.old_scheme = self.color_scheme_table.active_scheme_name
555 self.color_scheme_table.set_active_scheme('NoColor')
554 self.color_scheme_table.set_active_scheme('NoColor')
556 self.Colors = self.color_scheme_table.active_colors
555 self.Colors = self.color_scheme_table.active_colors
557
556
558 def stb2text(self, stb):
557 def stb2text(self, stb):
559 """Convert a structured traceback (a list) to a string."""
558 """Convert a structured traceback (a list) to a string."""
560 return '\n'.join(stb)
559 return '\n'.join(stb)
561
560
562 def text(self, etype, value, tb, tb_offset=None, context=5):
561 def text(self, etype, value, tb, tb_offset=None, context=5):
563 """Return formatted traceback.
562 """Return formatted traceback.
564
563
565 Subclasses may override this if they add extra arguments.
564 Subclasses may override this if they add extra arguments.
566 """
565 """
567 tb_list = self.structured_traceback(etype, value, tb,
566 tb_list = self.structured_traceback(etype, value, tb,
568 tb_offset, context)
567 tb_offset, context)
569 return self.stb2text(tb_list)
568 return self.stb2text(tb_list)
570
569
571 def structured_traceback(self, etype, evalue, tb, tb_offset=None,
570 def structured_traceback(self, etype, evalue, tb, tb_offset=None,
572 context=5, mode=None):
571 context=5, mode=None):
573 """Return a list of traceback frames.
572 """Return a list of traceback frames.
574
573
575 Must be implemented by each class.
574 Must be implemented by each class.
576 """
575 """
577 raise NotImplementedError()
576 raise NotImplementedError()
578
577
579
578
580 #---------------------------------------------------------------------------
579 #---------------------------------------------------------------------------
581 class ListTB(TBTools):
580 class ListTB(TBTools):
582 """Print traceback information from a traceback list, with optional color.
581 """Print traceback information from a traceback list, with optional color.
583
582
584 Calling requires 3 arguments: (etype, evalue, elist)
583 Calling requires 3 arguments: (etype, evalue, elist)
585 as would be obtained by::
584 as would be obtained by::
586
585
587 etype, evalue, tb = sys.exc_info()
586 etype, evalue, tb = sys.exc_info()
588 if tb:
587 if tb:
589 elist = traceback.extract_tb(tb)
588 elist = traceback.extract_tb(tb)
590 else:
589 else:
591 elist = None
590 elist = None
592
591
593 It can thus be used by programs which need to process the traceback before
592 It can thus be used by programs which need to process the traceback before
594 printing (such as console replacements based on the code module from the
593 printing (such as console replacements based on the code module from the
595 standard library).
594 standard library).
596
595
597 Because they are meant to be called without a full traceback (only a
596 Because they are meant to be called without a full traceback (only a
598 list), instances of this class can't call the interactive pdb debugger."""
597 list), instances of this class can't call the interactive pdb debugger."""
599
598
600 def __init__(self, color_scheme='NoColor', call_pdb=False, ostream=None, parent=None):
599 def __init__(self, color_scheme='NoColor', call_pdb=False, ostream=None, parent=None):
601 TBTools.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
600 TBTools.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
602 ostream=ostream, parent=parent)
601 ostream=ostream, parent=parent)
603
602
604 def __call__(self, etype, value, elist):
603 def __call__(self, etype, value, elist):
605 self.ostream.flush()
604 self.ostream.flush()
606 self.ostream.write(self.text(etype, value, elist))
605 self.ostream.write(self.text(etype, value, elist))
607 self.ostream.write('\n')
606 self.ostream.write('\n')
608
607
609 def structured_traceback(self, etype, value, elist, tb_offset=None,
608 def structured_traceback(self, etype, value, elist, tb_offset=None,
610 context=5):
609 context=5):
611 """Return a color formatted string with the traceback info.
610 """Return a color formatted string with the traceback info.
612
611
613 Parameters
612 Parameters
614 ----------
613 ----------
615 etype : exception type
614 etype : exception type
616 Type of the exception raised.
615 Type of the exception raised.
617
616
618 value : object
617 value : object
619 Data stored in the exception
618 Data stored in the exception
620
619
621 elist : list
620 elist : list
622 List of frames, see class docstring for details.
621 List of frames, see class docstring for details.
623
622
624 tb_offset : int, optional
623 tb_offset : int, optional
625 Number of frames in the traceback to skip. If not given, the
624 Number of frames in the traceback to skip. If not given, the
626 instance value is used (set in constructor).
625 instance value is used (set in constructor).
627
626
628 context : int, optional
627 context : int, optional
629 Number of lines of context information to print.
628 Number of lines of context information to print.
630
629
631 Returns
630 Returns
632 -------
631 -------
633 String with formatted exception.
632 String with formatted exception.
634 """
633 """
635 tb_offset = self.tb_offset if tb_offset is None else tb_offset
634 tb_offset = self.tb_offset if tb_offset is None else tb_offset
636 Colors = self.Colors
635 Colors = self.Colors
637 out_list = []
636 out_list = []
638 if elist:
637 if elist:
639
638
640 if tb_offset and len(elist) > tb_offset:
639 if tb_offset and len(elist) > tb_offset:
641 elist = elist[tb_offset:]
640 elist = elist[tb_offset:]
642
641
643 out_list.append('Traceback %s(most recent call last)%s:' %
642 out_list.append('Traceback %s(most recent call last)%s:' %
644 (Colors.normalEm, Colors.Normal) + '\n')
643 (Colors.normalEm, Colors.Normal) + '\n')
645 out_list.extend(self._format_list(elist))
644 out_list.extend(self._format_list(elist))
646 # The exception info should be a single entry in the list.
645 # The exception info should be a single entry in the list.
647 lines = ''.join(self._format_exception_only(etype, value))
646 lines = ''.join(self._format_exception_only(etype, value))
648 out_list.append(lines)
647 out_list.append(lines)
649
648
650 # Note: this code originally read:
649 # Note: this code originally read:
651
650
652 ## for line in lines[:-1]:
651 ## for line in lines[:-1]:
653 ## out_list.append(" "+line)
652 ## out_list.append(" "+line)
654 ## out_list.append(lines[-1])
653 ## out_list.append(lines[-1])
655
654
656 # This means it was indenting everything but the last line by a little
655 # This means it was indenting everything but the last line by a little
657 # bit. I've disabled this for now, but if we see ugliness somewhere we
656 # bit. I've disabled this for now, but if we see ugliness somewhere we
658 # can restore it.
657 # can restore it.
659
658
660 return out_list
659 return out_list
661
660
662 def _format_list(self, extracted_list):
661 def _format_list(self, extracted_list):
663 """Format a list of traceback entry tuples for printing.
662 """Format a list of traceback entry tuples for printing.
664
663
665 Given a list of tuples as returned by extract_tb() or
664 Given a list of tuples as returned by extract_tb() or
666 extract_stack(), return a list of strings ready for printing.
665 extract_stack(), return a list of strings ready for printing.
667 Each string in the resulting list corresponds to the item with the
666 Each string in the resulting list corresponds to the item with the
668 same index in the argument list. Each string ends in a newline;
667 same index in the argument list. Each string ends in a newline;
669 the strings may contain internal newlines as well, for those items
668 the strings may contain internal newlines as well, for those items
670 whose source text line is not None.
669 whose source text line is not None.
671
670
672 Lifted almost verbatim from traceback.py
671 Lifted almost verbatim from traceback.py
673 """
672 """
674
673
675 Colors = self.Colors
674 Colors = self.Colors
676 list = []
675 list = []
677 for filename, lineno, name, line in extracted_list[:-1]:
676 for filename, lineno, name, line in extracted_list[:-1]:
678 item = ' File %s"%s"%s, line %s%d%s, in %s%s%s\n' % \
677 item = ' File %s"%s"%s, line %s%d%s, in %s%s%s\n' % \
679 (Colors.filename, py3compat.cast_unicode_py2(filename, "utf-8"), Colors.Normal,
678 (Colors.filename, py3compat.cast_unicode_py2(filename, "utf-8"), Colors.Normal,
680 Colors.lineno, lineno, Colors.Normal,
679 Colors.lineno, lineno, Colors.Normal,
681 Colors.name, py3compat.cast_unicode_py2(name, "utf-8"), Colors.Normal)
680 Colors.name, py3compat.cast_unicode_py2(name, "utf-8"), Colors.Normal)
682 if line:
681 if line:
683 item += ' %s\n' % line.strip()
682 item += ' %s\n' % line.strip()
684 list.append(item)
683 list.append(item)
685 # Emphasize the last entry
684 # Emphasize the last entry
686 filename, lineno, name, line = extracted_list[-1]
685 filename, lineno, name, line = extracted_list[-1]
687 item = '%s File %s"%s"%s, line %s%d%s, in %s%s%s%s\n' % \
686 item = '%s File %s"%s"%s, line %s%d%s, in %s%s%s%s\n' % \
688 (Colors.normalEm,
687 (Colors.normalEm,
689 Colors.filenameEm, py3compat.cast_unicode_py2(filename, "utf-8"), Colors.normalEm,
688 Colors.filenameEm, py3compat.cast_unicode_py2(filename, "utf-8"), Colors.normalEm,
690 Colors.linenoEm, lineno, Colors.normalEm,
689 Colors.linenoEm, lineno, Colors.normalEm,
691 Colors.nameEm, py3compat.cast_unicode_py2(name, "utf-8"), Colors.normalEm,
690 Colors.nameEm, py3compat.cast_unicode_py2(name, "utf-8"), Colors.normalEm,
692 Colors.Normal)
691 Colors.Normal)
693 if line:
692 if line:
694 item += '%s %s%s\n' % (Colors.line, line.strip(),
693 item += '%s %s%s\n' % (Colors.line, line.strip(),
695 Colors.Normal)
694 Colors.Normal)
696 list.append(item)
695 list.append(item)
697 return list
696 return list
698
697
699 def _format_exception_only(self, etype, value):
698 def _format_exception_only(self, etype, value):
700 """Format the exception part of a traceback.
699 """Format the exception part of a traceback.
701
700
702 The arguments are the exception type and value such as given by
701 The arguments are the exception type and value such as given by
703 sys.exc_info()[:2]. The return value is a list of strings, each ending
702 sys.exc_info()[:2]. The return value is a list of strings, each ending
704 in a newline. Normally, the list contains a single string; however,
703 in a newline. Normally, the list contains a single string; however,
705 for SyntaxError exceptions, it contains several lines that (when
704 for SyntaxError exceptions, it contains several lines that (when
706 printed) display detailed information about where the syntax error
705 printed) display detailed information about where the syntax error
707 occurred. The message indicating which exception occurred is the
706 occurred. The message indicating which exception occurred is the
708 always last string in the list.
707 always last string in the list.
709
708
710 Also lifted nearly verbatim from traceback.py
709 Also lifted nearly verbatim from traceback.py
711 """
710 """
712 have_filedata = False
711 have_filedata = False
713 Colors = self.Colors
712 Colors = self.Colors
714 list = []
713 list = []
715 stype = py3compat.cast_unicode(Colors.excName + etype.__name__ + Colors.Normal)
714 stype = py3compat.cast_unicode(Colors.excName + etype.__name__ + Colors.Normal)
716 if value is None:
715 if value is None:
717 # Not sure if this can still happen in Python 2.6 and above
716 # Not sure if this can still happen in Python 2.6 and above
718 list.append(stype + '\n')
717 list.append(stype + '\n')
719 else:
718 else:
720 if issubclass(etype, SyntaxError):
719 if issubclass(etype, SyntaxError):
721 have_filedata = True
720 have_filedata = True
722 if not value.filename: value.filename = "<string>"
721 if not value.filename: value.filename = "<string>"
723 if value.lineno:
722 if value.lineno:
724 lineno = value.lineno
723 lineno = value.lineno
725 textline = ulinecache.getline(value.filename, value.lineno)
724 textline = ulinecache.getline(value.filename, value.lineno)
726 else:
725 else:
727 lineno = 'unknown'
726 lineno = 'unknown'
728 textline = ''
727 textline = ''
729 list.append('%s File %s"%s"%s, line %s%s%s\n' % \
728 list.append('%s File %s"%s"%s, line %s%s%s\n' % \
730 (Colors.normalEm,
729 (Colors.normalEm,
731 Colors.filenameEm, py3compat.cast_unicode(value.filename), Colors.normalEm,
730 Colors.filenameEm, py3compat.cast_unicode(value.filename), Colors.normalEm,
732 Colors.linenoEm, lineno, Colors.Normal ))
731 Colors.linenoEm, lineno, Colors.Normal ))
733 if textline == '':
732 if textline == '':
734 textline = py3compat.cast_unicode(value.text, "utf-8")
733 textline = py3compat.cast_unicode(value.text, "utf-8")
735
734
736 if textline is not None:
735 if textline is not None:
737 i = 0
736 i = 0
738 while i < len(textline) and textline[i].isspace():
737 while i < len(textline) and textline[i].isspace():
739 i += 1
738 i += 1
740 list.append('%s %s%s\n' % (Colors.line,
739 list.append('%s %s%s\n' % (Colors.line,
741 textline.strip(),
740 textline.strip(),
742 Colors.Normal))
741 Colors.Normal))
743 if value.offset is not None:
742 if value.offset is not None:
744 s = ' '
743 s = ' '
745 for c in textline[i:value.offset - 1]:
744 for c in textline[i:value.offset - 1]:
746 if c.isspace():
745 if c.isspace():
747 s += c
746 s += c
748 else:
747 else:
749 s += ' '
748 s += ' '
750 list.append('%s%s^%s\n' % (Colors.caret, s,
749 list.append('%s%s^%s\n' % (Colors.caret, s,
751 Colors.Normal))
750 Colors.Normal))
752
751
753 try:
752 try:
754 s = value.msg
753 s = value.msg
755 except Exception:
754 except Exception:
756 s = self._some_str(value)
755 s = self._some_str(value)
757 if s:
756 if s:
758 list.append('%s%s:%s %s\n' % (stype, Colors.excName,
757 list.append('%s%s:%s %s\n' % (stype, Colors.excName,
759 Colors.Normal, s))
758 Colors.Normal, s))
760 else:
759 else:
761 list.append('%s\n' % stype)
760 list.append('%s\n' % stype)
762
761
763 # sync with user hooks
762 # sync with user hooks
764 if have_filedata:
763 if have_filedata:
765 ipinst = get_ipython()
764 ipinst = get_ipython()
766 if ipinst is not None:
765 if ipinst is not None:
767 ipinst.hooks.synchronize_with_editor(value.filename, value.lineno, 0)
766 ipinst.hooks.synchronize_with_editor(value.filename, value.lineno, 0)
768
767
769 return list
768 return list
770
769
771 def get_exception_only(self, etype, value):
770 def get_exception_only(self, etype, value):
772 """Only print the exception type and message, without a traceback.
771 """Only print the exception type and message, without a traceback.
773
772
774 Parameters
773 Parameters
775 ----------
774 ----------
776 etype : exception type
775 etype : exception type
777 value : exception value
776 value : exception value
778 """
777 """
779 return ListTB.structured_traceback(self, etype, value, [])
778 return ListTB.structured_traceback(self, etype, value, [])
780
779
781 def show_exception_only(self, etype, evalue):
780 def show_exception_only(self, etype, evalue):
782 """Only print the exception type and message, without a traceback.
781 """Only print the exception type and message, without a traceback.
783
782
784 Parameters
783 Parameters
785 ----------
784 ----------
786 etype : exception type
785 etype : exception type
787 value : exception value
786 value : exception value
788 """
787 """
789 # This method needs to use __call__ from *this* class, not the one from
788 # This method needs to use __call__ from *this* class, not the one from
790 # a subclass whose signature or behavior may be different
789 # a subclass whose signature or behavior may be different
791 ostream = self.ostream
790 ostream = self.ostream
792 ostream.flush()
791 ostream.flush()
793 ostream.write('\n'.join(self.get_exception_only(etype, evalue)))
792 ostream.write('\n'.join(self.get_exception_only(etype, evalue)))
794 ostream.flush()
793 ostream.flush()
795
794
796 def _some_str(self, value):
795 def _some_str(self, value):
797 # Lifted from traceback.py
796 # Lifted from traceback.py
798 try:
797 try:
799 return py3compat.cast_unicode(str(value))
798 return py3compat.cast_unicode(str(value))
800 except:
799 except:
801 return u'<unprintable %s object>' % type(value).__name__
800 return u'<unprintable %s object>' % type(value).__name__
802
801
803
802
804 #----------------------------------------------------------------------------
803 #----------------------------------------------------------------------------
805 class VerboseTB(TBTools):
804 class VerboseTB(TBTools):
806 """A port of Ka-Ping Yee's cgitb.py module that outputs color text instead
805 """A port of Ka-Ping Yee's cgitb.py module that outputs color text instead
807 of HTML. Requires inspect and pydoc. Crazy, man.
806 of HTML. Requires inspect and pydoc. Crazy, man.
808
807
809 Modified version which optionally strips the topmost entries from the
808 Modified version which optionally strips the topmost entries from the
810 traceback, to be used with alternate interpreters (because their own code
809 traceback, to be used with alternate interpreters (because their own code
811 would appear in the traceback)."""
810 would appear in the traceback)."""
812
811
813 def __init__(self, color_scheme='Linux', call_pdb=False, ostream=None,
812 def __init__(self, color_scheme='Linux', call_pdb=False, ostream=None,
814 tb_offset=0, long_header=False, include_vars=True,
813 tb_offset=0, long_header=False, include_vars=True,
815 check_cache=None, debugger_cls = None):
814 check_cache=None, debugger_cls = None):
816 """Specify traceback offset, headers and color scheme.
815 """Specify traceback offset, headers and color scheme.
817
816
818 Define how many frames to drop from the tracebacks. Calling it with
817 Define how many frames to drop from the tracebacks. Calling it with
819 tb_offset=1 allows use of this handler in interpreters which will have
818 tb_offset=1 allows use of this handler in interpreters which will have
820 their own code at the top of the traceback (VerboseTB will first
819 their own code at the top of the traceback (VerboseTB will first
821 remove that frame before printing the traceback info)."""
820 remove that frame before printing the traceback info)."""
822 TBTools.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
821 TBTools.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
823 ostream=ostream)
822 ostream=ostream)
824 self.tb_offset = tb_offset
823 self.tb_offset = tb_offset
825 self.long_header = long_header
824 self.long_header = long_header
826 self.include_vars = include_vars
825 self.include_vars = include_vars
827 # By default we use linecache.checkcache, but the user can provide a
826 # By default we use linecache.checkcache, but the user can provide a
828 # different check_cache implementation. This is used by the IPython
827 # different check_cache implementation. This is used by the IPython
829 # kernel to provide tracebacks for interactive code that is cached,
828 # kernel to provide tracebacks for interactive code that is cached,
830 # by a compiler instance that flushes the linecache but preserves its
829 # by a compiler instance that flushes the linecache but preserves its
831 # own code cache.
830 # own code cache.
832 if check_cache is None:
831 if check_cache is None:
833 check_cache = linecache.checkcache
832 check_cache = linecache.checkcache
834 self.check_cache = check_cache
833 self.check_cache = check_cache
835
834
836 self.debugger_cls = debugger_cls or debugger.Pdb
835 self.debugger_cls = debugger_cls or debugger.Pdb
837
836
838 def format_records(self, records, last_unique, recursion_repeat):
837 def format_records(self, records, last_unique, recursion_repeat):
839 """Format the stack frames of the traceback"""
838 """Format the stack frames of the traceback"""
840 frames = []
839 frames = []
841 for r in records[:last_unique+recursion_repeat+1]:
840 for r in records[:last_unique+recursion_repeat+1]:
842 #print '*** record:',file,lnum,func,lines,index # dbg
841 #print '*** record:',file,lnum,func,lines,index # dbg
843 frames.append(self.format_record(*r))
842 frames.append(self.format_record(*r))
844
843
845 if recursion_repeat:
844 if recursion_repeat:
846 frames.append('... last %d frames repeated, from the frame below ...\n' % recursion_repeat)
845 frames.append('... last %d frames repeated, from the frame below ...\n' % recursion_repeat)
847 frames.append(self.format_record(*records[last_unique+recursion_repeat+1]))
846 frames.append(self.format_record(*records[last_unique+recursion_repeat+1]))
848
847
849 return frames
848 return frames
850
849
851 def format_record(self, frame, file, lnum, func, lines, index):
850 def format_record(self, frame, file, lnum, func, lines, index):
852 """Format a single stack frame"""
851 """Format a single stack frame"""
853 Colors = self.Colors # just a shorthand + quicker name lookup
852 Colors = self.Colors # just a shorthand + quicker name lookup
854 ColorsNormal = Colors.Normal # used a lot
853 ColorsNormal = Colors.Normal # used a lot
855 col_scheme = self.color_scheme_table.active_scheme_name
854 col_scheme = self.color_scheme_table.active_scheme_name
856 indent = ' ' * INDENT_SIZE
855 indent = ' ' * INDENT_SIZE
857 em_normal = '%s\n%s%s' % (Colors.valEm, indent, ColorsNormal)
856 em_normal = '%s\n%s%s' % (Colors.valEm, indent, ColorsNormal)
858 undefined = '%sundefined%s' % (Colors.em, ColorsNormal)
857 undefined = '%sundefined%s' % (Colors.em, ColorsNormal)
859 tpl_link = '%s%%s%s' % (Colors.filenameEm, ColorsNormal)
858 tpl_link = '%s%%s%s' % (Colors.filenameEm, ColorsNormal)
860 tpl_call = 'in %s%%s%s%%s%s' % (Colors.vName, Colors.valEm,
859 tpl_call = 'in %s%%s%s%%s%s' % (Colors.vName, Colors.valEm,
861 ColorsNormal)
860 ColorsNormal)
862 tpl_call_fail = 'in %s%%s%s(***failed resolving arguments***)%s' % \
861 tpl_call_fail = 'in %s%%s%s(***failed resolving arguments***)%s' % \
863 (Colors.vName, Colors.valEm, ColorsNormal)
862 (Colors.vName, Colors.valEm, ColorsNormal)
864 tpl_local_var = '%s%%s%s' % (Colors.vName, ColorsNormal)
863 tpl_local_var = '%s%%s%s' % (Colors.vName, ColorsNormal)
865 tpl_global_var = '%sglobal%s %s%%s%s' % (Colors.em, ColorsNormal,
864 tpl_global_var = '%sglobal%s %s%%s%s' % (Colors.em, ColorsNormal,
866 Colors.vName, ColorsNormal)
865 Colors.vName, ColorsNormal)
867 tpl_name_val = '%%s %s= %%s%s' % (Colors.valEm, ColorsNormal)
866 tpl_name_val = '%%s %s= %%s%s' % (Colors.valEm, ColorsNormal)
868
867
869 tpl_line = '%s%%s%s %%s' % (Colors.lineno, ColorsNormal)
868 tpl_line = '%s%%s%s %%s' % (Colors.lineno, ColorsNormal)
870 tpl_line_em = '%s%%s%s %%s%s' % (Colors.linenoEm, Colors.line,
869 tpl_line_em = '%s%%s%s %%s%s' % (Colors.linenoEm, Colors.line,
871 ColorsNormal)
870 ColorsNormal)
872
871
873 abspath = os.path.abspath
872 abspath = os.path.abspath
874
873
875
874
876 if not file:
875 if not file:
877 file = '?'
876 file = '?'
878 elif file.startswith(str("<")) and file.endswith(str(">")):
877 elif file.startswith(str("<")) and file.endswith(str(">")):
879 # Not a real filename, no problem...
878 # Not a real filename, no problem...
880 pass
879 pass
881 elif not os.path.isabs(file):
880 elif not os.path.isabs(file):
882 # Try to make the filename absolute by trying all
881 # Try to make the filename absolute by trying all
883 # sys.path entries (which is also what linecache does)
882 # sys.path entries (which is also what linecache does)
884 for dirname in sys.path:
883 for dirname in sys.path:
885 try:
884 try:
886 fullname = os.path.join(dirname, file)
885 fullname = os.path.join(dirname, file)
887 if os.path.isfile(fullname):
886 if os.path.isfile(fullname):
888 file = os.path.abspath(fullname)
887 file = os.path.abspath(fullname)
889 break
888 break
890 except Exception:
889 except Exception:
891 # Just in case that sys.path contains very
890 # Just in case that sys.path contains very
892 # strange entries...
891 # strange entries...
893 pass
892 pass
894
893
895 file = py3compat.cast_unicode(file, util_path.fs_encoding)
894 file = py3compat.cast_unicode(file, util_path.fs_encoding)
896 link = tpl_link % file
895 link = tpl_link % file
897 args, varargs, varkw, locals = fixed_getargvalues(frame)
896 args, varargs, varkw, locals = fixed_getargvalues(frame)
898
897
899 if func == '?':
898 if func == '?':
900 call = ''
899 call = ''
901 else:
900 else:
902 # Decide whether to include variable details or not
901 # Decide whether to include variable details or not
903 var_repr = self.include_vars and eqrepr or nullrepr
902 var_repr = self.include_vars and eqrepr or nullrepr
904 try:
903 try:
905 call = tpl_call % (func, inspect.formatargvalues(args,
904 call = tpl_call % (func, inspect.formatargvalues(args,
906 varargs, varkw,
905 varargs, varkw,
907 locals, formatvalue=var_repr))
906 locals, formatvalue=var_repr))
908 except KeyError:
907 except KeyError:
909 # This happens in situations like errors inside generator
908 # This happens in situations like errors inside generator
910 # expressions, where local variables are listed in the
909 # expressions, where local variables are listed in the
911 # line, but can't be extracted from the frame. I'm not
910 # line, but can't be extracted from the frame. I'm not
912 # 100% sure this isn't actually a bug in inspect itself,
911 # 100% sure this isn't actually a bug in inspect itself,
913 # but since there's no info for us to compute with, the
912 # but since there's no info for us to compute with, the
914 # best we can do is report the failure and move on. Here
913 # best we can do is report the failure and move on. Here
915 # we must *not* call any traceback construction again,
914 # we must *not* call any traceback construction again,
916 # because that would mess up use of %debug later on. So we
915 # because that would mess up use of %debug later on. So we
917 # simply report the failure and move on. The only
916 # simply report the failure and move on. The only
918 # limitation will be that this frame won't have locals
917 # limitation will be that this frame won't have locals
919 # listed in the call signature. Quite subtle problem...
918 # listed in the call signature. Quite subtle problem...
920 # I can't think of a good way to validate this in a unit
919 # I can't think of a good way to validate this in a unit
921 # test, but running a script consisting of:
920 # test, but running a script consisting of:
922 # dict( (k,v.strip()) for (k,v) in range(10) )
921 # dict( (k,v.strip()) for (k,v) in range(10) )
923 # will illustrate the error, if this exception catch is
922 # will illustrate the error, if this exception catch is
924 # disabled.
923 # disabled.
925 call = tpl_call_fail % func
924 call = tpl_call_fail % func
926
925
927 # Don't attempt to tokenize binary files.
926 # Don't attempt to tokenize binary files.
928 if file.endswith(('.so', '.pyd', '.dll')):
927 if file.endswith(('.so', '.pyd', '.dll')):
929 return '%s %s\n' % (link, call)
928 return '%s %s\n' % (link, call)
930
929
931 elif file.endswith(('.pyc', '.pyo')):
930 elif file.endswith(('.pyc', '.pyo')):
932 # Look up the corresponding source file.
931 # Look up the corresponding source file.
933 try:
932 try:
934 file = openpy.source_from_cache(file)
933 file = openpy.source_from_cache(file)
935 except ValueError:
934 except ValueError:
936 # Failed to get the source file for some reason
935 # Failed to get the source file for some reason
937 # E.g. https://github.com/ipython/ipython/issues/9486
936 # E.g. https://github.com/ipython/ipython/issues/9486
938 return '%s %s\n' % (link, call)
937 return '%s %s\n' % (link, call)
939
938
940 def linereader(file=file, lnum=[lnum], getline=ulinecache.getline):
939 def linereader(file=file, lnum=[lnum], getline=ulinecache.getline):
941 line = getline(file, lnum[0])
940 line = getline(file, lnum[0])
942 lnum[0] += 1
941 lnum[0] += 1
943 return line
942 return line
944
943
945 # Build the list of names on this line of code where the exception
944 # Build the list of names on this line of code where the exception
946 # occurred.
945 # occurred.
947 try:
946 try:
948 names = []
947 names = []
949 name_cont = False
948 name_cont = False
950
949
951 for token_type, token, start, end, line in generate_tokens(linereader):
950 for token_type, token, start, end, line in generate_tokens(linereader):
952 # build composite names
951 # build composite names
953 if token_type == tokenize.NAME and token not in keyword.kwlist:
952 if token_type == tokenize.NAME and token not in keyword.kwlist:
954 if name_cont:
953 if name_cont:
955 # Continuation of a dotted name
954 # Continuation of a dotted name
956 try:
955 try:
957 names[-1].append(token)
956 names[-1].append(token)
958 except IndexError:
957 except IndexError:
959 names.append([token])
958 names.append([token])
960 name_cont = False
959 name_cont = False
961 else:
960 else:
962 # Regular new names. We append everything, the caller
961 # Regular new names. We append everything, the caller
963 # will be responsible for pruning the list later. It's
962 # will be responsible for pruning the list later. It's
964 # very tricky to try to prune as we go, b/c composite
963 # very tricky to try to prune as we go, b/c composite
965 # names can fool us. The pruning at the end is easy
964 # names can fool us. The pruning at the end is easy
966 # to do (or the caller can print a list with repeated
965 # to do (or the caller can print a list with repeated
967 # names if so desired.
966 # names if so desired.
968 names.append([token])
967 names.append([token])
969 elif token == '.':
968 elif token == '.':
970 name_cont = True
969 name_cont = True
971 elif token_type == tokenize.NEWLINE:
970 elif token_type == tokenize.NEWLINE:
972 break
971 break
973
972
974 except (IndexError, UnicodeDecodeError, SyntaxError):
973 except (IndexError, UnicodeDecodeError, SyntaxError):
975 # signals exit of tokenizer
974 # signals exit of tokenizer
976 # SyntaxError can occur if the file is not actually Python
975 # SyntaxError can occur if the file is not actually Python
977 # - see gh-6300
976 # - see gh-6300
978 pass
977 pass
979 except tokenize.TokenError as msg:
978 except tokenize.TokenError as msg:
980 _m = ("An unexpected error occurred while tokenizing input\n"
979 _m = ("An unexpected error occurred while tokenizing input\n"
981 "The following traceback may be corrupted or invalid\n"
980 "The following traceback may be corrupted or invalid\n"
982 "The error message is: %s\n" % msg)
981 "The error message is: %s\n" % msg)
983 error(_m)
982 error(_m)
984
983
985 # Join composite names (e.g. "dict.fromkeys")
984 # Join composite names (e.g. "dict.fromkeys")
986 names = ['.'.join(n) for n in names]
985 names = ['.'.join(n) for n in names]
987 # prune names list of duplicates, but keep the right order
986 # prune names list of duplicates, but keep the right order
988 unique_names = uniq_stable(names)
987 unique_names = uniq_stable(names)
989
988
990 # Start loop over vars
989 # Start loop over vars
991 lvals = []
990 lvals = []
992 if self.include_vars:
991 if self.include_vars:
993 for name_full in unique_names:
992 for name_full in unique_names:
994 name_base = name_full.split('.', 1)[0]
993 name_base = name_full.split('.', 1)[0]
995 if name_base in frame.f_code.co_varnames:
994 if name_base in frame.f_code.co_varnames:
996 if name_base in locals:
995 if name_base in locals:
997 try:
996 try:
998 value = repr(eval(name_full, locals))
997 value = repr(eval(name_full, locals))
999 except:
998 except:
1000 value = undefined
999 value = undefined
1001 else:
1000 else:
1002 value = undefined
1001 value = undefined
1003 name = tpl_local_var % name_full
1002 name = tpl_local_var % name_full
1004 else:
1003 else:
1005 if name_base in frame.f_globals:
1004 if name_base in frame.f_globals:
1006 try:
1005 try:
1007 value = repr(eval(name_full, frame.f_globals))
1006 value = repr(eval(name_full, frame.f_globals))
1008 except:
1007 except:
1009 value = undefined
1008 value = undefined
1010 else:
1009 else:
1011 value = undefined
1010 value = undefined
1012 name = tpl_global_var % name_full
1011 name = tpl_global_var % name_full
1013 lvals.append(tpl_name_val % (name, value))
1012 lvals.append(tpl_name_val % (name, value))
1014 if lvals:
1013 if lvals:
1015 lvals = '%s%s' % (indent, em_normal.join(lvals))
1014 lvals = '%s%s' % (indent, em_normal.join(lvals))
1016 else:
1015 else:
1017 lvals = ''
1016 lvals = ''
1018
1017
1019 level = '%s %s\n' % (link, call)
1018 level = '%s %s\n' % (link, call)
1020
1019
1021 if index is None:
1020 if index is None:
1022 return level
1021 return level
1023 else:
1022 else:
1024 return '%s%s' % (level, ''.join(
1023 return '%s%s' % (level, ''.join(
1025 _format_traceback_lines(lnum, index, lines, Colors, lvals,
1024 _format_traceback_lines(lnum, index, lines, Colors, lvals,
1026 col_scheme)))
1025 col_scheme)))
1027
1026
1028 def prepare_chained_exception_message(self, cause):
1027 def prepare_chained_exception_message(self, cause):
1029 direct_cause = "\nThe above exception was the direct cause of the following exception:\n"
1028 direct_cause = "\nThe above exception was the direct cause of the following exception:\n"
1030 exception_during_handling = "\nDuring handling of the above exception, another exception occurred:\n"
1029 exception_during_handling = "\nDuring handling of the above exception, another exception occurred:\n"
1031
1030
1032 if cause:
1031 if cause:
1033 message = [[direct_cause]]
1032 message = [[direct_cause]]
1034 else:
1033 else:
1035 message = [[exception_during_handling]]
1034 message = [[exception_during_handling]]
1036 return message
1035 return message
1037
1036
1038 def prepare_header(self, etype, long_version=False):
1037 def prepare_header(self, etype, long_version=False):
1039 colors = self.Colors # just a shorthand + quicker name lookup
1038 colors = self.Colors # just a shorthand + quicker name lookup
1040 colorsnormal = colors.Normal # used a lot
1039 colorsnormal = colors.Normal # used a lot
1041 exc = '%s%s%s' % (colors.excName, etype, colorsnormal)
1040 exc = '%s%s%s' % (colors.excName, etype, colorsnormal)
1042 width = min(75, get_terminal_size()[0])
1041 width = min(75, get_terminal_size()[0])
1043 if long_version:
1042 if long_version:
1044 # Header with the exception type, python version, and date
1043 # Header with the exception type, python version, and date
1045 pyver = 'Python ' + sys.version.split()[0] + ': ' + sys.executable
1044 pyver = 'Python ' + sys.version.split()[0] + ': ' + sys.executable
1046 date = time.ctime(time.time())
1045 date = time.ctime(time.time())
1047
1046
1048 head = '%s%s%s\n%s%s%s\n%s' % (colors.topline, '-' * width, colorsnormal,
1047 head = '%s%s%s\n%s%s%s\n%s' % (colors.topline, '-' * width, colorsnormal,
1049 exc, ' ' * (width - len(str(etype)) - len(pyver)),
1048 exc, ' ' * (width - len(str(etype)) - len(pyver)),
1050 pyver, date.rjust(width) )
1049 pyver, date.rjust(width) )
1051 head += "\nA problem occurred executing Python code. Here is the sequence of function" \
1050 head += "\nA problem occurred executing Python code. Here is the sequence of function" \
1052 "\ncalls leading up to the error, with the most recent (innermost) call last."
1051 "\ncalls leading up to the error, with the most recent (innermost) call last."
1053 else:
1052 else:
1054 # Simplified header
1053 # Simplified header
1055 head = '%s%s' % (exc, 'Traceback (most recent call last)'. \
1054 head = '%s%s' % (exc, 'Traceback (most recent call last)'. \
1056 rjust(width - len(str(etype))) )
1055 rjust(width - len(str(etype))) )
1057
1056
1058 return head
1057 return head
1059
1058
1060 def format_exception(self, etype, evalue):
1059 def format_exception(self, etype, evalue):
1061 colors = self.Colors # just a shorthand + quicker name lookup
1060 colors = self.Colors # just a shorthand + quicker name lookup
1062 colorsnormal = colors.Normal # used a lot
1061 colorsnormal = colors.Normal # used a lot
1063 indent = ' ' * INDENT_SIZE
1062 indent = ' ' * INDENT_SIZE
1064 # Get (safely) a string form of the exception info
1063 # Get (safely) a string form of the exception info
1065 try:
1064 try:
1066 etype_str, evalue_str = map(str, (etype, evalue))
1065 etype_str, evalue_str = map(str, (etype, evalue))
1067 except:
1066 except:
1068 # User exception is improperly defined.
1067 # User exception is improperly defined.
1069 etype, evalue = str, sys.exc_info()[:2]
1068 etype, evalue = str, sys.exc_info()[:2]
1070 etype_str, evalue_str = map(str, (etype, evalue))
1069 etype_str, evalue_str = map(str, (etype, evalue))
1071 # ... and format it
1070 # ... and format it
1072 exception = ['%s%s%s: %s' % (colors.excName, etype_str,
1071 exception = ['%s%s%s: %s' % (colors.excName, etype_str,
1073 colorsnormal, py3compat.cast_unicode(evalue_str))]
1072 colorsnormal, py3compat.cast_unicode(evalue_str))]
1074
1073
1075 if (not py3compat.PY3) and type(evalue) is types.InstanceType:
1074 if (not py3compat.PY3) and type(evalue) is types.InstanceType:
1076 try:
1075 try:
1077 names = [w for w in dir(evalue) if isinstance(w, py3compat.string_types)]
1076 names = [w for w in dir(evalue) if isinstance(w, py3compat.string_types)]
1078 except:
1077 except:
1079 # Every now and then, an object with funny internals blows up
1078 # Every now and then, an object with funny internals blows up
1080 # when dir() is called on it. We do the best we can to report
1079 # when dir() is called on it. We do the best we can to report
1081 # the problem and continue
1080 # the problem and continue
1082 _m = '%sException reporting error (object with broken dir())%s:'
1081 _m = '%sException reporting error (object with broken dir())%s:'
1083 exception.append(_m % (colors.excName, colorsnormal))
1082 exception.append(_m % (colors.excName, colorsnormal))
1084 etype_str, evalue_str = map(str, sys.exc_info()[:2])
1083 etype_str, evalue_str = map(str, sys.exc_info()[:2])
1085 exception.append('%s%s%s: %s' % (colors.excName, etype_str,
1084 exception.append('%s%s%s: %s' % (colors.excName, etype_str,
1086 colorsnormal, py3compat.cast_unicode(evalue_str)))
1085 colorsnormal, py3compat.cast_unicode(evalue_str)))
1087 names = []
1086 names = []
1088 for name in names:
1087 for name in names:
1089 value = text_repr(getattr(evalue, name))
1088 value = text_repr(getattr(evalue, name))
1090 exception.append('\n%s%s = %s' % (indent, name, value))
1089 exception.append('\n%s%s = %s' % (indent, name, value))
1091
1090
1092 return exception
1091 return exception
1093
1092
1094 def format_exception_as_a_whole(self, etype, evalue, etb, number_of_lines_of_context, tb_offset):
1093 def format_exception_as_a_whole(self, etype, evalue, etb, number_of_lines_of_context, tb_offset):
1095 """Formats the header, traceback and exception message for a single exception.
1094 """Formats the header, traceback and exception message for a single exception.
1096
1095
1097 This may be called multiple times by Python 3 exception chaining
1096 This may be called multiple times by Python 3 exception chaining
1098 (PEP 3134).
1097 (PEP 3134).
1099 """
1098 """
1100 # some locals
1099 # some locals
1101 orig_etype = etype
1100 orig_etype = etype
1102 try:
1101 try:
1103 etype = etype.__name__
1102 etype = etype.__name__
1104 except AttributeError:
1103 except AttributeError:
1105 pass
1104 pass
1106
1105
1107 tb_offset = self.tb_offset if tb_offset is None else tb_offset
1106 tb_offset = self.tb_offset if tb_offset is None else tb_offset
1108 head = self.prepare_header(etype, self.long_header)
1107 head = self.prepare_header(etype, self.long_header)
1109 records = self.get_records(etb, number_of_lines_of_context, tb_offset)
1108 records = self.get_records(etb, number_of_lines_of_context, tb_offset)
1110
1109
1111 if records is None:
1110 if records is None:
1112 return ""
1111 return ""
1113
1112
1114 last_unique, recursion_repeat = find_recursion(orig_etype, evalue, records)
1113 last_unique, recursion_repeat = find_recursion(orig_etype, evalue, records)
1115
1114
1116 frames = self.format_records(records, last_unique, recursion_repeat)
1115 frames = self.format_records(records, last_unique, recursion_repeat)
1117
1116
1118 formatted_exception = self.format_exception(etype, evalue)
1117 formatted_exception = self.format_exception(etype, evalue)
1119 if records:
1118 if records:
1120 filepath, lnum = records[-1][1:3]
1119 filepath, lnum = records[-1][1:3]
1121 filepath = os.path.abspath(filepath)
1120 filepath = os.path.abspath(filepath)
1122 ipinst = get_ipython()
1121 ipinst = get_ipython()
1123 if ipinst is not None:
1122 if ipinst is not None:
1124 ipinst.hooks.synchronize_with_editor(filepath, lnum, 0)
1123 ipinst.hooks.synchronize_with_editor(filepath, lnum, 0)
1125
1124
1126 return [[head] + frames + [''.join(formatted_exception[0])]]
1125 return [[head] + frames + [''.join(formatted_exception[0])]]
1127
1126
1128 def get_records(self, etb, number_of_lines_of_context, tb_offset):
1127 def get_records(self, etb, number_of_lines_of_context, tb_offset):
1129 try:
1128 try:
1130 # Try the default getinnerframes and Alex's: Alex's fixes some
1129 # Try the default getinnerframes and Alex's: Alex's fixes some
1131 # problems, but it generates empty tracebacks for console errors
1130 # problems, but it generates empty tracebacks for console errors
1132 # (5 blanks lines) where none should be returned.
1131 # (5 blanks lines) where none should be returned.
1133 return _fixed_getinnerframes(etb, number_of_lines_of_context, tb_offset)
1132 return _fixed_getinnerframes(etb, number_of_lines_of_context, tb_offset)
1134 except:
1133 except:
1135 # FIXME: I've been getting many crash reports from python 2.3
1134 # FIXME: I've been getting many crash reports from python 2.3
1136 # users, traceable to inspect.py. If I can find a small test-case
1135 # users, traceable to inspect.py. If I can find a small test-case
1137 # to reproduce this, I should either write a better workaround or
1136 # to reproduce this, I should either write a better workaround or
1138 # file a bug report against inspect (if that's the real problem).
1137 # file a bug report against inspect (if that's the real problem).
1139 # So far, I haven't been able to find an isolated example to
1138 # So far, I haven't been able to find an isolated example to
1140 # reproduce the problem.
1139 # reproduce the problem.
1141 inspect_error()
1140 inspect_error()
1142 traceback.print_exc(file=self.ostream)
1141 traceback.print_exc(file=self.ostream)
1143 info('\nUnfortunately, your original traceback can not be constructed.\n')
1142 info('\nUnfortunately, your original traceback can not be constructed.\n')
1144 return None
1143 return None
1145
1144
1146 def get_parts_of_chained_exception(self, evalue):
1145 def get_parts_of_chained_exception(self, evalue):
1147 def get_chained_exception(exception_value):
1146 def get_chained_exception(exception_value):
1148 cause = getattr(exception_value, '__cause__', None)
1147 cause = getattr(exception_value, '__cause__', None)
1149 if cause:
1148 if cause:
1150 return cause
1149 return cause
1151 if getattr(exception_value, '__suppress_context__', False):
1150 if getattr(exception_value, '__suppress_context__', False):
1152 return None
1151 return None
1153 return getattr(exception_value, '__context__', None)
1152 return getattr(exception_value, '__context__', None)
1154
1153
1155 chained_evalue = get_chained_exception(evalue)
1154 chained_evalue = get_chained_exception(evalue)
1156
1155
1157 if chained_evalue:
1156 if chained_evalue:
1158 return chained_evalue.__class__, chained_evalue, chained_evalue.__traceback__
1157 return chained_evalue.__class__, chained_evalue, chained_evalue.__traceback__
1159
1158
1160 def structured_traceback(self, etype, evalue, etb, tb_offset=None,
1159 def structured_traceback(self, etype, evalue, etb, tb_offset=None,
1161 number_of_lines_of_context=5):
1160 number_of_lines_of_context=5):
1162 """Return a nice text document describing the traceback."""
1161 """Return a nice text document describing the traceback."""
1163
1162
1164 formatted_exception = self.format_exception_as_a_whole(etype, evalue, etb, number_of_lines_of_context,
1163 formatted_exception = self.format_exception_as_a_whole(etype, evalue, etb, number_of_lines_of_context,
1165 tb_offset)
1164 tb_offset)
1166
1165
1167 colors = self.Colors # just a shorthand + quicker name lookup
1166 colors = self.Colors # just a shorthand + quicker name lookup
1168 colorsnormal = colors.Normal # used a lot
1167 colorsnormal = colors.Normal # used a lot
1169 head = '%s%s%s' % (colors.topline, '-' * min(75, get_terminal_size()[0]), colorsnormal)
1168 head = '%s%s%s' % (colors.topline, '-' * min(75, get_terminal_size()[0]), colorsnormal)
1170 structured_traceback_parts = [head]
1169 structured_traceback_parts = [head]
1171 if py3compat.PY3:
1170 if py3compat.PY3:
1172 chained_exceptions_tb_offset = 0
1171 chained_exceptions_tb_offset = 0
1173 lines_of_context = 3
1172 lines_of_context = 3
1174 formatted_exceptions = formatted_exception
1173 formatted_exceptions = formatted_exception
1175 exception = self.get_parts_of_chained_exception(evalue)
1174 exception = self.get_parts_of_chained_exception(evalue)
1176 if exception:
1175 if exception:
1177 formatted_exceptions += self.prepare_chained_exception_message(evalue.__cause__)
1176 formatted_exceptions += self.prepare_chained_exception_message(evalue.__cause__)
1178 etype, evalue, etb = exception
1177 etype, evalue, etb = exception
1179 else:
1178 else:
1180 evalue = None
1179 evalue = None
1181 chained_exc_ids = set()
1180 chained_exc_ids = set()
1182 while evalue:
1181 while evalue:
1183 formatted_exceptions += self.format_exception_as_a_whole(etype, evalue, etb, lines_of_context,
1182 formatted_exceptions += self.format_exception_as_a_whole(etype, evalue, etb, lines_of_context,
1184 chained_exceptions_tb_offset)
1183 chained_exceptions_tb_offset)
1185 exception = self.get_parts_of_chained_exception(evalue)
1184 exception = self.get_parts_of_chained_exception(evalue)
1186
1185
1187 if exception and not id(exception[1]) in chained_exc_ids:
1186 if exception and not id(exception[1]) in chained_exc_ids:
1188 chained_exc_ids.add(id(exception[1])) # trace exception to avoid infinite 'cause' loop
1187 chained_exc_ids.add(id(exception[1])) # trace exception to avoid infinite 'cause' loop
1189 formatted_exceptions += self.prepare_chained_exception_message(evalue.__cause__)
1188 formatted_exceptions += self.prepare_chained_exception_message(evalue.__cause__)
1190 etype, evalue, etb = exception
1189 etype, evalue, etb = exception
1191 else:
1190 else:
1192 evalue = None
1191 evalue = None
1193
1192
1194 # we want to see exceptions in a reversed order:
1193 # we want to see exceptions in a reversed order:
1195 # the first exception should be on top
1194 # the first exception should be on top
1196 for formatted_exception in reversed(formatted_exceptions):
1195 for formatted_exception in reversed(formatted_exceptions):
1197 structured_traceback_parts += formatted_exception
1196 structured_traceback_parts += formatted_exception
1198 else:
1197 else:
1199 structured_traceback_parts += formatted_exception[0]
1198 structured_traceback_parts += formatted_exception[0]
1200
1199
1201 return structured_traceback_parts
1200 return structured_traceback_parts
1202
1201
1203 def debugger(self, force=False):
1202 def debugger(self, force=False):
1204 """Call up the pdb debugger if desired, always clean up the tb
1203 """Call up the pdb debugger if desired, always clean up the tb
1205 reference.
1204 reference.
1206
1205
1207 Keywords:
1206 Keywords:
1208
1207
1209 - force(False): by default, this routine checks the instance call_pdb
1208 - force(False): by default, this routine checks the instance call_pdb
1210 flag and does not actually invoke the debugger if the flag is false.
1209 flag and does not actually invoke the debugger if the flag is false.
1211 The 'force' option forces the debugger to activate even if the flag
1210 The 'force' option forces the debugger to activate even if the flag
1212 is false.
1211 is false.
1213
1212
1214 If the call_pdb flag is set, the pdb interactive debugger is
1213 If the call_pdb flag is set, the pdb interactive debugger is
1215 invoked. In all cases, the self.tb reference to the current traceback
1214 invoked. In all cases, the self.tb reference to the current traceback
1216 is deleted to prevent lingering references which hamper memory
1215 is deleted to prevent lingering references which hamper memory
1217 management.
1216 management.
1218
1217
1219 Note that each call to pdb() does an 'import readline', so if your app
1218 Note that each call to pdb() does an 'import readline', so if your app
1220 requires a special setup for the readline completers, you'll have to
1219 requires a special setup for the readline completers, you'll have to
1221 fix that by hand after invoking the exception handler."""
1220 fix that by hand after invoking the exception handler."""
1222
1221
1223 if force or self.call_pdb:
1222 if force or self.call_pdb:
1224 if self.pdb is None:
1223 if self.pdb is None:
1225 self.pdb = self.debugger_cls(
1224 self.pdb = self.debugger_cls(
1226 self.color_scheme_table.active_scheme_name)
1225 self.color_scheme_table.active_scheme_name)
1227 # the system displayhook may have changed, restore the original
1226 # the system displayhook may have changed, restore the original
1228 # for pdb
1227 # for pdb
1229 display_trap = DisplayTrap(hook=sys.__displayhook__)
1228 display_trap = DisplayTrap(hook=sys.__displayhook__)
1230 with display_trap:
1229 with display_trap:
1231 self.pdb.reset()
1230 self.pdb.reset()
1232 # Find the right frame so we don't pop up inside ipython itself
1231 # Find the right frame so we don't pop up inside ipython itself
1233 if hasattr(self, 'tb') and self.tb is not None:
1232 if hasattr(self, 'tb') and self.tb is not None:
1234 etb = self.tb
1233 etb = self.tb
1235 else:
1234 else:
1236 etb = self.tb = sys.last_traceback
1235 etb = self.tb = sys.last_traceback
1237 while self.tb is not None and self.tb.tb_next is not None:
1236 while self.tb is not None and self.tb.tb_next is not None:
1238 self.tb = self.tb.tb_next
1237 self.tb = self.tb.tb_next
1239 if etb and etb.tb_next:
1238 if etb and etb.tb_next:
1240 etb = etb.tb_next
1239 etb = etb.tb_next
1241 self.pdb.botframe = etb.tb_frame
1240 self.pdb.botframe = etb.tb_frame
1242 self.pdb.interaction(self.tb.tb_frame, self.tb)
1241 self.pdb.interaction(self.tb.tb_frame, self.tb)
1243
1242
1244 if hasattr(self, 'tb'):
1243 if hasattr(self, 'tb'):
1245 del self.tb
1244 del self.tb
1246
1245
1247 def handler(self, info=None):
1246 def handler(self, info=None):
1248 (etype, evalue, etb) = info or sys.exc_info()
1247 (etype, evalue, etb) = info or sys.exc_info()
1249 self.tb = etb
1248 self.tb = etb
1250 ostream = self.ostream
1249 ostream = self.ostream
1251 ostream.flush()
1250 ostream.flush()
1252 ostream.write(self.text(etype, evalue, etb))
1251 ostream.write(self.text(etype, evalue, etb))
1253 ostream.write('\n')
1252 ostream.write('\n')
1254 ostream.flush()
1253 ostream.flush()
1255
1254
1256 # Changed so an instance can just be called as VerboseTB_inst() and print
1255 # Changed so an instance can just be called as VerboseTB_inst() and print
1257 # out the right info on its own.
1256 # out the right info on its own.
1258 def __call__(self, etype=None, evalue=None, etb=None):
1257 def __call__(self, etype=None, evalue=None, etb=None):
1259 """This hook can replace sys.excepthook (for Python 2.1 or higher)."""
1258 """This hook can replace sys.excepthook (for Python 2.1 or higher)."""
1260 if etb is None:
1259 if etb is None:
1261 self.handler()
1260 self.handler()
1262 else:
1261 else:
1263 self.handler((etype, evalue, etb))
1262 self.handler((etype, evalue, etb))
1264 try:
1263 try:
1265 self.debugger()
1264 self.debugger()
1266 except KeyboardInterrupt:
1265 except KeyboardInterrupt:
1267 print("\nKeyboardInterrupt")
1266 print("\nKeyboardInterrupt")
1268
1267
1269
1268
1270 #----------------------------------------------------------------------------
1269 #----------------------------------------------------------------------------
1271 class FormattedTB(VerboseTB, ListTB):
1270 class FormattedTB(VerboseTB, ListTB):
1272 """Subclass ListTB but allow calling with a traceback.
1271 """Subclass ListTB but allow calling with a traceback.
1273
1272
1274 It can thus be used as a sys.excepthook for Python > 2.1.
1273 It can thus be used as a sys.excepthook for Python > 2.1.
1275
1274
1276 Also adds 'Context' and 'Verbose' modes, not available in ListTB.
1275 Also adds 'Context' and 'Verbose' modes, not available in ListTB.
1277
1276
1278 Allows a tb_offset to be specified. This is useful for situations where
1277 Allows a tb_offset to be specified. This is useful for situations where
1279 one needs to remove a number of topmost frames from the traceback (such as
1278 one needs to remove a number of topmost frames from the traceback (such as
1280 occurs with python programs that themselves execute other python code,
1279 occurs with python programs that themselves execute other python code,
1281 like Python shells). """
1280 like Python shells). """
1282
1281
1283 def __init__(self, mode='Plain', color_scheme='Linux', call_pdb=False,
1282 def __init__(self, mode='Plain', color_scheme='Linux', call_pdb=False,
1284 ostream=None,
1283 ostream=None,
1285 tb_offset=0, long_header=False, include_vars=False,
1284 tb_offset=0, long_header=False, include_vars=False,
1286 check_cache=None, debugger_cls=None):
1285 check_cache=None, debugger_cls=None):
1287
1286
1288 # NEVER change the order of this list. Put new modes at the end:
1287 # NEVER change the order of this list. Put new modes at the end:
1289 self.valid_modes = ['Plain', 'Context', 'Verbose']
1288 self.valid_modes = ['Plain', 'Context', 'Verbose']
1290 self.verbose_modes = self.valid_modes[1:3]
1289 self.verbose_modes = self.valid_modes[1:3]
1291
1290
1292 VerboseTB.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
1291 VerboseTB.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
1293 ostream=ostream, tb_offset=tb_offset,
1292 ostream=ostream, tb_offset=tb_offset,
1294 long_header=long_header, include_vars=include_vars,
1293 long_header=long_header, include_vars=include_vars,
1295 check_cache=check_cache, debugger_cls=debugger_cls)
1294 check_cache=check_cache, debugger_cls=debugger_cls)
1296
1295
1297 # Different types of tracebacks are joined with different separators to
1296 # Different types of tracebacks are joined with different separators to
1298 # form a single string. They are taken from this dict
1297 # form a single string. They are taken from this dict
1299 self._join_chars = dict(Plain='', Context='\n', Verbose='\n')
1298 self._join_chars = dict(Plain='', Context='\n', Verbose='\n')
1300 # set_mode also sets the tb_join_char attribute
1299 # set_mode also sets the tb_join_char attribute
1301 self.set_mode(mode)
1300 self.set_mode(mode)
1302
1301
1303 def _extract_tb(self, tb):
1302 def _extract_tb(self, tb):
1304 if tb:
1303 if tb:
1305 return traceback.extract_tb(tb)
1304 return traceback.extract_tb(tb)
1306 else:
1305 else:
1307 return None
1306 return None
1308
1307
1309 def structured_traceback(self, etype, value, tb, tb_offset=None, number_of_lines_of_context=5):
1308 def structured_traceback(self, etype, value, tb, tb_offset=None, number_of_lines_of_context=5):
1310 tb_offset = self.tb_offset if tb_offset is None else tb_offset
1309 tb_offset = self.tb_offset if tb_offset is None else tb_offset
1311 mode = self.mode
1310 mode = self.mode
1312 if mode in self.verbose_modes:
1311 if mode in self.verbose_modes:
1313 # Verbose modes need a full traceback
1312 # Verbose modes need a full traceback
1314 return VerboseTB.structured_traceback(
1313 return VerboseTB.structured_traceback(
1315 self, etype, value, tb, tb_offset, number_of_lines_of_context
1314 self, etype, value, tb, tb_offset, number_of_lines_of_context
1316 )
1315 )
1317 else:
1316 else:
1318 # We must check the source cache because otherwise we can print
1317 # We must check the source cache because otherwise we can print
1319 # out-of-date source code.
1318 # out-of-date source code.
1320 self.check_cache()
1319 self.check_cache()
1321 # Now we can extract and format the exception
1320 # Now we can extract and format the exception
1322 elist = self._extract_tb(tb)
1321 elist = self._extract_tb(tb)
1323 return ListTB.structured_traceback(
1322 return ListTB.structured_traceback(
1324 self, etype, value, elist, tb_offset, number_of_lines_of_context
1323 self, etype, value, elist, tb_offset, number_of_lines_of_context
1325 )
1324 )
1326
1325
1327 def stb2text(self, stb):
1326 def stb2text(self, stb):
1328 """Convert a structured traceback (a list) to a string."""
1327 """Convert a structured traceback (a list) to a string."""
1329 return self.tb_join_char.join(stb)
1328 return self.tb_join_char.join(stb)
1330
1329
1331
1330
1332 def set_mode(self, mode=None):
1331 def set_mode(self, mode=None):
1333 """Switch to the desired mode.
1332 """Switch to the desired mode.
1334
1333
1335 If mode is not specified, cycles through the available modes."""
1334 If mode is not specified, cycles through the available modes."""
1336
1335
1337 if not mode:
1336 if not mode:
1338 new_idx = (self.valid_modes.index(self.mode) + 1 ) % \
1337 new_idx = (self.valid_modes.index(self.mode) + 1 ) % \
1339 len(self.valid_modes)
1338 len(self.valid_modes)
1340 self.mode = self.valid_modes[new_idx]
1339 self.mode = self.valid_modes[new_idx]
1341 elif mode not in self.valid_modes:
1340 elif mode not in self.valid_modes:
1342 raise ValueError('Unrecognized mode in FormattedTB: <' + mode + '>\n'
1341 raise ValueError('Unrecognized mode in FormattedTB: <' + mode + '>\n'
1343 'Valid modes: ' + str(self.valid_modes))
1342 'Valid modes: ' + str(self.valid_modes))
1344 else:
1343 else:
1345 self.mode = mode
1344 self.mode = mode
1346 # include variable details only in 'Verbose' mode
1345 # include variable details only in 'Verbose' mode
1347 self.include_vars = (self.mode == self.valid_modes[2])
1346 self.include_vars = (self.mode == self.valid_modes[2])
1348 # Set the join character for generating text tracebacks
1347 # Set the join character for generating text tracebacks
1349 self.tb_join_char = self._join_chars[self.mode]
1348 self.tb_join_char = self._join_chars[self.mode]
1350
1349
1351 # some convenient shortcuts
1350 # some convenient shortcuts
1352 def plain(self):
1351 def plain(self):
1353 self.set_mode(self.valid_modes[0])
1352 self.set_mode(self.valid_modes[0])
1354
1353
1355 def context(self):
1354 def context(self):
1356 self.set_mode(self.valid_modes[1])
1355 self.set_mode(self.valid_modes[1])
1357
1356
1358 def verbose(self):
1357 def verbose(self):
1359 self.set_mode(self.valid_modes[2])
1358 self.set_mode(self.valid_modes[2])
1360
1359
1361
1360
1362 #----------------------------------------------------------------------------
1361 #----------------------------------------------------------------------------
1363 class AutoFormattedTB(FormattedTB):
1362 class AutoFormattedTB(FormattedTB):
1364 """A traceback printer which can be called on the fly.
1363 """A traceback printer which can be called on the fly.
1365
1364
1366 It will find out about exceptions by itself.
1365 It will find out about exceptions by itself.
1367
1366
1368 A brief example::
1367 A brief example::
1369
1368
1370 AutoTB = AutoFormattedTB(mode = 'Verbose',color_scheme='Linux')
1369 AutoTB = AutoFormattedTB(mode = 'Verbose',color_scheme='Linux')
1371 try:
1370 try:
1372 ...
1371 ...
1373 except:
1372 except:
1374 AutoTB() # or AutoTB(out=logfile) where logfile is an open file object
1373 AutoTB() # or AutoTB(out=logfile) where logfile is an open file object
1375 """
1374 """
1376
1375
1377 def __call__(self, etype=None, evalue=None, etb=None,
1376 def __call__(self, etype=None, evalue=None, etb=None,
1378 out=None, tb_offset=None):
1377 out=None, tb_offset=None):
1379 """Print out a formatted exception traceback.
1378 """Print out a formatted exception traceback.
1380
1379
1381 Optional arguments:
1380 Optional arguments:
1382 - out: an open file-like object to direct output to.
1381 - out: an open file-like object to direct output to.
1383
1382
1384 - tb_offset: the number of frames to skip over in the stack, on a
1383 - tb_offset: the number of frames to skip over in the stack, on a
1385 per-call basis (this overrides temporarily the instance's tb_offset
1384 per-call basis (this overrides temporarily the instance's tb_offset
1386 given at initialization time. """
1385 given at initialization time. """
1387
1386
1388 if out is None:
1387 if out is None:
1389 out = self.ostream
1388 out = self.ostream
1390 out.flush()
1389 out.flush()
1391 out.write(self.text(etype, evalue, etb, tb_offset))
1390 out.write(self.text(etype, evalue, etb, tb_offset))
1392 out.write('\n')
1391 out.write('\n')
1393 out.flush()
1392 out.flush()
1394 # FIXME: we should remove the auto pdb behavior from here and leave
1393 # FIXME: we should remove the auto pdb behavior from here and leave
1395 # that to the clients.
1394 # that to the clients.
1396 try:
1395 try:
1397 self.debugger()
1396 self.debugger()
1398 except KeyboardInterrupt:
1397 except KeyboardInterrupt:
1399 print("\nKeyboardInterrupt")
1398 print("\nKeyboardInterrupt")
1400
1399
1401 def structured_traceback(self, etype=None, value=None, tb=None,
1400 def structured_traceback(self, etype=None, value=None, tb=None,
1402 tb_offset=None, number_of_lines_of_context=5):
1401 tb_offset=None, number_of_lines_of_context=5):
1403 if etype is None:
1402 if etype is None:
1404 etype, value, tb = sys.exc_info()
1403 etype, value, tb = sys.exc_info()
1405 self.tb = tb
1404 self.tb = tb
1406 return FormattedTB.structured_traceback(
1405 return FormattedTB.structured_traceback(
1407 self, etype, value, tb, tb_offset, number_of_lines_of_context)
1406 self, etype, value, tb, tb_offset, number_of_lines_of_context)
1408
1407
1409
1408
1410 #---------------------------------------------------------------------------
1409 #---------------------------------------------------------------------------
1411
1410
1412 # A simple class to preserve Nathan's original functionality.
1411 # A simple class to preserve Nathan's original functionality.
1413 class ColorTB(FormattedTB):
1412 class ColorTB(FormattedTB):
1414 """Shorthand to initialize a FormattedTB in Linux colors mode."""
1413 """Shorthand to initialize a FormattedTB in Linux colors mode."""
1415
1414
1416 def __init__(self, color_scheme='Linux', call_pdb=0, **kwargs):
1415 def __init__(self, color_scheme='Linux', call_pdb=0, **kwargs):
1417 FormattedTB.__init__(self, color_scheme=color_scheme,
1416 FormattedTB.__init__(self, color_scheme=color_scheme,
1418 call_pdb=call_pdb, **kwargs)
1417 call_pdb=call_pdb, **kwargs)
1419
1418
1420
1419
1421 class SyntaxTB(ListTB):
1420 class SyntaxTB(ListTB):
1422 """Extension which holds some state: the last exception value"""
1421 """Extension which holds some state: the last exception value"""
1423
1422
1424 def __init__(self, color_scheme='NoColor'):
1423 def __init__(self, color_scheme='NoColor'):
1425 ListTB.__init__(self, color_scheme)
1424 ListTB.__init__(self, color_scheme)
1426 self.last_syntax_error = None
1425 self.last_syntax_error = None
1427
1426
1428 def __call__(self, etype, value, elist):
1427 def __call__(self, etype, value, elist):
1429 self.last_syntax_error = value
1428 self.last_syntax_error = value
1430
1429
1431 ListTB.__call__(self, etype, value, elist)
1430 ListTB.__call__(self, etype, value, elist)
1432
1431
1433 def structured_traceback(self, etype, value, elist, tb_offset=None,
1432 def structured_traceback(self, etype, value, elist, tb_offset=None,
1434 context=5):
1433 context=5):
1435 # If the source file has been edited, the line in the syntax error can
1434 # If the source file has been edited, the line in the syntax error can
1436 # be wrong (retrieved from an outdated cache). This replaces it with
1435 # be wrong (retrieved from an outdated cache). This replaces it with
1437 # the current value.
1436 # the current value.
1438 if isinstance(value, SyntaxError) \
1437 if isinstance(value, SyntaxError) \
1439 and isinstance(value.filename, py3compat.string_types) \
1438 and isinstance(value.filename, py3compat.string_types) \
1440 and isinstance(value.lineno, int):
1439 and isinstance(value.lineno, int):
1441 linecache.checkcache(value.filename)
1440 linecache.checkcache(value.filename)
1442 newtext = ulinecache.getline(value.filename, value.lineno)
1441 newtext = ulinecache.getline(value.filename, value.lineno)
1443 if newtext:
1442 if newtext:
1444 value.text = newtext
1443 value.text = newtext
1445 self.last_syntax_error = value
1444 self.last_syntax_error = value
1446 return super(SyntaxTB, self).structured_traceback(etype, value, elist,
1445 return super(SyntaxTB, self).structured_traceback(etype, value, elist,
1447 tb_offset=tb_offset, context=context)
1446 tb_offset=tb_offset, context=context)
1448
1447
1449 def clear_err_state(self):
1448 def clear_err_state(self):
1450 """Return the current error state and clear it"""
1449 """Return the current error state and clear it"""
1451 e = self.last_syntax_error
1450 e = self.last_syntax_error
1452 self.last_syntax_error = None
1451 self.last_syntax_error = None
1453 return e
1452 return e
1454
1453
1455 def stb2text(self, stb):
1454 def stb2text(self, stb):
1456 """Convert a structured traceback (a list) to a string."""
1455 """Convert a structured traceback (a list) to a string."""
1457 return ''.join(stb)
1456 return ''.join(stb)
1458
1457
1459
1458
1460 # some internal-use functions
1459 # some internal-use functions
1461 def text_repr(value):
1460 def text_repr(value):
1462 """Hopefully pretty robust repr equivalent."""
1461 """Hopefully pretty robust repr equivalent."""
1463 # this is pretty horrible but should always return *something*
1462 # this is pretty horrible but should always return *something*
1464 try:
1463 try:
1465 return pydoc.text.repr(value)
1464 return pydoc.text.repr(value)
1466 except KeyboardInterrupt:
1465 except KeyboardInterrupt:
1467 raise
1466 raise
1468 except:
1467 except:
1469 try:
1468 try:
1470 return repr(value)
1469 return repr(value)
1471 except KeyboardInterrupt:
1470 except KeyboardInterrupt:
1472 raise
1471 raise
1473 except:
1472 except:
1474 try:
1473 try:
1475 # all still in an except block so we catch
1474 # all still in an except block so we catch
1476 # getattr raising
1475 # getattr raising
1477 name = getattr(value, '__name__', None)
1476 name = getattr(value, '__name__', None)
1478 if name:
1477 if name:
1479 # ick, recursion
1478 # ick, recursion
1480 return text_repr(name)
1479 return text_repr(name)
1481 klass = getattr(value, '__class__', None)
1480 klass = getattr(value, '__class__', None)
1482 if klass:
1481 if klass:
1483 return '%s instance' % text_repr(klass)
1482 return '%s instance' % text_repr(klass)
1484 except KeyboardInterrupt:
1483 except KeyboardInterrupt:
1485 raise
1484 raise
1486 except:
1485 except:
1487 return 'UNRECOVERABLE REPR FAILURE'
1486 return 'UNRECOVERABLE REPR FAILURE'
1488
1487
1489
1488
1490 def eqrepr(value, repr=text_repr):
1489 def eqrepr(value, repr=text_repr):
1491 return '=%s' % repr(value)
1490 return '=%s' % repr(value)
1492
1491
1493
1492
1494 def nullrepr(value, repr=text_repr):
1493 def nullrepr(value, repr=text_repr):
1495 return ''
1494 return ''
@@ -1,325 +1,322 b''
1 # encoding: utf-8
1 # encoding: utf-8
2 """
2 """
3 An embedded IPython shell.
3 An embedded IPython shell.
4 """
4 """
5 # Copyright (c) IPython Development Team.
5 # Copyright (c) IPython Development Team.
6 # Distributed under the terms of the Modified BSD License.
6 # Distributed under the terms of the Modified BSD License.
7
7
8 from __future__ import with_statement
8 from __future__ import with_statement
9 from __future__ import print_function
9 from __future__ import print_function
10
10
11 import sys
11 import sys
12 import warnings
12 import warnings
13
13
14 from IPython.core import ultratb, compilerop
14 from IPython.core import ultratb, compilerop
15 from IPython.core.magic import Magics, magics_class, line_magic
15 from IPython.core.magic import Magics, magics_class, line_magic
16 from IPython.core.interactiveshell import DummyMod, InteractiveShell
16 from IPython.core.interactiveshell import DummyMod, InteractiveShell
17 from IPython.terminal.interactiveshell import TerminalInteractiveShell
17 from IPython.terminal.interactiveshell import TerminalInteractiveShell
18 from IPython.terminal.ipapp import load_default_config
18 from IPython.terminal.ipapp import load_default_config
19
19
20 from traitlets import Bool, CBool, Unicode
20 from traitlets import Bool, CBool, Unicode
21 from IPython.utils.io import ask_yes_no
21 from IPython.utils.io import ask_yes_no
22
22
23 class KillEmbeded(Exception):pass
23 class KillEmbeded(Exception):pass
24
24
25 # This is an additional magic that is exposed in embedded shells.
25 # This is an additional magic that is exposed in embedded shells.
26 @magics_class
26 @magics_class
27 class EmbeddedMagics(Magics):
27 class EmbeddedMagics(Magics):
28
28
29 @line_magic
29 @line_magic
30 def kill_embedded(self, parameter_s=''):
30 def kill_embedded(self, parameter_s=''):
31 """%kill_embedded : deactivate for good the current embedded IPython.
31 """%kill_embedded : deactivate for good the current embedded IPython.
32
32
33 This function (after asking for confirmation) sets an internal flag so
33 This function (after asking for confirmation) sets an internal flag so
34 that an embedded IPython will never activate again. This is useful to
34 that an embedded IPython will never activate again. This is useful to
35 permanently disable a shell that is being called inside a loop: once
35 permanently disable a shell that is being called inside a loop: once
36 you've figured out what you needed from it, you may then kill it and
36 you've figured out what you needed from it, you may then kill it and
37 the program will then continue to run without the interactive shell
37 the program will then continue to run without the interactive shell
38 interfering again.
38 interfering again.
39 """
39 """
40
40
41 kill = ask_yes_no("Are you sure you want to kill this embedded instance? [y/N] ",'n')
41 kill = ask_yes_no("Are you sure you want to kill this embedded instance? [y/N] ",'n')
42 if kill:
42 if kill:
43 self.shell.embedded_active = False
43 self.shell.embedded_active = False
44 print ("This embedded IPython will not reactivate anymore "
44 print ("This embedded IPython will not reactivate anymore "
45 "once you exit.")
45 "once you exit.")
46
46
47
47
48 @line_magic
48 @line_magic
49 def exit_raise(self, parameter_s=''):
49 def exit_raise(self, parameter_s=''):
50 """%exit_raise Make the current embedded kernel exit and raise and exception.
50 """%exit_raise Make the current embedded kernel exit and raise and exception.
51
51
52 This function sets an internal flag so that an embedded IPython will
52 This function sets an internal flag so that an embedded IPython will
53 raise a `IPython.terminal.embed.KillEmbeded` Exception on exit, and then exit the current I. This is
53 raise a `IPython.terminal.embed.KillEmbeded` Exception on exit, and then exit the current I. This is
54 useful to permanently exit a loop that create IPython embed instance.
54 useful to permanently exit a loop that create IPython embed instance.
55 """
55 """
56
56
57 self.shell.should_raise = True
57 self.shell.should_raise = True
58 self.shell.ask_exit()
58 self.shell.ask_exit()
59
59
60
60
61
61
62 class InteractiveShellEmbed(TerminalInteractiveShell):
62 class InteractiveShellEmbed(TerminalInteractiveShell):
63
63
64 dummy_mode = Bool(False)
64 dummy_mode = Bool(False)
65 exit_msg = Unicode('')
65 exit_msg = Unicode('')
66 embedded = CBool(True)
66 embedded = CBool(True)
67 should_raise = CBool(False)
67 should_raise = CBool(False)
68 # Like the base class display_banner is not configurable, but here it
68 # Like the base class display_banner is not configurable, but here it
69 # is True by default.
69 # is True by default.
70 display_banner = CBool(True)
70 display_banner = CBool(True)
71 exit_msg = Unicode()
71 exit_msg = Unicode()
72
72
73 _inactive_locations = set()
73 _inactive_locations = set()
74
74
75 @property
75 @property
76 def embedded_active(self):
76 def embedded_active(self):
77 return self._call_location_id not in InteractiveShellEmbed._inactive_locations
77 return self._call_location_id not in InteractiveShellEmbed._inactive_locations
78
78
79 @embedded_active.setter
79 @embedded_active.setter
80 def embedded_active(self, value):
80 def embedded_active(self, value):
81 if value :
81 if value :
82 if self._call_location_id in InteractiveShellEmbed._inactive_locations:
82 if self._call_location_id in InteractiveShellEmbed._inactive_locations:
83 InteractiveShellEmbed._inactive_locations.remove(self._call_location_id)
83 InteractiveShellEmbed._inactive_locations.remove(self._call_location_id)
84 else:
84 else:
85 InteractiveShellEmbed._inactive_locations.add(self._call_location_id)
85 InteractiveShellEmbed._inactive_locations.add(self._call_location_id)
86
86
87 def __init__(self, **kw):
87 def __init__(self, **kw):
88
88
89
89
90 if kw.get('user_global_ns', None) is not None:
90 if kw.get('user_global_ns', None) is not None:
91 raise DeprecationWarning("Key word argument `user_global_ns` has been replaced by `user_module` since IPython 4.0.")
91 raise DeprecationWarning("Key word argument `user_global_ns` has been replaced by `user_module` since IPython 4.0.")
92
92
93 self._call_location_id = kw.pop('_call_location_id', None)
93 self._call_location_id = kw.pop('_call_location_id', None)
94
94
95 super(InteractiveShellEmbed,self).__init__(**kw)
95 super(InteractiveShellEmbed,self).__init__(**kw)
96
96
97 if not self._call_location_id:
97 if not self._call_location_id:
98 frame = sys._getframe(1)
98 frame = sys._getframe(1)
99 self._call_location_id = '%s:%s' % (frame.f_code.co_filename, frame.f_lineno)
99 self._call_location_id = '%s:%s' % (frame.f_code.co_filename, frame.f_lineno)
100 # don't use the ipython crash handler so that user exceptions aren't
100 # don't use the ipython crash handler so that user exceptions aren't
101 # trapped
101 # trapped
102 sys.excepthook = ultratb.FormattedTB(color_scheme=self.colors,
102 sys.excepthook = ultratb.FormattedTB(color_scheme=self.colors,
103 mode=self.xmode,
103 mode=self.xmode,
104 call_pdb=self.pdb)
104 call_pdb=self.pdb)
105
105
106 def init_sys_modules(self):
106 def init_sys_modules(self):
107 pass
107 pass
108
108
109 def init_magics(self):
109 def init_magics(self):
110 super(InteractiveShellEmbed, self).init_magics()
110 super(InteractiveShellEmbed, self).init_magics()
111 self.register_magics(EmbeddedMagics)
111 self.register_magics(EmbeddedMagics)
112
112
113 def __call__(self, header='', local_ns=None, module=None, dummy=None,
113 def __call__(self, header='', local_ns=None, module=None, dummy=None,
114 stack_depth=1, global_ns=None, compile_flags=None):
114 stack_depth=1, global_ns=None, compile_flags=None):
115 """Activate the interactive interpreter.
115 """Activate the interactive interpreter.
116
116
117 __call__(self,header='',local_ns=None,module=None,dummy=None) -> Start
117 __call__(self,header='',local_ns=None,module=None,dummy=None) -> Start
118 the interpreter shell with the given local and global namespaces, and
118 the interpreter shell with the given local and global namespaces, and
119 optionally print a header string at startup.
119 optionally print a header string at startup.
120
120
121 The shell can be globally activated/deactivated using the
121 The shell can be globally activated/deactivated using the
122 dummy_mode attribute. This allows you to turn off a shell used
122 dummy_mode attribute. This allows you to turn off a shell used
123 for debugging globally.
123 for debugging globally.
124
124
125 However, *each* time you call the shell you can override the current
125 However, *each* time you call the shell you can override the current
126 state of dummy_mode with the optional keyword parameter 'dummy'. For
126 state of dummy_mode with the optional keyword parameter 'dummy'. For
127 example, if you set dummy mode on with IPShell.dummy_mode = True, you
127 example, if you set dummy mode on with IPShell.dummy_mode = True, you
128 can still have a specific call work by making it as IPShell(dummy=False).
128 can still have a specific call work by making it as IPShell(dummy=False).
129 """
129 """
130
130
131 # If the user has turned it off, go away
131 # If the user has turned it off, go away
132 if not self.embedded_active:
132 if not self.embedded_active:
133 return
133 return
134
134
135 # Normal exits from interactive mode set this flag, so the shell can't
135 # Normal exits from interactive mode set this flag, so the shell can't
136 # re-enter (it checks this variable at the start of interactive mode).
136 # re-enter (it checks this variable at the start of interactive mode).
137 self.exit_now = False
137 self.exit_now = False
138
138
139 # Allow the dummy parameter to override the global __dummy_mode
139 # Allow the dummy parameter to override the global __dummy_mode
140 if dummy or (dummy != 0 and self.dummy_mode):
140 if dummy or (dummy != 0 and self.dummy_mode):
141 return
141 return
142
142
143 if self.has_readline:
144 self.set_readline_completer()
145
146 # self.banner is auto computed
143 # self.banner is auto computed
147 if header:
144 if header:
148 self.old_banner2 = self.banner2
145 self.old_banner2 = self.banner2
149 self.banner2 = self.banner2 + '\n' + header + '\n'
146 self.banner2 = self.banner2 + '\n' + header + '\n'
150 else:
147 else:
151 self.old_banner2 = ''
148 self.old_banner2 = ''
152
149
153 if self.display_banner:
150 if self.display_banner:
154 self.show_banner()
151 self.show_banner()
155
152
156 # Call the embedding code with a stack depth of 1 so it can skip over
153 # Call the embedding code with a stack depth of 1 so it can skip over
157 # our call and get the original caller's namespaces.
154 # our call and get the original caller's namespaces.
158 self.mainloop(local_ns, module, stack_depth=stack_depth,
155 self.mainloop(local_ns, module, stack_depth=stack_depth,
159 global_ns=global_ns, compile_flags=compile_flags)
156 global_ns=global_ns, compile_flags=compile_flags)
160
157
161 self.banner2 = self.old_banner2
158 self.banner2 = self.old_banner2
162
159
163 if self.exit_msg is not None:
160 if self.exit_msg is not None:
164 print(self.exit_msg)
161 print(self.exit_msg)
165
162
166 if self.should_raise:
163 if self.should_raise:
167 raise KillEmbeded('Embedded IPython raising error, as user requested.')
164 raise KillEmbeded('Embedded IPython raising error, as user requested.')
168
165
169
166
170 def mainloop(self, local_ns=None, module=None, stack_depth=0,
167 def mainloop(self, local_ns=None, module=None, stack_depth=0,
171 display_banner=None, global_ns=None, compile_flags=None):
168 display_banner=None, global_ns=None, compile_flags=None):
172 """Embeds IPython into a running python program.
169 """Embeds IPython into a running python program.
173
170
174 Parameters
171 Parameters
175 ----------
172 ----------
176
173
177 local_ns, module
174 local_ns, module
178 Working local namespace (a dict) and module (a module or similar
175 Working local namespace (a dict) and module (a module or similar
179 object). If given as None, they are automatically taken from the scope
176 object). If given as None, they are automatically taken from the scope
180 where the shell was called, so that program variables become visible.
177 where the shell was called, so that program variables become visible.
181
178
182 stack_depth : int
179 stack_depth : int
183 How many levels in the stack to go to looking for namespaces (when
180 How many levels in the stack to go to looking for namespaces (when
184 local_ns or module is None). This allows an intermediate caller to
181 local_ns or module is None). This allows an intermediate caller to
185 make sure that this function gets the namespace from the intended
182 make sure that this function gets the namespace from the intended
186 level in the stack. By default (0) it will get its locals and globals
183 level in the stack. By default (0) it will get its locals and globals
187 from the immediate caller.
184 from the immediate caller.
188
185
189 compile_flags
186 compile_flags
190 A bit field identifying the __future__ features
187 A bit field identifying the __future__ features
191 that are enabled, as passed to the builtin :func:`compile` function.
188 that are enabled, as passed to the builtin :func:`compile` function.
192 If given as None, they are automatically taken from the scope where
189 If given as None, they are automatically taken from the scope where
193 the shell was called.
190 the shell was called.
194
191
195 """
192 """
196
193
197 if (global_ns is not None) and (module is None):
194 if (global_ns is not None) and (module is None):
198 raise DeprecationWarning("'global_ns' keyword argument is deprecated, and has been removed in IPython 5.0 use `module` keyword argument instead.")
195 raise DeprecationWarning("'global_ns' keyword argument is deprecated, and has been removed in IPython 5.0 use `module` keyword argument instead.")
199
196
200 if (display_banner is not None):
197 if (display_banner is not None):
201 warnings.warn("The display_banner parameter is deprecated since IPython 4.0", DeprecationWarning)
198 warnings.warn("The display_banner parameter is deprecated since IPython 4.0", DeprecationWarning)
202
199
203 # Get locals and globals from caller
200 # Get locals and globals from caller
204 if ((local_ns is None or module is None or compile_flags is None)
201 if ((local_ns is None or module is None or compile_flags is None)
205 and self.default_user_namespaces):
202 and self.default_user_namespaces):
206 call_frame = sys._getframe(stack_depth).f_back
203 call_frame = sys._getframe(stack_depth).f_back
207
204
208 if local_ns is None:
205 if local_ns is None:
209 local_ns = call_frame.f_locals
206 local_ns = call_frame.f_locals
210 if module is None:
207 if module is None:
211 global_ns = call_frame.f_globals
208 global_ns = call_frame.f_globals
212 try:
209 try:
213 module = sys.modules[global_ns['__name__']]
210 module = sys.modules[global_ns['__name__']]
214 except KeyError:
211 except KeyError:
215 warnings.warn("Failed to get module %s" % \
212 warnings.warn("Failed to get module %s" % \
216 global_ns.get('__name__', 'unknown module')
213 global_ns.get('__name__', 'unknown module')
217 )
214 )
218 module = DummyMod()
215 module = DummyMod()
219 module.__dict__ = global_ns
216 module.__dict__ = global_ns
220 if compile_flags is None:
217 if compile_flags is None:
221 compile_flags = (call_frame.f_code.co_flags &
218 compile_flags = (call_frame.f_code.co_flags &
222 compilerop.PyCF_MASK)
219 compilerop.PyCF_MASK)
223
220
224 # Save original namespace and module so we can restore them after
221 # Save original namespace and module so we can restore them after
225 # embedding; otherwise the shell doesn't shut down correctly.
222 # embedding; otherwise the shell doesn't shut down correctly.
226 orig_user_module = self.user_module
223 orig_user_module = self.user_module
227 orig_user_ns = self.user_ns
224 orig_user_ns = self.user_ns
228 orig_compile_flags = self.compile.flags
225 orig_compile_flags = self.compile.flags
229
226
230 # Update namespaces and fire up interpreter
227 # Update namespaces and fire up interpreter
231
228
232 # The global one is easy, we can just throw it in
229 # The global one is easy, we can just throw it in
233 if module is not None:
230 if module is not None:
234 self.user_module = module
231 self.user_module = module
235
232
236 # But the user/local one is tricky: ipython needs it to store internal
233 # But the user/local one is tricky: ipython needs it to store internal
237 # data, but we also need the locals. We'll throw our hidden variables
234 # data, but we also need the locals. We'll throw our hidden variables
238 # like _ih and get_ipython() into the local namespace, but delete them
235 # like _ih and get_ipython() into the local namespace, but delete them
239 # later.
236 # later.
240 if local_ns is not None:
237 if local_ns is not None:
241 reentrant_local_ns = {k: v for (k, v) in local_ns.items() if k not in self.user_ns_hidden.keys()}
238 reentrant_local_ns = {k: v for (k, v) in local_ns.items() if k not in self.user_ns_hidden.keys()}
242 self.user_ns = reentrant_local_ns
239 self.user_ns = reentrant_local_ns
243 self.init_user_ns()
240 self.init_user_ns()
244
241
245 # Compiler flags
242 # Compiler flags
246 if compile_flags is not None:
243 if compile_flags is not None:
247 self.compile.flags = compile_flags
244 self.compile.flags = compile_flags
248
245
249 # make sure the tab-completer has the correct frame information, so it
246 # make sure the tab-completer has the correct frame information, so it
250 # actually completes using the frame's locals/globals
247 # actually completes using the frame's locals/globals
251 self.set_completer_frame()
248 self.set_completer_frame()
252
249
253 with self.builtin_trap, self.display_trap:
250 with self.builtin_trap, self.display_trap:
254 self.interact()
251 self.interact()
255
252
256 # now, purge out the local namespace of IPython's hidden variables.
253 # now, purge out the local namespace of IPython's hidden variables.
257 if local_ns is not None:
254 if local_ns is not None:
258 local_ns.update({k: v for (k, v) in self.user_ns.items() if k not in self.user_ns_hidden.keys()})
255 local_ns.update({k: v for (k, v) in self.user_ns.items() if k not in self.user_ns_hidden.keys()})
259
256
260
257
261 # Restore original namespace so shell can shut down when we exit.
258 # Restore original namespace so shell can shut down when we exit.
262 self.user_module = orig_user_module
259 self.user_module = orig_user_module
263 self.user_ns = orig_user_ns
260 self.user_ns = orig_user_ns
264 self.compile.flags = orig_compile_flags
261 self.compile.flags = orig_compile_flags
265
262
266
263
267 def embed(**kwargs):
264 def embed(**kwargs):
268 """Call this to embed IPython at the current point in your program.
265 """Call this to embed IPython at the current point in your program.
269
266
270 The first invocation of this will create an :class:`InteractiveShellEmbed`
267 The first invocation of this will create an :class:`InteractiveShellEmbed`
271 instance and then call it. Consecutive calls just call the already
268 instance and then call it. Consecutive calls just call the already
272 created instance.
269 created instance.
273
270
274 If you don't want the kernel to initialize the namespace
271 If you don't want the kernel to initialize the namespace
275 from the scope of the surrounding function,
272 from the scope of the surrounding function,
276 and/or you want to load full IPython configuration,
273 and/or you want to load full IPython configuration,
277 you probably want `IPython.start_ipython()` instead.
274 you probably want `IPython.start_ipython()` instead.
278
275
279 Here is a simple example::
276 Here is a simple example::
280
277
281 from IPython import embed
278 from IPython import embed
282 a = 10
279 a = 10
283 b = 20
280 b = 20
284 embed(header='First time')
281 embed(header='First time')
285 c = 30
282 c = 30
286 d = 40
283 d = 40
287 embed()
284 embed()
288
285
289 Full customization can be done by passing a :class:`Config` in as the
286 Full customization can be done by passing a :class:`Config` in as the
290 config argument.
287 config argument.
291 """
288 """
292 config = kwargs.get('config')
289 config = kwargs.get('config')
293 header = kwargs.pop('header', u'')
290 header = kwargs.pop('header', u'')
294 compile_flags = kwargs.pop('compile_flags', None)
291 compile_flags = kwargs.pop('compile_flags', None)
295 if config is None:
292 if config is None:
296 config = load_default_config()
293 config = load_default_config()
297 config.InteractiveShellEmbed = config.TerminalInteractiveShell
294 config.InteractiveShellEmbed = config.TerminalInteractiveShell
298 config.InteractiveShellEmbed.colors='nocolor'
295 config.InteractiveShellEmbed.colors='nocolor'
299 kwargs['config'] = config
296 kwargs['config'] = config
300 #save ps1/ps2 if defined
297 #save ps1/ps2 if defined
301 ps1 = None
298 ps1 = None
302 ps2 = None
299 ps2 = None
303 try:
300 try:
304 ps1 = sys.ps1
301 ps1 = sys.ps1
305 ps2 = sys.ps2
302 ps2 = sys.ps2
306 except AttributeError:
303 except AttributeError:
307 pass
304 pass
308 #save previous instance
305 #save previous instance
309 saved_shell_instance = InteractiveShell._instance
306 saved_shell_instance = InteractiveShell._instance
310 if saved_shell_instance is not None:
307 if saved_shell_instance is not None:
311 cls = type(saved_shell_instance)
308 cls = type(saved_shell_instance)
312 cls.clear_instance()
309 cls.clear_instance()
313 frame = sys._getframe(1)
310 frame = sys._getframe(1)
314 shell = InteractiveShellEmbed.instance(_call_location_id='%s:%s' % (frame.f_code.co_filename, frame.f_lineno), **kwargs)
311 shell = InteractiveShellEmbed.instance(_call_location_id='%s:%s' % (frame.f_code.co_filename, frame.f_lineno), **kwargs)
315 shell(header=header, stack_depth=2, compile_flags=compile_flags)
312 shell(header=header, stack_depth=2, compile_flags=compile_flags)
316 InteractiveShellEmbed.clear_instance()
313 InteractiveShellEmbed.clear_instance()
317 #restore previous instance
314 #restore previous instance
318 if saved_shell_instance is not None:
315 if saved_shell_instance is not None:
319 cls = type(saved_shell_instance)
316 cls = type(saved_shell_instance)
320 cls.clear_instance()
317 cls.clear_instance()
321 for subclass in cls._walk_mro():
318 for subclass in cls._walk_mro():
322 subclass._instance = saved_shell_instance
319 subclass._instance = saved_shell_instance
323 if ps1 is not None:
320 if ps1 is not None:
324 sys.ps1 = ps1
321 sys.ps1 = ps1
325 sys.ps2 = ps2
322 sys.ps2 = ps2
General Comments 0
You need to be logged in to leave comments. Login now