##// END OF EJS Templates
Change functions,...
Srinivas Reddy Thatiparthy -
Show More
@@ -1,103 +1,103 b''
1 """
1 """
2 A context manager for managing things injected into :mod:`__builtin__`.
2 A context manager for managing things injected into :mod:`__builtin__`.
3
3
4 Authors:
4 Authors:
5
5
6 * Brian Granger
6 * Brian Granger
7 * Fernando Perez
7 * Fernando Perez
8 """
8 """
9 #-----------------------------------------------------------------------------
9 #-----------------------------------------------------------------------------
10 # Copyright (C) 2010-2011 The IPython Development Team.
10 # Copyright (C) 2010-2011 The IPython Development Team.
11 #
11 #
12 # Distributed under the terms of the BSD License.
12 # Distributed under the terms of the BSD License.
13 #
13 #
14 # Complete license in the file COPYING.txt, distributed with this software.
14 # Complete license in the file COPYING.txt, distributed with this software.
15 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
16
16
17 #-----------------------------------------------------------------------------
17 #-----------------------------------------------------------------------------
18 # Imports
18 # Imports
19 #-----------------------------------------------------------------------------
19 #-----------------------------------------------------------------------------
20
20
21 from traitlets.config.configurable import Configurable
21 from traitlets.config.configurable import Configurable
22
22
23 from IPython.utils.py3compat import builtin_mod, iteritems
23 from IPython.utils.py3compat import builtin_mod
24 from traitlets import Instance
24 from traitlets import Instance
25
25
26 #-----------------------------------------------------------------------------
26 #-----------------------------------------------------------------------------
27 # Classes and functions
27 # Classes and functions
28 #-----------------------------------------------------------------------------
28 #-----------------------------------------------------------------------------
29
29
30 class __BuiltinUndefined(object): pass
30 class __BuiltinUndefined(object): pass
31 BuiltinUndefined = __BuiltinUndefined()
31 BuiltinUndefined = __BuiltinUndefined()
32
32
33 class __HideBuiltin(object): pass
33 class __HideBuiltin(object): pass
34 HideBuiltin = __HideBuiltin()
34 HideBuiltin = __HideBuiltin()
35
35
36
36
37 class BuiltinTrap(Configurable):
37 class BuiltinTrap(Configurable):
38
38
39 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC',
39 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC',
40 allow_none=True)
40 allow_none=True)
41
41
42 def __init__(self, shell=None):
42 def __init__(self, shell=None):
43 super(BuiltinTrap, self).__init__(shell=shell, config=None)
43 super(BuiltinTrap, self).__init__(shell=shell, config=None)
44 self._orig_builtins = {}
44 self._orig_builtins = {}
45 # We define this to track if a single BuiltinTrap is nested.
45 # We define this to track if a single BuiltinTrap is nested.
46 # Only turn off the trap when the outermost call to __exit__ is made.
46 # Only turn off the trap when the outermost call to __exit__ is made.
47 self._nested_level = 0
47 self._nested_level = 0
48 self.shell = shell
48 self.shell = shell
49 # builtins we always add - if set to HideBuiltin, they will just
49 # builtins we always add - if set to HideBuiltin, they will just
50 # be removed instead of being replaced by something else
50 # be removed instead of being replaced by something else
51 self.auto_builtins = {'exit': HideBuiltin,
51 self.auto_builtins = {'exit': HideBuiltin,
52 'quit': HideBuiltin,
52 'quit': HideBuiltin,
53 'get_ipython': self.shell.get_ipython,
53 'get_ipython': self.shell.get_ipython,
54 }
54 }
55
55
56 def __enter__(self):
56 def __enter__(self):
57 if self._nested_level == 0:
57 if self._nested_level == 0:
58 self.activate()
58 self.activate()
59 self._nested_level += 1
59 self._nested_level += 1
60 # I return self, so callers can use add_builtin in a with clause.
60 # I return self, so callers can use add_builtin in a with clause.
61 return self
61 return self
62
62
63 def __exit__(self, type, value, traceback):
63 def __exit__(self, type, value, traceback):
64 if self._nested_level == 1:
64 if self._nested_level == 1:
65 self.deactivate()
65 self.deactivate()
66 self._nested_level -= 1
66 self._nested_level -= 1
67 # Returning False will cause exceptions to propagate
67 # Returning False will cause exceptions to propagate
68 return False
68 return False
69
69
70 def add_builtin(self, key, value):
70 def add_builtin(self, key, value):
71 """Add a builtin and save the original."""
71 """Add a builtin and save the original."""
72 bdict = builtin_mod.__dict__
72 bdict = builtin_mod.__dict__
73 orig = bdict.get(key, BuiltinUndefined)
73 orig = bdict.get(key, BuiltinUndefined)
74 if value is HideBuiltin:
74 if value is HideBuiltin:
75 if orig is not BuiltinUndefined: #same as 'key in bdict'
75 if orig is not BuiltinUndefined: #same as 'key in bdict'
76 self._orig_builtins[key] = orig
76 self._orig_builtins[key] = orig
77 del bdict[key]
77 del bdict[key]
78 else:
78 else:
79 self._orig_builtins[key] = orig
79 self._orig_builtins[key] = orig
80 bdict[key] = value
80 bdict[key] = value
81
81
82 def remove_builtin(self, key, orig):
82 def remove_builtin(self, key, orig):
83 """Remove an added builtin and re-set the original."""
83 """Remove an added builtin and re-set the original."""
84 if orig is BuiltinUndefined:
84 if orig is BuiltinUndefined:
85 del builtin_mod.__dict__[key]
85 del builtin_mod.__dict__[key]
86 else:
86 else:
87 builtin_mod.__dict__[key] = orig
87 builtin_mod.__dict__[key] = orig
88
88
89 def activate(self):
89 def activate(self):
90 """Store ipython references in the __builtin__ namespace."""
90 """Store ipython references in the __builtin__ namespace."""
91
91
92 add_builtin = self.add_builtin
92 add_builtin = self.add_builtin
93 for name, func in iteritems(self.auto_builtins):
93 for name, func in self.auto_builtins.items():
94 add_builtin(name, func)
94 add_builtin(name, func)
95
95
96 def deactivate(self):
96 def deactivate(self):
97 """Remove any builtins which might have been added by add_builtins, or
97 """Remove any builtins which might have been added by add_builtins, or
98 restore overwritten ones to their previous values."""
98 restore overwritten ones to their previous values."""
99 remove_builtin = self.remove_builtin
99 remove_builtin = self.remove_builtin
100 for key, val in iteritems(self._orig_builtins):
100 for key, val in self._orig_builtins.items():
101 remove_builtin(key, val)
101 remove_builtin(key, val)
102 self._orig_builtins.clear()
102 self._orig_builtins.clear()
103 self._builtins_added = False
103 self._builtins_added = False
@@ -1,3226 +1,3226 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
13
14 import __future__
14 import __future__
15 import abc
15 import abc
16 import ast
16 import ast
17 import atexit
17 import atexit
18 import functools
18 import functools
19 import os
19 import os
20 import re
20 import re
21 import runpy
21 import runpy
22 import sys
22 import sys
23 import tempfile
23 import tempfile
24 import traceback
24 import traceback
25 import types
25 import types
26 import subprocess
26 import subprocess
27 import warnings
27 import warnings
28 from io import open as io_open
28 from io import open as io_open
29
29
30 from pickleshare import PickleShareDB
30 from pickleshare import PickleShareDB
31
31
32 from traitlets.config.configurable import SingletonConfigurable
32 from traitlets.config.configurable import SingletonConfigurable
33 from IPython.core import oinspect
33 from IPython.core import oinspect
34 from IPython.core import magic
34 from IPython.core import magic
35 from IPython.core import page
35 from IPython.core import page
36 from IPython.core import prefilter
36 from IPython.core import prefilter
37 from IPython.core import shadowns
37 from IPython.core import shadowns
38 from IPython.core import ultratb
38 from IPython.core import ultratb
39 from IPython.core.alias import Alias, AliasManager
39 from IPython.core.alias import Alias, AliasManager
40 from IPython.core.autocall import ExitAutocall
40 from IPython.core.autocall import ExitAutocall
41 from IPython.core.builtin_trap import BuiltinTrap
41 from IPython.core.builtin_trap import BuiltinTrap
42 from IPython.core.events import EventManager, available_events
42 from IPython.core.events import EventManager, available_events
43 from IPython.core.compilerop import CachingCompiler, check_linecache_ipython
43 from IPython.core.compilerop import CachingCompiler, check_linecache_ipython
44 from IPython.core.debugger import Pdb
44 from IPython.core.debugger import Pdb
45 from IPython.core.display_trap import DisplayTrap
45 from IPython.core.display_trap import DisplayTrap
46 from IPython.core.displayhook import DisplayHook
46 from IPython.core.displayhook import DisplayHook
47 from IPython.core.displaypub import DisplayPublisher
47 from IPython.core.displaypub import DisplayPublisher
48 from IPython.core.error import InputRejected, UsageError
48 from IPython.core.error import InputRejected, UsageError
49 from IPython.core.extensions import ExtensionManager
49 from IPython.core.extensions import ExtensionManager
50 from IPython.core.formatters import DisplayFormatter
50 from IPython.core.formatters import DisplayFormatter
51 from IPython.core.history import HistoryManager
51 from IPython.core.history import HistoryManager
52 from IPython.core.inputsplitter import ESC_MAGIC, ESC_MAGIC2
52 from IPython.core.inputsplitter import ESC_MAGIC, ESC_MAGIC2
53 from IPython.core.logger import Logger
53 from IPython.core.logger import Logger
54 from IPython.core.macro import Macro
54 from IPython.core.macro import Macro
55 from IPython.core.payload import PayloadManager
55 from IPython.core.payload import PayloadManager
56 from IPython.core.prefilter import PrefilterManager
56 from IPython.core.prefilter import PrefilterManager
57 from IPython.core.profiledir import ProfileDir
57 from IPython.core.profiledir import ProfileDir
58 from IPython.core.usage import default_banner
58 from IPython.core.usage import default_banner
59 from IPython.testing.skipdoctest import skip_doctest
59 from IPython.testing.skipdoctest import skip_doctest
60 from IPython.utils import PyColorize
60 from IPython.utils import PyColorize
61 from IPython.utils import io
61 from IPython.utils import io
62 from IPython.utils import py3compat
62 from IPython.utils import py3compat
63 from IPython.utils import openpy
63 from IPython.utils import openpy
64 from IPython.utils.decorators import undoc
64 from IPython.utils.decorators import undoc
65 from IPython.utils.io import ask_yes_no
65 from IPython.utils.io import ask_yes_no
66 from IPython.utils.ipstruct import Struct
66 from IPython.utils.ipstruct import Struct
67 from IPython.paths import get_ipython_dir
67 from IPython.paths import get_ipython_dir
68 from IPython.utils.path import get_home_dir, get_py_filename, ensure_dir_exists
68 from IPython.utils.path import get_home_dir, get_py_filename, ensure_dir_exists
69 from IPython.utils.process import system, getoutput
69 from IPython.utils.process import system, getoutput
70 from IPython.utils.py3compat import (builtin_mod, unicode_type, string_types,
70 from IPython.utils.py3compat import (builtin_mod, unicode_type, string_types,
71 with_metaclass, iteritems)
71 with_metaclass)
72 from IPython.utils.strdispatch import StrDispatch
72 from IPython.utils.strdispatch import StrDispatch
73 from IPython.utils.syspathcontext import prepended_to_syspath
73 from IPython.utils.syspathcontext import prepended_to_syspath
74 from IPython.utils.text import format_screen, LSString, SList, DollarFormatter
74 from IPython.utils.text import format_screen, LSString, SList, DollarFormatter
75 from IPython.utils.tempdir import TemporaryDirectory
75 from IPython.utils.tempdir import TemporaryDirectory
76 from traitlets import (
76 from traitlets import (
77 Integer, Bool, CaselessStrEnum, Enum, List, Dict, Unicode, Instance, Type,
77 Integer, Bool, CaselessStrEnum, Enum, List, Dict, Unicode, Instance, Type,
78 observe, default,
78 observe, default,
79 )
79 )
80 from warnings import warn
80 from warnings import warn
81 from logging import error
81 from logging import error
82 import IPython.core.hooks
82 import IPython.core.hooks
83
83
84 # NoOpContext is deprecated, but ipykernel imports it from here.
84 # NoOpContext is deprecated, but ipykernel imports it from here.
85 # See https://github.com/ipython/ipykernel/issues/157
85 # See https://github.com/ipython/ipykernel/issues/157
86 from IPython.utils.contexts import NoOpContext
86 from IPython.utils.contexts import NoOpContext
87
87
88 try:
88 try:
89 import docrepr.sphinxify as sphx
89 import docrepr.sphinxify as sphx
90
90
91 def sphinxify(doc):
91 def sphinxify(doc):
92 with TemporaryDirectory() as dirname:
92 with TemporaryDirectory() as dirname:
93 return {
93 return {
94 'text/html': sphx.sphinxify(doc, dirname),
94 'text/html': sphx.sphinxify(doc, dirname),
95 'text/plain': doc
95 'text/plain': doc
96 }
96 }
97 except ImportError:
97 except ImportError:
98 sphinxify = None
98 sphinxify = None
99
99
100
100
101 class ProvisionalWarning(DeprecationWarning):
101 class ProvisionalWarning(DeprecationWarning):
102 """
102 """
103 Warning class for unstable features
103 Warning class for unstable features
104 """
104 """
105 pass
105 pass
106
106
107 #-----------------------------------------------------------------------------
107 #-----------------------------------------------------------------------------
108 # Globals
108 # Globals
109 #-----------------------------------------------------------------------------
109 #-----------------------------------------------------------------------------
110
110
111 # compiled regexps for autoindent management
111 # compiled regexps for autoindent management
112 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
112 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
113
113
114 #-----------------------------------------------------------------------------
114 #-----------------------------------------------------------------------------
115 # Utilities
115 # Utilities
116 #-----------------------------------------------------------------------------
116 #-----------------------------------------------------------------------------
117
117
118 @undoc
118 @undoc
119 def softspace(file, newvalue):
119 def softspace(file, newvalue):
120 """Copied from code.py, to remove the dependency"""
120 """Copied from code.py, to remove the dependency"""
121
121
122 oldvalue = 0
122 oldvalue = 0
123 try:
123 try:
124 oldvalue = file.softspace
124 oldvalue = file.softspace
125 except AttributeError:
125 except AttributeError:
126 pass
126 pass
127 try:
127 try:
128 file.softspace = newvalue
128 file.softspace = newvalue
129 except (AttributeError, TypeError):
129 except (AttributeError, TypeError):
130 # "attribute-less object" or "read-only attributes"
130 # "attribute-less object" or "read-only attributes"
131 pass
131 pass
132 return oldvalue
132 return oldvalue
133
133
134 @undoc
134 @undoc
135 def no_op(*a, **kw): pass
135 def no_op(*a, **kw): pass
136
136
137
137
138 class SpaceInInput(Exception): pass
138 class SpaceInInput(Exception): pass
139
139
140
140
141 def get_default_colors():
141 def get_default_colors():
142 "DEPRECATED"
142 "DEPRECATED"
143 warn('get_default_color is Deprecated, and is `Neutral` on all platforms.',
143 warn('get_default_color is Deprecated, and is `Neutral` on all platforms.',
144 DeprecationWarning, stacklevel=2)
144 DeprecationWarning, stacklevel=2)
145 return 'Neutral'
145 return 'Neutral'
146
146
147
147
148 class SeparateUnicode(Unicode):
148 class SeparateUnicode(Unicode):
149 r"""A Unicode subclass to validate separate_in, separate_out, etc.
149 r"""A Unicode subclass to validate separate_in, separate_out, etc.
150
150
151 This is a Unicode based trait that converts '0'->'' and ``'\\n'->'\n'``.
151 This is a Unicode based trait that converts '0'->'' and ``'\\n'->'\n'``.
152 """
152 """
153
153
154 def validate(self, obj, value):
154 def validate(self, obj, value):
155 if value == '0': value = ''
155 if value == '0': value = ''
156 value = value.replace('\\n','\n')
156 value = value.replace('\\n','\n')
157 return super(SeparateUnicode, self).validate(obj, value)
157 return super(SeparateUnicode, self).validate(obj, value)
158
158
159
159
160 @undoc
160 @undoc
161 class DummyMod(object):
161 class DummyMod(object):
162 """A dummy module used for IPython's interactive module when
162 """A dummy module used for IPython's interactive module when
163 a namespace must be assigned to the module's __dict__."""
163 a namespace must be assigned to the module's __dict__."""
164 pass
164 pass
165
165
166
166
167 class ExecutionResult(object):
167 class ExecutionResult(object):
168 """The result of a call to :meth:`InteractiveShell.run_cell`
168 """The result of a call to :meth:`InteractiveShell.run_cell`
169
169
170 Stores information about what took place.
170 Stores information about what took place.
171 """
171 """
172 execution_count = None
172 execution_count = None
173 error_before_exec = None
173 error_before_exec = None
174 error_in_exec = None
174 error_in_exec = None
175 result = None
175 result = None
176
176
177 @property
177 @property
178 def success(self):
178 def success(self):
179 return (self.error_before_exec is None) and (self.error_in_exec is None)
179 return (self.error_before_exec is None) and (self.error_in_exec is None)
180
180
181 def raise_error(self):
181 def raise_error(self):
182 """Reraises error if `success` is `False`, otherwise does nothing"""
182 """Reraises error if `success` is `False`, otherwise does nothing"""
183 if self.error_before_exec is not None:
183 if self.error_before_exec is not None:
184 raise self.error_before_exec
184 raise self.error_before_exec
185 if self.error_in_exec is not None:
185 if self.error_in_exec is not None:
186 raise self.error_in_exec
186 raise self.error_in_exec
187
187
188 def __repr__(self):
188 def __repr__(self):
189 name = self.__class__.__qualname__
189 name = self.__class__.__qualname__
190 return '<%s object at %x, execution_count=%s error_before_exec=%s error_in_exec=%s result=%s>' %\
190 return '<%s object at %x, execution_count=%s error_before_exec=%s error_in_exec=%s result=%s>' %\
191 (name, id(self), self.execution_count, self.error_before_exec, self.error_in_exec, repr(self.result))
191 (name, id(self), self.execution_count, self.error_before_exec, self.error_in_exec, repr(self.result))
192
192
193
193
194 class InteractiveShell(SingletonConfigurable):
194 class InteractiveShell(SingletonConfigurable):
195 """An enhanced, interactive shell for Python."""
195 """An enhanced, interactive shell for Python."""
196
196
197 _instance = None
197 _instance = None
198
198
199 ast_transformers = List([], help=
199 ast_transformers = List([], help=
200 """
200 """
201 A list of ast.NodeTransformer subclass instances, which will be applied
201 A list of ast.NodeTransformer subclass instances, which will be applied
202 to user input before code is run.
202 to user input before code is run.
203 """
203 """
204 ).tag(config=True)
204 ).tag(config=True)
205
205
206 autocall = Enum((0,1,2), default_value=0, help=
206 autocall = Enum((0,1,2), default_value=0, help=
207 """
207 """
208 Make IPython automatically call any callable object even if you didn't
208 Make IPython automatically call any callable object even if you didn't
209 type explicit parentheses. For example, 'str 43' becomes 'str(43)'
209 type explicit parentheses. For example, 'str 43' becomes 'str(43)'
210 automatically. The value can be '0' to disable the feature, '1' for
210 automatically. The value can be '0' to disable the feature, '1' for
211 'smart' autocall, where it is not applied if there are no more
211 'smart' autocall, where it is not applied if there are no more
212 arguments on the line, and '2' for 'full' autocall, where all callable
212 arguments on the line, and '2' for 'full' autocall, where all callable
213 objects are automatically called (even if no arguments are present).
213 objects are automatically called (even if no arguments are present).
214 """
214 """
215 ).tag(config=True)
215 ).tag(config=True)
216 # TODO: remove all autoindent logic and put into frontends.
216 # TODO: remove all autoindent logic and put into frontends.
217 # We can't do this yet because even runlines uses the autoindent.
217 # We can't do this yet because even runlines uses the autoindent.
218 autoindent = Bool(True, help=
218 autoindent = Bool(True, help=
219 """
219 """
220 Autoindent IPython code entered interactively.
220 Autoindent IPython code entered interactively.
221 """
221 """
222 ).tag(config=True)
222 ).tag(config=True)
223
223
224 automagic = Bool(True, help=
224 automagic = Bool(True, help=
225 """
225 """
226 Enable magic commands to be called without the leading %.
226 Enable magic commands to be called without the leading %.
227 """
227 """
228 ).tag(config=True)
228 ).tag(config=True)
229
229
230 banner1 = Unicode(default_banner,
230 banner1 = Unicode(default_banner,
231 help="""The part of the banner to be printed before the profile"""
231 help="""The part of the banner to be printed before the profile"""
232 ).tag(config=True)
232 ).tag(config=True)
233 banner2 = Unicode('',
233 banner2 = Unicode('',
234 help="""The part of the banner to be printed after the profile"""
234 help="""The part of the banner to be printed after the profile"""
235 ).tag(config=True)
235 ).tag(config=True)
236
236
237 cache_size = Integer(1000, help=
237 cache_size = Integer(1000, help=
238 """
238 """
239 Set the size of the output cache. The default is 1000, you can
239 Set the size of the output cache. The default is 1000, you can
240 change it permanently in your config file. Setting it to 0 completely
240 change it permanently in your config file. Setting it to 0 completely
241 disables the caching system, and the minimum value accepted is 20 (if
241 disables the caching system, and the minimum value accepted is 20 (if
242 you provide a value less than 20, it is reset to 0 and a warning is
242 you provide a value less than 20, it is reset to 0 and a warning is
243 issued). This limit is defined because otherwise you'll spend more
243 issued). This limit is defined because otherwise you'll spend more
244 time re-flushing a too small cache than working
244 time re-flushing a too small cache than working
245 """
245 """
246 ).tag(config=True)
246 ).tag(config=True)
247 color_info = Bool(True, help=
247 color_info = Bool(True, help=
248 """
248 """
249 Use colors for displaying information about objects. Because this
249 Use colors for displaying information about objects. Because this
250 information is passed through a pager (like 'less'), and some pagers
250 information is passed through a pager (like 'less'), and some pagers
251 get confused with color codes, this capability can be turned off.
251 get confused with color codes, this capability can be turned off.
252 """
252 """
253 ).tag(config=True)
253 ).tag(config=True)
254 colors = CaselessStrEnum(('Neutral', 'NoColor','LightBG','Linux'),
254 colors = CaselessStrEnum(('Neutral', 'NoColor','LightBG','Linux'),
255 default_value='Neutral',
255 default_value='Neutral',
256 help="Set the color scheme (NoColor, Neutral, Linux, or LightBG)."
256 help="Set the color scheme (NoColor, Neutral, Linux, or LightBG)."
257 ).tag(config=True)
257 ).tag(config=True)
258 debug = Bool(False).tag(config=True)
258 debug = Bool(False).tag(config=True)
259 disable_failing_post_execute = Bool(False,
259 disable_failing_post_execute = Bool(False,
260 help="Don't call post-execute functions that have failed in the past."
260 help="Don't call post-execute functions that have failed in the past."
261 ).tag(config=True)
261 ).tag(config=True)
262 display_formatter = Instance(DisplayFormatter, allow_none=True)
262 display_formatter = Instance(DisplayFormatter, allow_none=True)
263 displayhook_class = Type(DisplayHook)
263 displayhook_class = Type(DisplayHook)
264 display_pub_class = Type(DisplayPublisher)
264 display_pub_class = Type(DisplayPublisher)
265
265
266 sphinxify_docstring = Bool(False, help=
266 sphinxify_docstring = Bool(False, help=
267 """
267 """
268 Enables rich html representation of docstrings. (This requires the
268 Enables rich html representation of docstrings. (This requires the
269 docrepr module).
269 docrepr module).
270 """).tag(config=True)
270 """).tag(config=True)
271
271
272 @observe("sphinxify_docstring")
272 @observe("sphinxify_docstring")
273 def _sphinxify_docstring_changed(self, change):
273 def _sphinxify_docstring_changed(self, change):
274 if change['new']:
274 if change['new']:
275 warn("`sphinxify_docstring` is provisional since IPython 5.0 and might change in future versions." , ProvisionalWarning)
275 warn("`sphinxify_docstring` is provisional since IPython 5.0 and might change in future versions." , ProvisionalWarning)
276
276
277 enable_html_pager = Bool(False, help=
277 enable_html_pager = Bool(False, help=
278 """
278 """
279 (Provisional API) enables html representation in mime bundles sent
279 (Provisional API) enables html representation in mime bundles sent
280 to pagers.
280 to pagers.
281 """).tag(config=True)
281 """).tag(config=True)
282
282
283 @observe("enable_html_pager")
283 @observe("enable_html_pager")
284 def _enable_html_pager_changed(self, change):
284 def _enable_html_pager_changed(self, change):
285 if change['new']:
285 if change['new']:
286 warn("`enable_html_pager` is provisional since IPython 5.0 and might change in future versions.", ProvisionalWarning)
286 warn("`enable_html_pager` is provisional since IPython 5.0 and might change in future versions.", ProvisionalWarning)
287
287
288 data_pub_class = None
288 data_pub_class = None
289
289
290 exit_now = Bool(False)
290 exit_now = Bool(False)
291 exiter = Instance(ExitAutocall)
291 exiter = Instance(ExitAutocall)
292 @default('exiter')
292 @default('exiter')
293 def _exiter_default(self):
293 def _exiter_default(self):
294 return ExitAutocall(self)
294 return ExitAutocall(self)
295 # Monotonically increasing execution counter
295 # Monotonically increasing execution counter
296 execution_count = Integer(1)
296 execution_count = Integer(1)
297 filename = Unicode("<ipython console>")
297 filename = Unicode("<ipython console>")
298 ipython_dir= Unicode('').tag(config=True) # Set to get_ipython_dir() in __init__
298 ipython_dir= Unicode('').tag(config=True) # Set to get_ipython_dir() in __init__
299
299
300 # Input splitter, to transform input line by line and detect when a block
300 # Input splitter, to transform input line by line and detect when a block
301 # is ready to be executed.
301 # is ready to be executed.
302 input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
302 input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
303 (), {'line_input_checker': True})
303 (), {'line_input_checker': True})
304
304
305 # This InputSplitter instance is used to transform completed cells before
305 # This InputSplitter instance is used to transform completed cells before
306 # running them. It allows cell magics to contain blank lines.
306 # running them. It allows cell magics to contain blank lines.
307 input_transformer_manager = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
307 input_transformer_manager = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
308 (), {'line_input_checker': False})
308 (), {'line_input_checker': False})
309
309
310 logstart = Bool(False, help=
310 logstart = Bool(False, help=
311 """
311 """
312 Start logging to the default log file in overwrite mode.
312 Start logging to the default log file in overwrite mode.
313 Use `logappend` to specify a log file to **append** logs to.
313 Use `logappend` to specify a log file to **append** logs to.
314 """
314 """
315 ).tag(config=True)
315 ).tag(config=True)
316 logfile = Unicode('', help=
316 logfile = Unicode('', help=
317 """
317 """
318 The name of the logfile to use.
318 The name of the logfile to use.
319 """
319 """
320 ).tag(config=True)
320 ).tag(config=True)
321 logappend = Unicode('', help=
321 logappend = Unicode('', help=
322 """
322 """
323 Start logging to the given file in append mode.
323 Start logging to the given file in append mode.
324 Use `logfile` to specify a log file to **overwrite** logs to.
324 Use `logfile` to specify a log file to **overwrite** logs to.
325 """
325 """
326 ).tag(config=True)
326 ).tag(config=True)
327 object_info_string_level = Enum((0,1,2), default_value=0,
327 object_info_string_level = Enum((0,1,2), default_value=0,
328 ).tag(config=True)
328 ).tag(config=True)
329 pdb = Bool(False, help=
329 pdb = Bool(False, help=
330 """
330 """
331 Automatically call the pdb debugger after every exception.
331 Automatically call the pdb debugger after every exception.
332 """
332 """
333 ).tag(config=True)
333 ).tag(config=True)
334 display_page = Bool(False,
334 display_page = Bool(False,
335 help="""If True, anything that would be passed to the pager
335 help="""If True, anything that would be passed to the pager
336 will be displayed as regular output instead."""
336 will be displayed as regular output instead."""
337 ).tag(config=True)
337 ).tag(config=True)
338
338
339 # deprecated prompt traits:
339 # deprecated prompt traits:
340
340
341 prompt_in1 = Unicode('In [\\#]: ',
341 prompt_in1 = Unicode('In [\\#]: ',
342 help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
342 help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
343 ).tag(config=True)
343 ).tag(config=True)
344 prompt_in2 = Unicode(' .\\D.: ',
344 prompt_in2 = Unicode(' .\\D.: ',
345 help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
345 help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
346 ).tag(config=True)
346 ).tag(config=True)
347 prompt_out = Unicode('Out[\\#]: ',
347 prompt_out = Unicode('Out[\\#]: ',
348 help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
348 help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
349 ).tag(config=True)
349 ).tag(config=True)
350 prompts_pad_left = Bool(True,
350 prompts_pad_left = Bool(True,
351 help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
351 help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
352 ).tag(config=True)
352 ).tag(config=True)
353
353
354 @observe('prompt_in1', 'prompt_in2', 'prompt_out', 'prompt_pad_left')
354 @observe('prompt_in1', 'prompt_in2', 'prompt_out', 'prompt_pad_left')
355 def _prompt_trait_changed(self, change):
355 def _prompt_trait_changed(self, change):
356 name = change['name']
356 name = change['name']
357 warn("InteractiveShell.{name} is deprecated since IPython 4.0"
357 warn("InteractiveShell.{name} is deprecated since IPython 4.0"
358 " and ignored since 5.0, set TerminalInteractiveShell.prompts"
358 " and ignored since 5.0, set TerminalInteractiveShell.prompts"
359 " object directly.".format(name=name))
359 " object directly.".format(name=name))
360
360
361 # protect against weird cases where self.config may not exist:
361 # protect against weird cases where self.config may not exist:
362
362
363 show_rewritten_input = Bool(True,
363 show_rewritten_input = Bool(True,
364 help="Show rewritten input, e.g. for autocall."
364 help="Show rewritten input, e.g. for autocall."
365 ).tag(config=True)
365 ).tag(config=True)
366
366
367 quiet = Bool(False).tag(config=True)
367 quiet = Bool(False).tag(config=True)
368
368
369 history_length = Integer(10000,
369 history_length = Integer(10000,
370 help='Total length of command history'
370 help='Total length of command history'
371 ).tag(config=True)
371 ).tag(config=True)
372
372
373 history_load_length = Integer(1000, help=
373 history_load_length = Integer(1000, help=
374 """
374 """
375 The number of saved history entries to be loaded
375 The number of saved history entries to be loaded
376 into the history buffer at startup.
376 into the history buffer at startup.
377 """
377 """
378 ).tag(config=True)
378 ).tag(config=True)
379
379
380 ast_node_interactivity = Enum(['all', 'last', 'last_expr', 'none'],
380 ast_node_interactivity = Enum(['all', 'last', 'last_expr', 'none'],
381 default_value='last_expr',
381 default_value='last_expr',
382 help="""
382 help="""
383 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
383 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
384 run interactively (displaying output from expressions)."""
384 run interactively (displaying output from expressions)."""
385 ).tag(config=True)
385 ).tag(config=True)
386
386
387 # TODO: this part of prompt management should be moved to the frontends.
387 # TODO: this part of prompt management should be moved to the frontends.
388 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
388 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
389 separate_in = SeparateUnicode('\n').tag(config=True)
389 separate_in = SeparateUnicode('\n').tag(config=True)
390 separate_out = SeparateUnicode('').tag(config=True)
390 separate_out = SeparateUnicode('').tag(config=True)
391 separate_out2 = SeparateUnicode('').tag(config=True)
391 separate_out2 = SeparateUnicode('').tag(config=True)
392 wildcards_case_sensitive = Bool(True).tag(config=True)
392 wildcards_case_sensitive = Bool(True).tag(config=True)
393 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
393 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
394 default_value='Context').tag(config=True)
394 default_value='Context').tag(config=True)
395
395
396 # Subcomponents of InteractiveShell
396 # Subcomponents of InteractiveShell
397 alias_manager = Instance('IPython.core.alias.AliasManager', allow_none=True)
397 alias_manager = Instance('IPython.core.alias.AliasManager', allow_none=True)
398 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager', allow_none=True)
398 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager', allow_none=True)
399 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap', allow_none=True)
399 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap', allow_none=True)
400 display_trap = Instance('IPython.core.display_trap.DisplayTrap', allow_none=True)
400 display_trap = Instance('IPython.core.display_trap.DisplayTrap', allow_none=True)
401 extension_manager = Instance('IPython.core.extensions.ExtensionManager', allow_none=True)
401 extension_manager = Instance('IPython.core.extensions.ExtensionManager', allow_none=True)
402 payload_manager = Instance('IPython.core.payload.PayloadManager', allow_none=True)
402 payload_manager = Instance('IPython.core.payload.PayloadManager', allow_none=True)
403 history_manager = Instance('IPython.core.history.HistoryAccessorBase', allow_none=True)
403 history_manager = Instance('IPython.core.history.HistoryAccessorBase', allow_none=True)
404 magics_manager = Instance('IPython.core.magic.MagicsManager', allow_none=True)
404 magics_manager = Instance('IPython.core.magic.MagicsManager', allow_none=True)
405
405
406 profile_dir = Instance('IPython.core.application.ProfileDir', allow_none=True)
406 profile_dir = Instance('IPython.core.application.ProfileDir', allow_none=True)
407 @property
407 @property
408 def profile(self):
408 def profile(self):
409 if self.profile_dir is not None:
409 if self.profile_dir is not None:
410 name = os.path.basename(self.profile_dir.location)
410 name = os.path.basename(self.profile_dir.location)
411 return name.replace('profile_','')
411 return name.replace('profile_','')
412
412
413
413
414 # Private interface
414 # Private interface
415 _post_execute = Dict()
415 _post_execute = Dict()
416
416
417 # Tracks any GUI loop loaded for pylab
417 # Tracks any GUI loop loaded for pylab
418 pylab_gui_select = None
418 pylab_gui_select = None
419
419
420 last_execution_succeeded = Bool(True, help='Did last executed command succeeded')
420 last_execution_succeeded = Bool(True, help='Did last executed command succeeded')
421
421
422 def __init__(self, ipython_dir=None, profile_dir=None,
422 def __init__(self, ipython_dir=None, profile_dir=None,
423 user_module=None, user_ns=None,
423 user_module=None, user_ns=None,
424 custom_exceptions=((), None), **kwargs):
424 custom_exceptions=((), None), **kwargs):
425
425
426 # This is where traits with a config_key argument are updated
426 # This is where traits with a config_key argument are updated
427 # from the values on config.
427 # from the values on config.
428 super(InteractiveShell, self).__init__(**kwargs)
428 super(InteractiveShell, self).__init__(**kwargs)
429 if 'PromptManager' in self.config:
429 if 'PromptManager' in self.config:
430 warn('As of IPython 5.0 `PromptManager` config will have no effect'
430 warn('As of IPython 5.0 `PromptManager` config will have no effect'
431 ' and has been replaced by TerminalInteractiveShell.prompts_class')
431 ' and has been replaced by TerminalInteractiveShell.prompts_class')
432 self.configurables = [self]
432 self.configurables = [self]
433
433
434 # These are relatively independent and stateless
434 # These are relatively independent and stateless
435 self.init_ipython_dir(ipython_dir)
435 self.init_ipython_dir(ipython_dir)
436 self.init_profile_dir(profile_dir)
436 self.init_profile_dir(profile_dir)
437 self.init_instance_attrs()
437 self.init_instance_attrs()
438 self.init_environment()
438 self.init_environment()
439
439
440 # Check if we're in a virtualenv, and set up sys.path.
440 # Check if we're in a virtualenv, and set up sys.path.
441 self.init_virtualenv()
441 self.init_virtualenv()
442
442
443 # Create namespaces (user_ns, user_global_ns, etc.)
443 # Create namespaces (user_ns, user_global_ns, etc.)
444 self.init_create_namespaces(user_module, user_ns)
444 self.init_create_namespaces(user_module, user_ns)
445 # This has to be done after init_create_namespaces because it uses
445 # This has to be done after init_create_namespaces because it uses
446 # something in self.user_ns, but before init_sys_modules, which
446 # something in self.user_ns, but before init_sys_modules, which
447 # is the first thing to modify sys.
447 # is the first thing to modify sys.
448 # TODO: When we override sys.stdout and sys.stderr before this class
448 # TODO: When we override sys.stdout and sys.stderr before this class
449 # is created, we are saving the overridden ones here. Not sure if this
449 # is created, we are saving the overridden ones here. Not sure if this
450 # is what we want to do.
450 # is what we want to do.
451 self.save_sys_module_state()
451 self.save_sys_module_state()
452 self.init_sys_modules()
452 self.init_sys_modules()
453
453
454 # While we're trying to have each part of the code directly access what
454 # While we're trying to have each part of the code directly access what
455 # it needs without keeping redundant references to objects, we have too
455 # it needs without keeping redundant references to objects, we have too
456 # much legacy code that expects ip.db to exist.
456 # much legacy code that expects ip.db to exist.
457 self.db = PickleShareDB(os.path.join(self.profile_dir.location, 'db'))
457 self.db = PickleShareDB(os.path.join(self.profile_dir.location, 'db'))
458
458
459 self.init_history()
459 self.init_history()
460 self.init_encoding()
460 self.init_encoding()
461 self.init_prefilter()
461 self.init_prefilter()
462
462
463 self.init_syntax_highlighting()
463 self.init_syntax_highlighting()
464 self.init_hooks()
464 self.init_hooks()
465 self.init_events()
465 self.init_events()
466 self.init_pushd_popd_magic()
466 self.init_pushd_popd_magic()
467 self.init_user_ns()
467 self.init_user_ns()
468 self.init_logger()
468 self.init_logger()
469 self.init_builtins()
469 self.init_builtins()
470
470
471 # The following was in post_config_initialization
471 # The following was in post_config_initialization
472 self.init_inspector()
472 self.init_inspector()
473 self.raw_input_original = input
473 self.raw_input_original = input
474 self.init_completer()
474 self.init_completer()
475 # TODO: init_io() needs to happen before init_traceback handlers
475 # TODO: init_io() needs to happen before init_traceback handlers
476 # because the traceback handlers hardcode the stdout/stderr streams.
476 # because the traceback handlers hardcode the stdout/stderr streams.
477 # This logic in in debugger.Pdb and should eventually be changed.
477 # This logic in in debugger.Pdb and should eventually be changed.
478 self.init_io()
478 self.init_io()
479 self.init_traceback_handlers(custom_exceptions)
479 self.init_traceback_handlers(custom_exceptions)
480 self.init_prompts()
480 self.init_prompts()
481 self.init_display_formatter()
481 self.init_display_formatter()
482 self.init_display_pub()
482 self.init_display_pub()
483 self.init_data_pub()
483 self.init_data_pub()
484 self.init_displayhook()
484 self.init_displayhook()
485 self.init_magics()
485 self.init_magics()
486 self.init_alias()
486 self.init_alias()
487 self.init_logstart()
487 self.init_logstart()
488 self.init_pdb()
488 self.init_pdb()
489 self.init_extension_manager()
489 self.init_extension_manager()
490 self.init_payload()
490 self.init_payload()
491 self.init_deprecation_warnings()
491 self.init_deprecation_warnings()
492 self.hooks.late_startup_hook()
492 self.hooks.late_startup_hook()
493 self.events.trigger('shell_initialized', self)
493 self.events.trigger('shell_initialized', self)
494 atexit.register(self.atexit_operations)
494 atexit.register(self.atexit_operations)
495
495
496 def get_ipython(self):
496 def get_ipython(self):
497 """Return the currently running IPython instance."""
497 """Return the currently running IPython instance."""
498 return self
498 return self
499
499
500 #-------------------------------------------------------------------------
500 #-------------------------------------------------------------------------
501 # Trait changed handlers
501 # Trait changed handlers
502 #-------------------------------------------------------------------------
502 #-------------------------------------------------------------------------
503 @observe('ipython_dir')
503 @observe('ipython_dir')
504 def _ipython_dir_changed(self, change):
504 def _ipython_dir_changed(self, change):
505 ensure_dir_exists(change['new'])
505 ensure_dir_exists(change['new'])
506
506
507 def set_autoindent(self,value=None):
507 def set_autoindent(self,value=None):
508 """Set the autoindent flag.
508 """Set the autoindent flag.
509
509
510 If called with no arguments, it acts as a toggle."""
510 If called with no arguments, it acts as a toggle."""
511 if value is None:
511 if value is None:
512 self.autoindent = not self.autoindent
512 self.autoindent = not self.autoindent
513 else:
513 else:
514 self.autoindent = value
514 self.autoindent = value
515
515
516 #-------------------------------------------------------------------------
516 #-------------------------------------------------------------------------
517 # init_* methods called by __init__
517 # init_* methods called by __init__
518 #-------------------------------------------------------------------------
518 #-------------------------------------------------------------------------
519
519
520 def init_ipython_dir(self, ipython_dir):
520 def init_ipython_dir(self, ipython_dir):
521 if ipython_dir is not None:
521 if ipython_dir is not None:
522 self.ipython_dir = ipython_dir
522 self.ipython_dir = ipython_dir
523 return
523 return
524
524
525 self.ipython_dir = get_ipython_dir()
525 self.ipython_dir = get_ipython_dir()
526
526
527 def init_profile_dir(self, profile_dir):
527 def init_profile_dir(self, profile_dir):
528 if profile_dir is not None:
528 if profile_dir is not None:
529 self.profile_dir = profile_dir
529 self.profile_dir = profile_dir
530 return
530 return
531 self.profile_dir =\
531 self.profile_dir =\
532 ProfileDir.create_profile_dir_by_name(self.ipython_dir, 'default')
532 ProfileDir.create_profile_dir_by_name(self.ipython_dir, 'default')
533
533
534 def init_instance_attrs(self):
534 def init_instance_attrs(self):
535 self.more = False
535 self.more = False
536
536
537 # command compiler
537 # command compiler
538 self.compile = CachingCompiler()
538 self.compile = CachingCompiler()
539
539
540 # Make an empty namespace, which extension writers can rely on both
540 # Make an empty namespace, which extension writers can rely on both
541 # existing and NEVER being used by ipython itself. This gives them a
541 # existing and NEVER being used by ipython itself. This gives them a
542 # convenient location for storing additional information and state
542 # convenient location for storing additional information and state
543 # their extensions may require, without fear of collisions with other
543 # their extensions may require, without fear of collisions with other
544 # ipython names that may develop later.
544 # ipython names that may develop later.
545 self.meta = Struct()
545 self.meta = Struct()
546
546
547 # Temporary files used for various purposes. Deleted at exit.
547 # Temporary files used for various purposes. Deleted at exit.
548 self.tempfiles = []
548 self.tempfiles = []
549 self.tempdirs = []
549 self.tempdirs = []
550
550
551 # keep track of where we started running (mainly for crash post-mortem)
551 # keep track of where we started running (mainly for crash post-mortem)
552 # This is not being used anywhere currently.
552 # This is not being used anywhere currently.
553 self.starting_dir = py3compat.getcwd()
553 self.starting_dir = py3compat.getcwd()
554
554
555 # Indentation management
555 # Indentation management
556 self.indent_current_nsp = 0
556 self.indent_current_nsp = 0
557
557
558 # Dict to track post-execution functions that have been registered
558 # Dict to track post-execution functions that have been registered
559 self._post_execute = {}
559 self._post_execute = {}
560
560
561 def init_environment(self):
561 def init_environment(self):
562 """Any changes we need to make to the user's environment."""
562 """Any changes we need to make to the user's environment."""
563 pass
563 pass
564
564
565 def init_encoding(self):
565 def init_encoding(self):
566 # Get system encoding at startup time. Certain terminals (like Emacs
566 # Get system encoding at startup time. Certain terminals (like Emacs
567 # under Win32 have it set to None, and we need to have a known valid
567 # under Win32 have it set to None, and we need to have a known valid
568 # encoding to use in the raw_input() method
568 # encoding to use in the raw_input() method
569 try:
569 try:
570 self.stdin_encoding = sys.stdin.encoding or 'ascii'
570 self.stdin_encoding = sys.stdin.encoding or 'ascii'
571 except AttributeError:
571 except AttributeError:
572 self.stdin_encoding = 'ascii'
572 self.stdin_encoding = 'ascii'
573
573
574
574
575 @observe('colors')
575 @observe('colors')
576 def init_syntax_highlighting(self, changes=None):
576 def init_syntax_highlighting(self, changes=None):
577 # Python source parser/formatter for syntax highlighting
577 # Python source parser/formatter for syntax highlighting
578 pyformat = PyColorize.Parser(style=self.colors, parent=self).format
578 pyformat = PyColorize.Parser(style=self.colors, parent=self).format
579 self.pycolorize = lambda src: pyformat(src,'str')
579 self.pycolorize = lambda src: pyformat(src,'str')
580
580
581 def refresh_style(self):
581 def refresh_style(self):
582 # No-op here, used in subclass
582 # No-op here, used in subclass
583 pass
583 pass
584
584
585 def init_pushd_popd_magic(self):
585 def init_pushd_popd_magic(self):
586 # for pushd/popd management
586 # for pushd/popd management
587 self.home_dir = get_home_dir()
587 self.home_dir = get_home_dir()
588
588
589 self.dir_stack = []
589 self.dir_stack = []
590
590
591 def init_logger(self):
591 def init_logger(self):
592 self.logger = Logger(self.home_dir, logfname='ipython_log.py',
592 self.logger = Logger(self.home_dir, logfname='ipython_log.py',
593 logmode='rotate')
593 logmode='rotate')
594
594
595 def init_logstart(self):
595 def init_logstart(self):
596 """Initialize logging in case it was requested at the command line.
596 """Initialize logging in case it was requested at the command line.
597 """
597 """
598 if self.logappend:
598 if self.logappend:
599 self.magic('logstart %s append' % self.logappend)
599 self.magic('logstart %s append' % self.logappend)
600 elif self.logfile:
600 elif self.logfile:
601 self.magic('logstart %s' % self.logfile)
601 self.magic('logstart %s' % self.logfile)
602 elif self.logstart:
602 elif self.logstart:
603 self.magic('logstart')
603 self.magic('logstart')
604
604
605 def init_deprecation_warnings(self):
605 def init_deprecation_warnings(self):
606 """
606 """
607 register default filter for deprecation warning.
607 register default filter for deprecation warning.
608
608
609 This will allow deprecation warning of function used interactively to show
609 This will allow deprecation warning of function used interactively to show
610 warning to users, and still hide deprecation warning from libraries import.
610 warning to users, and still hide deprecation warning from libraries import.
611 """
611 """
612 warnings.filterwarnings("default", category=DeprecationWarning, module=self.user_ns.get("__name__"))
612 warnings.filterwarnings("default", category=DeprecationWarning, module=self.user_ns.get("__name__"))
613
613
614 def init_builtins(self):
614 def init_builtins(self):
615 # A single, static flag that we set to True. Its presence indicates
615 # A single, static flag that we set to True. Its presence indicates
616 # that an IPython shell has been created, and we make no attempts at
616 # that an IPython shell has been created, and we make no attempts at
617 # removing on exit or representing the existence of more than one
617 # removing on exit or representing the existence of more than one
618 # IPython at a time.
618 # IPython at a time.
619 builtin_mod.__dict__['__IPYTHON__'] = True
619 builtin_mod.__dict__['__IPYTHON__'] = True
620
620
621 self.builtin_trap = BuiltinTrap(shell=self)
621 self.builtin_trap = BuiltinTrap(shell=self)
622
622
623 def init_inspector(self):
623 def init_inspector(self):
624 # Object inspector
624 # Object inspector
625 self.inspector = oinspect.Inspector(oinspect.InspectColors,
625 self.inspector = oinspect.Inspector(oinspect.InspectColors,
626 PyColorize.ANSICodeColors,
626 PyColorize.ANSICodeColors,
627 'NoColor',
627 'NoColor',
628 self.object_info_string_level)
628 self.object_info_string_level)
629
629
630 def init_io(self):
630 def init_io(self):
631 # This will just use sys.stdout and sys.stderr. If you want to
631 # This will just use sys.stdout and sys.stderr. If you want to
632 # override sys.stdout and sys.stderr themselves, you need to do that
632 # override sys.stdout and sys.stderr themselves, you need to do that
633 # *before* instantiating this class, because io holds onto
633 # *before* instantiating this class, because io holds onto
634 # references to the underlying streams.
634 # references to the underlying streams.
635 # io.std* are deprecated, but don't show our own deprecation warnings
635 # io.std* are deprecated, but don't show our own deprecation warnings
636 # during initialization of the deprecated API.
636 # during initialization of the deprecated API.
637 with warnings.catch_warnings():
637 with warnings.catch_warnings():
638 warnings.simplefilter('ignore', DeprecationWarning)
638 warnings.simplefilter('ignore', DeprecationWarning)
639 io.stdout = io.IOStream(sys.stdout)
639 io.stdout = io.IOStream(sys.stdout)
640 io.stderr = io.IOStream(sys.stderr)
640 io.stderr = io.IOStream(sys.stderr)
641
641
642 def init_prompts(self):
642 def init_prompts(self):
643 # Set system prompts, so that scripts can decide if they are running
643 # Set system prompts, so that scripts can decide if they are running
644 # interactively.
644 # interactively.
645 sys.ps1 = 'In : '
645 sys.ps1 = 'In : '
646 sys.ps2 = '...: '
646 sys.ps2 = '...: '
647 sys.ps3 = 'Out: '
647 sys.ps3 = 'Out: '
648
648
649 def init_display_formatter(self):
649 def init_display_formatter(self):
650 self.display_formatter = DisplayFormatter(parent=self)
650 self.display_formatter = DisplayFormatter(parent=self)
651 self.configurables.append(self.display_formatter)
651 self.configurables.append(self.display_formatter)
652
652
653 def init_display_pub(self):
653 def init_display_pub(self):
654 self.display_pub = self.display_pub_class(parent=self)
654 self.display_pub = self.display_pub_class(parent=self)
655 self.configurables.append(self.display_pub)
655 self.configurables.append(self.display_pub)
656
656
657 def init_data_pub(self):
657 def init_data_pub(self):
658 if not self.data_pub_class:
658 if not self.data_pub_class:
659 self.data_pub = None
659 self.data_pub = None
660 return
660 return
661 self.data_pub = self.data_pub_class(parent=self)
661 self.data_pub = self.data_pub_class(parent=self)
662 self.configurables.append(self.data_pub)
662 self.configurables.append(self.data_pub)
663
663
664 def init_displayhook(self):
664 def init_displayhook(self):
665 # Initialize displayhook, set in/out prompts and printing system
665 # Initialize displayhook, set in/out prompts and printing system
666 self.displayhook = self.displayhook_class(
666 self.displayhook = self.displayhook_class(
667 parent=self,
667 parent=self,
668 shell=self,
668 shell=self,
669 cache_size=self.cache_size,
669 cache_size=self.cache_size,
670 )
670 )
671 self.configurables.append(self.displayhook)
671 self.configurables.append(self.displayhook)
672 # This is a context manager that installs/revmoes the displayhook at
672 # This is a context manager that installs/revmoes the displayhook at
673 # the appropriate time.
673 # the appropriate time.
674 self.display_trap = DisplayTrap(hook=self.displayhook)
674 self.display_trap = DisplayTrap(hook=self.displayhook)
675
675
676 def init_virtualenv(self):
676 def init_virtualenv(self):
677 """Add a virtualenv to sys.path so the user can import modules from it.
677 """Add a virtualenv to sys.path so the user can import modules from it.
678 This isn't perfect: it doesn't use the Python interpreter with which the
678 This isn't perfect: it doesn't use the Python interpreter with which the
679 virtualenv was built, and it ignores the --no-site-packages option. A
679 virtualenv was built, and it ignores the --no-site-packages option. A
680 warning will appear suggesting the user installs IPython in the
680 warning will appear suggesting the user installs IPython in the
681 virtualenv, but for many cases, it probably works well enough.
681 virtualenv, but for many cases, it probably works well enough.
682
682
683 Adapted from code snippets online.
683 Adapted from code snippets online.
684
684
685 http://blog.ufsoft.org/2009/1/29/ipython-and-virtualenv
685 http://blog.ufsoft.org/2009/1/29/ipython-and-virtualenv
686 """
686 """
687 if 'VIRTUAL_ENV' not in os.environ:
687 if 'VIRTUAL_ENV' not in os.environ:
688 # Not in a virtualenv
688 # Not in a virtualenv
689 return
689 return
690
690
691 # venv detection:
691 # venv detection:
692 # stdlib venv may symlink sys.executable, so we can't use realpath.
692 # stdlib venv may symlink sys.executable, so we can't use realpath.
693 # but others can symlink *to* the venv Python, so we can't just use sys.executable.
693 # but others can symlink *to* the venv Python, so we can't just use sys.executable.
694 # So we just check every item in the symlink tree (generally <= 3)
694 # So we just check every item in the symlink tree (generally <= 3)
695 p = os.path.normcase(sys.executable)
695 p = os.path.normcase(sys.executable)
696 paths = [p]
696 paths = [p]
697 while os.path.islink(p):
697 while os.path.islink(p):
698 p = os.path.normcase(os.path.join(os.path.dirname(p), os.readlink(p)))
698 p = os.path.normcase(os.path.join(os.path.dirname(p), os.readlink(p)))
699 paths.append(p)
699 paths.append(p)
700 p_venv = os.path.normcase(os.environ['VIRTUAL_ENV'])
700 p_venv = os.path.normcase(os.environ['VIRTUAL_ENV'])
701 if any(p.startswith(p_venv) for p in paths):
701 if any(p.startswith(p_venv) for p in paths):
702 # Running properly in the virtualenv, don't need to do anything
702 # Running properly in the virtualenv, don't need to do anything
703 return
703 return
704
704
705 warn("Attempting to work in a virtualenv. If you encounter problems, please "
705 warn("Attempting to work in a virtualenv. If you encounter problems, please "
706 "install IPython inside the virtualenv.")
706 "install IPython inside the virtualenv.")
707 if sys.platform == "win32":
707 if sys.platform == "win32":
708 virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'Lib', 'site-packages')
708 virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'Lib', 'site-packages')
709 else:
709 else:
710 virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'lib',
710 virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'lib',
711 'python%d.%d' % sys.version_info[:2], 'site-packages')
711 'python%d.%d' % sys.version_info[:2], 'site-packages')
712
712
713 import site
713 import site
714 sys.path.insert(0, virtual_env)
714 sys.path.insert(0, virtual_env)
715 site.addsitedir(virtual_env)
715 site.addsitedir(virtual_env)
716
716
717 #-------------------------------------------------------------------------
717 #-------------------------------------------------------------------------
718 # Things related to injections into the sys module
718 # Things related to injections into the sys module
719 #-------------------------------------------------------------------------
719 #-------------------------------------------------------------------------
720
720
721 def save_sys_module_state(self):
721 def save_sys_module_state(self):
722 """Save the state of hooks in the sys module.
722 """Save the state of hooks in the sys module.
723
723
724 This has to be called after self.user_module is created.
724 This has to be called after self.user_module is created.
725 """
725 """
726 self._orig_sys_module_state = {'stdin': sys.stdin,
726 self._orig_sys_module_state = {'stdin': sys.stdin,
727 'stdout': sys.stdout,
727 'stdout': sys.stdout,
728 'stderr': sys.stderr,
728 'stderr': sys.stderr,
729 'excepthook': sys.excepthook}
729 'excepthook': sys.excepthook}
730 self._orig_sys_modules_main_name = self.user_module.__name__
730 self._orig_sys_modules_main_name = self.user_module.__name__
731 self._orig_sys_modules_main_mod = sys.modules.get(self.user_module.__name__)
731 self._orig_sys_modules_main_mod = sys.modules.get(self.user_module.__name__)
732
732
733 def restore_sys_module_state(self):
733 def restore_sys_module_state(self):
734 """Restore the state of the sys module."""
734 """Restore the state of the sys module."""
735 try:
735 try:
736 for k, v in iteritems(self._orig_sys_module_state):
736 for k, v in self._orig_sys_module_state.items():
737 setattr(sys, k, v)
737 setattr(sys, k, v)
738 except AttributeError:
738 except AttributeError:
739 pass
739 pass
740 # Reset what what done in self.init_sys_modules
740 # Reset what what done in self.init_sys_modules
741 if self._orig_sys_modules_main_mod is not None:
741 if self._orig_sys_modules_main_mod is not None:
742 sys.modules[self._orig_sys_modules_main_name] = self._orig_sys_modules_main_mod
742 sys.modules[self._orig_sys_modules_main_name] = self._orig_sys_modules_main_mod
743
743
744 #-------------------------------------------------------------------------
744 #-------------------------------------------------------------------------
745 # Things related to the banner
745 # Things related to the banner
746 #-------------------------------------------------------------------------
746 #-------------------------------------------------------------------------
747
747
748 @property
748 @property
749 def banner(self):
749 def banner(self):
750 banner = self.banner1
750 banner = self.banner1
751 if self.profile and self.profile != 'default':
751 if self.profile and self.profile != 'default':
752 banner += '\nIPython profile: %s\n' % self.profile
752 banner += '\nIPython profile: %s\n' % self.profile
753 if self.banner2:
753 if self.banner2:
754 banner += '\n' + self.banner2
754 banner += '\n' + self.banner2
755 return banner
755 return banner
756
756
757 def show_banner(self, banner=None):
757 def show_banner(self, banner=None):
758 if banner is None:
758 if banner is None:
759 banner = self.banner
759 banner = self.banner
760 sys.stdout.write(banner)
760 sys.stdout.write(banner)
761
761
762 #-------------------------------------------------------------------------
762 #-------------------------------------------------------------------------
763 # Things related to hooks
763 # Things related to hooks
764 #-------------------------------------------------------------------------
764 #-------------------------------------------------------------------------
765
765
766 def init_hooks(self):
766 def init_hooks(self):
767 # hooks holds pointers used for user-side customizations
767 # hooks holds pointers used for user-side customizations
768 self.hooks = Struct()
768 self.hooks = Struct()
769
769
770 self.strdispatchers = {}
770 self.strdispatchers = {}
771
771
772 # Set all default hooks, defined in the IPython.hooks module.
772 # Set all default hooks, defined in the IPython.hooks module.
773 hooks = IPython.core.hooks
773 hooks = IPython.core.hooks
774 for hook_name in hooks.__all__:
774 for hook_name in hooks.__all__:
775 # default hooks have priority 100, i.e. low; user hooks should have
775 # default hooks have priority 100, i.e. low; user hooks should have
776 # 0-100 priority
776 # 0-100 priority
777 self.set_hook(hook_name,getattr(hooks,hook_name), 100, _warn_deprecated=False)
777 self.set_hook(hook_name,getattr(hooks,hook_name), 100, _warn_deprecated=False)
778
778
779 if self.display_page:
779 if self.display_page:
780 self.set_hook('show_in_pager', page.as_hook(page.display_page), 90)
780 self.set_hook('show_in_pager', page.as_hook(page.display_page), 90)
781
781
782 def set_hook(self,name,hook, priority=50, str_key=None, re_key=None,
782 def set_hook(self,name,hook, priority=50, str_key=None, re_key=None,
783 _warn_deprecated=True):
783 _warn_deprecated=True):
784 """set_hook(name,hook) -> sets an internal IPython hook.
784 """set_hook(name,hook) -> sets an internal IPython hook.
785
785
786 IPython exposes some of its internal API as user-modifiable hooks. By
786 IPython exposes some of its internal API as user-modifiable hooks. By
787 adding your function to one of these hooks, you can modify IPython's
787 adding your function to one of these hooks, you can modify IPython's
788 behavior to call at runtime your own routines."""
788 behavior to call at runtime your own routines."""
789
789
790 # At some point in the future, this should validate the hook before it
790 # At some point in the future, this should validate the hook before it
791 # accepts it. Probably at least check that the hook takes the number
791 # accepts it. Probably at least check that the hook takes the number
792 # of args it's supposed to.
792 # of args it's supposed to.
793
793
794 f = types.MethodType(hook,self)
794 f = types.MethodType(hook,self)
795
795
796 # check if the hook is for strdispatcher first
796 # check if the hook is for strdispatcher first
797 if str_key is not None:
797 if str_key is not None:
798 sdp = self.strdispatchers.get(name, StrDispatch())
798 sdp = self.strdispatchers.get(name, StrDispatch())
799 sdp.add_s(str_key, f, priority )
799 sdp.add_s(str_key, f, priority )
800 self.strdispatchers[name] = sdp
800 self.strdispatchers[name] = sdp
801 return
801 return
802 if re_key is not None:
802 if re_key is not None:
803 sdp = self.strdispatchers.get(name, StrDispatch())
803 sdp = self.strdispatchers.get(name, StrDispatch())
804 sdp.add_re(re.compile(re_key), f, priority )
804 sdp.add_re(re.compile(re_key), f, priority )
805 self.strdispatchers[name] = sdp
805 self.strdispatchers[name] = sdp
806 return
806 return
807
807
808 dp = getattr(self.hooks, name, None)
808 dp = getattr(self.hooks, name, None)
809 if name not in IPython.core.hooks.__all__:
809 if name not in IPython.core.hooks.__all__:
810 print("Warning! Hook '%s' is not one of %s" % \
810 print("Warning! Hook '%s' is not one of %s" % \
811 (name, IPython.core.hooks.__all__ ))
811 (name, IPython.core.hooks.__all__ ))
812
812
813 if _warn_deprecated and (name in IPython.core.hooks.deprecated):
813 if _warn_deprecated and (name in IPython.core.hooks.deprecated):
814 alternative = IPython.core.hooks.deprecated[name]
814 alternative = IPython.core.hooks.deprecated[name]
815 warn("Hook {} is deprecated. Use {} instead.".format(name, alternative), stacklevel=2)
815 warn("Hook {} is deprecated. Use {} instead.".format(name, alternative), stacklevel=2)
816
816
817 if not dp:
817 if not dp:
818 dp = IPython.core.hooks.CommandChainDispatcher()
818 dp = IPython.core.hooks.CommandChainDispatcher()
819
819
820 try:
820 try:
821 dp.add(f,priority)
821 dp.add(f,priority)
822 except AttributeError:
822 except AttributeError:
823 # it was not commandchain, plain old func - replace
823 # it was not commandchain, plain old func - replace
824 dp = f
824 dp = f
825
825
826 setattr(self.hooks,name, dp)
826 setattr(self.hooks,name, dp)
827
827
828 #-------------------------------------------------------------------------
828 #-------------------------------------------------------------------------
829 # Things related to events
829 # Things related to events
830 #-------------------------------------------------------------------------
830 #-------------------------------------------------------------------------
831
831
832 def init_events(self):
832 def init_events(self):
833 self.events = EventManager(self, available_events)
833 self.events = EventManager(self, available_events)
834
834
835 self.events.register("pre_execute", self._clear_warning_registry)
835 self.events.register("pre_execute", self._clear_warning_registry)
836
836
837 def register_post_execute(self, func):
837 def register_post_execute(self, func):
838 """DEPRECATED: Use ip.events.register('post_run_cell', func)
838 """DEPRECATED: Use ip.events.register('post_run_cell', func)
839
839
840 Register a function for calling after code execution.
840 Register a function for calling after code execution.
841 """
841 """
842 warn("ip.register_post_execute is deprecated, use "
842 warn("ip.register_post_execute is deprecated, use "
843 "ip.events.register('post_run_cell', func) instead.", stacklevel=2)
843 "ip.events.register('post_run_cell', func) instead.", stacklevel=2)
844 self.events.register('post_run_cell', func)
844 self.events.register('post_run_cell', func)
845
845
846 def _clear_warning_registry(self):
846 def _clear_warning_registry(self):
847 # clear the warning registry, so that different code blocks with
847 # clear the warning registry, so that different code blocks with
848 # overlapping line number ranges don't cause spurious suppression of
848 # overlapping line number ranges don't cause spurious suppression of
849 # warnings (see gh-6611 for details)
849 # warnings (see gh-6611 for details)
850 if "__warningregistry__" in self.user_global_ns:
850 if "__warningregistry__" in self.user_global_ns:
851 del self.user_global_ns["__warningregistry__"]
851 del self.user_global_ns["__warningregistry__"]
852
852
853 #-------------------------------------------------------------------------
853 #-------------------------------------------------------------------------
854 # Things related to the "main" module
854 # Things related to the "main" module
855 #-------------------------------------------------------------------------
855 #-------------------------------------------------------------------------
856
856
857 def new_main_mod(self, filename, modname):
857 def new_main_mod(self, filename, modname):
858 """Return a new 'main' module object for user code execution.
858 """Return a new 'main' module object for user code execution.
859
859
860 ``filename`` should be the path of the script which will be run in the
860 ``filename`` should be the path of the script which will be run in the
861 module. Requests with the same filename will get the same module, with
861 module. Requests with the same filename will get the same module, with
862 its namespace cleared.
862 its namespace cleared.
863
863
864 ``modname`` should be the module name - normally either '__main__' or
864 ``modname`` should be the module name - normally either '__main__' or
865 the basename of the file without the extension.
865 the basename of the file without the extension.
866
866
867 When scripts are executed via %run, we must keep a reference to their
867 When scripts are executed via %run, we must keep a reference to their
868 __main__ module around so that Python doesn't
868 __main__ module around so that Python doesn't
869 clear it, rendering references to module globals useless.
869 clear it, rendering references to module globals useless.
870
870
871 This method keeps said reference in a private dict, keyed by the
871 This method keeps said reference in a private dict, keyed by the
872 absolute path of the script. This way, for multiple executions of the
872 absolute path of the script. This way, for multiple executions of the
873 same script we only keep one copy of the namespace (the last one),
873 same script we only keep one copy of the namespace (the last one),
874 thus preventing memory leaks from old references while allowing the
874 thus preventing memory leaks from old references while allowing the
875 objects from the last execution to be accessible.
875 objects from the last execution to be accessible.
876 """
876 """
877 filename = os.path.abspath(filename)
877 filename = os.path.abspath(filename)
878 try:
878 try:
879 main_mod = self._main_mod_cache[filename]
879 main_mod = self._main_mod_cache[filename]
880 except KeyError:
880 except KeyError:
881 main_mod = self._main_mod_cache[filename] = types.ModuleType(
881 main_mod = self._main_mod_cache[filename] = types.ModuleType(
882 py3compat.cast_bytes_py2(modname),
882 py3compat.cast_bytes_py2(modname),
883 doc="Module created for script run in IPython")
883 doc="Module created for script run in IPython")
884 else:
884 else:
885 main_mod.__dict__.clear()
885 main_mod.__dict__.clear()
886 main_mod.__name__ = modname
886 main_mod.__name__ = modname
887
887
888 main_mod.__file__ = filename
888 main_mod.__file__ = filename
889 # It seems pydoc (and perhaps others) needs any module instance to
889 # It seems pydoc (and perhaps others) needs any module instance to
890 # implement a __nonzero__ method
890 # implement a __nonzero__ method
891 main_mod.__nonzero__ = lambda : True
891 main_mod.__nonzero__ = lambda : True
892
892
893 return main_mod
893 return main_mod
894
894
895 def clear_main_mod_cache(self):
895 def clear_main_mod_cache(self):
896 """Clear the cache of main modules.
896 """Clear the cache of main modules.
897
897
898 Mainly for use by utilities like %reset.
898 Mainly for use by utilities like %reset.
899
899
900 Examples
900 Examples
901 --------
901 --------
902
902
903 In [15]: import IPython
903 In [15]: import IPython
904
904
905 In [16]: m = _ip.new_main_mod(IPython.__file__, 'IPython')
905 In [16]: m = _ip.new_main_mod(IPython.__file__, 'IPython')
906
906
907 In [17]: len(_ip._main_mod_cache) > 0
907 In [17]: len(_ip._main_mod_cache) > 0
908 Out[17]: True
908 Out[17]: True
909
909
910 In [18]: _ip.clear_main_mod_cache()
910 In [18]: _ip.clear_main_mod_cache()
911
911
912 In [19]: len(_ip._main_mod_cache) == 0
912 In [19]: len(_ip._main_mod_cache) == 0
913 Out[19]: True
913 Out[19]: True
914 """
914 """
915 self._main_mod_cache.clear()
915 self._main_mod_cache.clear()
916
916
917 #-------------------------------------------------------------------------
917 #-------------------------------------------------------------------------
918 # Things related to debugging
918 # Things related to debugging
919 #-------------------------------------------------------------------------
919 #-------------------------------------------------------------------------
920
920
921 def init_pdb(self):
921 def init_pdb(self):
922 # Set calling of pdb on exceptions
922 # Set calling of pdb on exceptions
923 # self.call_pdb is a property
923 # self.call_pdb is a property
924 self.call_pdb = self.pdb
924 self.call_pdb = self.pdb
925
925
926 def _get_call_pdb(self):
926 def _get_call_pdb(self):
927 return self._call_pdb
927 return self._call_pdb
928
928
929 def _set_call_pdb(self,val):
929 def _set_call_pdb(self,val):
930
930
931 if val not in (0,1,False,True):
931 if val not in (0,1,False,True):
932 raise ValueError('new call_pdb value must be boolean')
932 raise ValueError('new call_pdb value must be boolean')
933
933
934 # store value in instance
934 # store value in instance
935 self._call_pdb = val
935 self._call_pdb = val
936
936
937 # notify the actual exception handlers
937 # notify the actual exception handlers
938 self.InteractiveTB.call_pdb = val
938 self.InteractiveTB.call_pdb = val
939
939
940 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
940 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
941 'Control auto-activation of pdb at exceptions')
941 'Control auto-activation of pdb at exceptions')
942
942
943 def debugger(self,force=False):
943 def debugger(self,force=False):
944 """Call the pdb debugger.
944 """Call the pdb debugger.
945
945
946 Keywords:
946 Keywords:
947
947
948 - force(False): by default, this routine checks the instance call_pdb
948 - force(False): by default, this routine checks the instance call_pdb
949 flag and does not actually invoke the debugger if the flag is false.
949 flag and does not actually invoke the debugger if the flag is false.
950 The 'force' option forces the debugger to activate even if the flag
950 The 'force' option forces the debugger to activate even if the flag
951 is false.
951 is false.
952 """
952 """
953
953
954 if not (force or self.call_pdb):
954 if not (force or self.call_pdb):
955 return
955 return
956
956
957 if not hasattr(sys,'last_traceback'):
957 if not hasattr(sys,'last_traceback'):
958 error('No traceback has been produced, nothing to debug.')
958 error('No traceback has been produced, nothing to debug.')
959 return
959 return
960
960
961 self.InteractiveTB.debugger(force=True)
961 self.InteractiveTB.debugger(force=True)
962
962
963 #-------------------------------------------------------------------------
963 #-------------------------------------------------------------------------
964 # Things related to IPython's various namespaces
964 # Things related to IPython's various namespaces
965 #-------------------------------------------------------------------------
965 #-------------------------------------------------------------------------
966 default_user_namespaces = True
966 default_user_namespaces = True
967
967
968 def init_create_namespaces(self, user_module=None, user_ns=None):
968 def init_create_namespaces(self, user_module=None, user_ns=None):
969 # Create the namespace where the user will operate. user_ns is
969 # Create the namespace where the user will operate. user_ns is
970 # normally the only one used, and it is passed to the exec calls as
970 # normally the only one used, and it is passed to the exec calls as
971 # the locals argument. But we do carry a user_global_ns namespace
971 # the locals argument. But we do carry a user_global_ns namespace
972 # given as the exec 'globals' argument, This is useful in embedding
972 # given as the exec 'globals' argument, This is useful in embedding
973 # situations where the ipython shell opens in a context where the
973 # situations where the ipython shell opens in a context where the
974 # distinction between locals and globals is meaningful. For
974 # distinction between locals and globals is meaningful. For
975 # non-embedded contexts, it is just the same object as the user_ns dict.
975 # non-embedded contexts, it is just the same object as the user_ns dict.
976
976
977 # FIXME. For some strange reason, __builtins__ is showing up at user
977 # FIXME. For some strange reason, __builtins__ is showing up at user
978 # level as a dict instead of a module. This is a manual fix, but I
978 # level as a dict instead of a module. This is a manual fix, but I
979 # should really track down where the problem is coming from. Alex
979 # should really track down where the problem is coming from. Alex
980 # Schmolck reported this problem first.
980 # Schmolck reported this problem first.
981
981
982 # A useful post by Alex Martelli on this topic:
982 # A useful post by Alex Martelli on this topic:
983 # Re: inconsistent value from __builtins__
983 # Re: inconsistent value from __builtins__
984 # Von: Alex Martelli <aleaxit@yahoo.com>
984 # Von: Alex Martelli <aleaxit@yahoo.com>
985 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
985 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
986 # Gruppen: comp.lang.python
986 # Gruppen: comp.lang.python
987
987
988 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
988 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
989 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
989 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
990 # > <type 'dict'>
990 # > <type 'dict'>
991 # > >>> print type(__builtins__)
991 # > >>> print type(__builtins__)
992 # > <type 'module'>
992 # > <type 'module'>
993 # > Is this difference in return value intentional?
993 # > Is this difference in return value intentional?
994
994
995 # Well, it's documented that '__builtins__' can be either a dictionary
995 # Well, it's documented that '__builtins__' can be either a dictionary
996 # or a module, and it's been that way for a long time. Whether it's
996 # or a module, and it's been that way for a long time. Whether it's
997 # intentional (or sensible), I don't know. In any case, the idea is
997 # intentional (or sensible), I don't know. In any case, the idea is
998 # that if you need to access the built-in namespace directly, you
998 # that if you need to access the built-in namespace directly, you
999 # should start with "import __builtin__" (note, no 's') which will
999 # should start with "import __builtin__" (note, no 's') which will
1000 # definitely give you a module. Yeah, it's somewhat confusing:-(.
1000 # definitely give you a module. Yeah, it's somewhat confusing:-(.
1001
1001
1002 # These routines return a properly built module and dict as needed by
1002 # These routines return a properly built module and dict as needed by
1003 # the rest of the code, and can also be used by extension writers to
1003 # the rest of the code, and can also be used by extension writers to
1004 # generate properly initialized namespaces.
1004 # generate properly initialized namespaces.
1005 if (user_ns is not None) or (user_module is not None):
1005 if (user_ns is not None) or (user_module is not None):
1006 self.default_user_namespaces = False
1006 self.default_user_namespaces = False
1007 self.user_module, self.user_ns = self.prepare_user_module(user_module, user_ns)
1007 self.user_module, self.user_ns = self.prepare_user_module(user_module, user_ns)
1008
1008
1009 # A record of hidden variables we have added to the user namespace, so
1009 # A record of hidden variables we have added to the user namespace, so
1010 # we can list later only variables defined in actual interactive use.
1010 # we can list later only variables defined in actual interactive use.
1011 self.user_ns_hidden = {}
1011 self.user_ns_hidden = {}
1012
1012
1013 # Now that FakeModule produces a real module, we've run into a nasty
1013 # Now that FakeModule produces a real module, we've run into a nasty
1014 # problem: after script execution (via %run), the module where the user
1014 # problem: after script execution (via %run), the module where the user
1015 # code ran is deleted. Now that this object is a true module (needed
1015 # code ran is deleted. Now that this object is a true module (needed
1016 # so doctest and other tools work correctly), the Python module
1016 # so doctest and other tools work correctly), the Python module
1017 # teardown mechanism runs over it, and sets to None every variable
1017 # teardown mechanism runs over it, and sets to None every variable
1018 # present in that module. Top-level references to objects from the
1018 # present in that module. Top-level references to objects from the
1019 # script survive, because the user_ns is updated with them. However,
1019 # script survive, because the user_ns is updated with them. However,
1020 # calling functions defined in the script that use other things from
1020 # calling functions defined in the script that use other things from
1021 # the script will fail, because the function's closure had references
1021 # the script will fail, because the function's closure had references
1022 # to the original objects, which are now all None. So we must protect
1022 # to the original objects, which are now all None. So we must protect
1023 # these modules from deletion by keeping a cache.
1023 # these modules from deletion by keeping a cache.
1024 #
1024 #
1025 # To avoid keeping stale modules around (we only need the one from the
1025 # To avoid keeping stale modules around (we only need the one from the
1026 # last run), we use a dict keyed with the full path to the script, so
1026 # last run), we use a dict keyed with the full path to the script, so
1027 # only the last version of the module is held in the cache. Note,
1027 # only the last version of the module is held in the cache. Note,
1028 # however, that we must cache the module *namespace contents* (their
1028 # however, that we must cache the module *namespace contents* (their
1029 # __dict__). Because if we try to cache the actual modules, old ones
1029 # __dict__). Because if we try to cache the actual modules, old ones
1030 # (uncached) could be destroyed while still holding references (such as
1030 # (uncached) could be destroyed while still holding references (such as
1031 # those held by GUI objects that tend to be long-lived)>
1031 # those held by GUI objects that tend to be long-lived)>
1032 #
1032 #
1033 # The %reset command will flush this cache. See the cache_main_mod()
1033 # The %reset command will flush this cache. See the cache_main_mod()
1034 # and clear_main_mod_cache() methods for details on use.
1034 # and clear_main_mod_cache() methods for details on use.
1035
1035
1036 # This is the cache used for 'main' namespaces
1036 # This is the cache used for 'main' namespaces
1037 self._main_mod_cache = {}
1037 self._main_mod_cache = {}
1038
1038
1039 # A table holding all the namespaces IPython deals with, so that
1039 # A table holding all the namespaces IPython deals with, so that
1040 # introspection facilities can search easily.
1040 # introspection facilities can search easily.
1041 self.ns_table = {'user_global':self.user_module.__dict__,
1041 self.ns_table = {'user_global':self.user_module.__dict__,
1042 'user_local':self.user_ns,
1042 'user_local':self.user_ns,
1043 'builtin':builtin_mod.__dict__
1043 'builtin':builtin_mod.__dict__
1044 }
1044 }
1045
1045
1046 @property
1046 @property
1047 def user_global_ns(self):
1047 def user_global_ns(self):
1048 return self.user_module.__dict__
1048 return self.user_module.__dict__
1049
1049
1050 def prepare_user_module(self, user_module=None, user_ns=None):
1050 def prepare_user_module(self, user_module=None, user_ns=None):
1051 """Prepare the module and namespace in which user code will be run.
1051 """Prepare the module and namespace in which user code will be run.
1052
1052
1053 When IPython is started normally, both parameters are None: a new module
1053 When IPython is started normally, both parameters are None: a new module
1054 is created automatically, and its __dict__ used as the namespace.
1054 is created automatically, and its __dict__ used as the namespace.
1055
1055
1056 If only user_module is provided, its __dict__ is used as the namespace.
1056 If only user_module is provided, its __dict__ is used as the namespace.
1057 If only user_ns is provided, a dummy module is created, and user_ns
1057 If only user_ns is provided, a dummy module is created, and user_ns
1058 becomes the global namespace. If both are provided (as they may be
1058 becomes the global namespace. If both are provided (as they may be
1059 when embedding), user_ns is the local namespace, and user_module
1059 when embedding), user_ns is the local namespace, and user_module
1060 provides the global namespace.
1060 provides the global namespace.
1061
1061
1062 Parameters
1062 Parameters
1063 ----------
1063 ----------
1064 user_module : module, optional
1064 user_module : module, optional
1065 The current user module in which IPython is being run. If None,
1065 The current user module in which IPython is being run. If None,
1066 a clean module will be created.
1066 a clean module will be created.
1067 user_ns : dict, optional
1067 user_ns : dict, optional
1068 A namespace in which to run interactive commands.
1068 A namespace in which to run interactive commands.
1069
1069
1070 Returns
1070 Returns
1071 -------
1071 -------
1072 A tuple of user_module and user_ns, each properly initialised.
1072 A tuple of user_module and user_ns, each properly initialised.
1073 """
1073 """
1074 if user_module is None and user_ns is not None:
1074 if user_module is None and user_ns is not None:
1075 user_ns.setdefault("__name__", "__main__")
1075 user_ns.setdefault("__name__", "__main__")
1076 user_module = DummyMod()
1076 user_module = DummyMod()
1077 user_module.__dict__ = user_ns
1077 user_module.__dict__ = user_ns
1078
1078
1079 if user_module is None:
1079 if user_module is None:
1080 user_module = types.ModuleType("__main__",
1080 user_module = types.ModuleType("__main__",
1081 doc="Automatically created module for IPython interactive environment")
1081 doc="Automatically created module for IPython interactive environment")
1082
1082
1083 # We must ensure that __builtin__ (without the final 's') is always
1083 # We must ensure that __builtin__ (without the final 's') is always
1084 # available and pointing to the __builtin__ *module*. For more details:
1084 # available and pointing to the __builtin__ *module*. For more details:
1085 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1085 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1086 user_module.__dict__.setdefault('__builtin__', builtin_mod)
1086 user_module.__dict__.setdefault('__builtin__', builtin_mod)
1087 user_module.__dict__.setdefault('__builtins__', builtin_mod)
1087 user_module.__dict__.setdefault('__builtins__', builtin_mod)
1088
1088
1089 if user_ns is None:
1089 if user_ns is None:
1090 user_ns = user_module.__dict__
1090 user_ns = user_module.__dict__
1091
1091
1092 return user_module, user_ns
1092 return user_module, user_ns
1093
1093
1094 def init_sys_modules(self):
1094 def init_sys_modules(self):
1095 # We need to insert into sys.modules something that looks like a
1095 # We need to insert into sys.modules something that looks like a
1096 # module but which accesses the IPython namespace, for shelve and
1096 # module but which accesses the IPython namespace, for shelve and
1097 # pickle to work interactively. Normally they rely on getting
1097 # pickle to work interactively. Normally they rely on getting
1098 # everything out of __main__, but for embedding purposes each IPython
1098 # everything out of __main__, but for embedding purposes each IPython
1099 # instance has its own private namespace, so we can't go shoving
1099 # instance has its own private namespace, so we can't go shoving
1100 # everything into __main__.
1100 # everything into __main__.
1101
1101
1102 # note, however, that we should only do this for non-embedded
1102 # note, however, that we should only do this for non-embedded
1103 # ipythons, which really mimic the __main__.__dict__ with their own
1103 # ipythons, which really mimic the __main__.__dict__ with their own
1104 # namespace. Embedded instances, on the other hand, should not do
1104 # namespace. Embedded instances, on the other hand, should not do
1105 # this because they need to manage the user local/global namespaces
1105 # this because they need to manage the user local/global namespaces
1106 # only, but they live within a 'normal' __main__ (meaning, they
1106 # only, but they live within a 'normal' __main__ (meaning, they
1107 # shouldn't overtake the execution environment of the script they're
1107 # shouldn't overtake the execution environment of the script they're
1108 # embedded in).
1108 # embedded in).
1109
1109
1110 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
1110 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
1111 main_name = self.user_module.__name__
1111 main_name = self.user_module.__name__
1112 sys.modules[main_name] = self.user_module
1112 sys.modules[main_name] = self.user_module
1113
1113
1114 def init_user_ns(self):
1114 def init_user_ns(self):
1115 """Initialize all user-visible namespaces to their minimum defaults.
1115 """Initialize all user-visible namespaces to their minimum defaults.
1116
1116
1117 Certain history lists are also initialized here, as they effectively
1117 Certain history lists are also initialized here, as they effectively
1118 act as user namespaces.
1118 act as user namespaces.
1119
1119
1120 Notes
1120 Notes
1121 -----
1121 -----
1122 All data structures here are only filled in, they are NOT reset by this
1122 All data structures here are only filled in, they are NOT reset by this
1123 method. If they were not empty before, data will simply be added to
1123 method. If they were not empty before, data will simply be added to
1124 therm.
1124 therm.
1125 """
1125 """
1126 # This function works in two parts: first we put a few things in
1126 # This function works in two parts: first we put a few things in
1127 # user_ns, and we sync that contents into user_ns_hidden so that these
1127 # user_ns, and we sync that contents into user_ns_hidden so that these
1128 # initial variables aren't shown by %who. After the sync, we add the
1128 # initial variables aren't shown by %who. After the sync, we add the
1129 # rest of what we *do* want the user to see with %who even on a new
1129 # rest of what we *do* want the user to see with %who even on a new
1130 # session (probably nothing, so they really only see their own stuff)
1130 # session (probably nothing, so they really only see their own stuff)
1131
1131
1132 # The user dict must *always* have a __builtin__ reference to the
1132 # The user dict must *always* have a __builtin__ reference to the
1133 # Python standard __builtin__ namespace, which must be imported.
1133 # Python standard __builtin__ namespace, which must be imported.
1134 # This is so that certain operations in prompt evaluation can be
1134 # This is so that certain operations in prompt evaluation can be
1135 # reliably executed with builtins. Note that we can NOT use
1135 # reliably executed with builtins. Note that we can NOT use
1136 # __builtins__ (note the 's'), because that can either be a dict or a
1136 # __builtins__ (note the 's'), because that can either be a dict or a
1137 # module, and can even mutate at runtime, depending on the context
1137 # module, and can even mutate at runtime, depending on the context
1138 # (Python makes no guarantees on it). In contrast, __builtin__ is
1138 # (Python makes no guarantees on it). In contrast, __builtin__ is
1139 # always a module object, though it must be explicitly imported.
1139 # always a module object, though it must be explicitly imported.
1140
1140
1141 # For more details:
1141 # For more details:
1142 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1142 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1143 ns = dict()
1143 ns = dict()
1144
1144
1145 # make global variables for user access to the histories
1145 # make global variables for user access to the histories
1146 ns['_ih'] = self.history_manager.input_hist_parsed
1146 ns['_ih'] = self.history_manager.input_hist_parsed
1147 ns['_oh'] = self.history_manager.output_hist
1147 ns['_oh'] = self.history_manager.output_hist
1148 ns['_dh'] = self.history_manager.dir_hist
1148 ns['_dh'] = self.history_manager.dir_hist
1149
1149
1150 ns['_sh'] = shadowns
1150 ns['_sh'] = shadowns
1151
1151
1152 # user aliases to input and output histories. These shouldn't show up
1152 # user aliases to input and output histories. These shouldn't show up
1153 # in %who, as they can have very large reprs.
1153 # in %who, as they can have very large reprs.
1154 ns['In'] = self.history_manager.input_hist_parsed
1154 ns['In'] = self.history_manager.input_hist_parsed
1155 ns['Out'] = self.history_manager.output_hist
1155 ns['Out'] = self.history_manager.output_hist
1156
1156
1157 # Store myself as the public api!!!
1157 # Store myself as the public api!!!
1158 ns['get_ipython'] = self.get_ipython
1158 ns['get_ipython'] = self.get_ipython
1159
1159
1160 ns['exit'] = self.exiter
1160 ns['exit'] = self.exiter
1161 ns['quit'] = self.exiter
1161 ns['quit'] = self.exiter
1162
1162
1163 # Sync what we've added so far to user_ns_hidden so these aren't seen
1163 # Sync what we've added so far to user_ns_hidden so these aren't seen
1164 # by %who
1164 # by %who
1165 self.user_ns_hidden.update(ns)
1165 self.user_ns_hidden.update(ns)
1166
1166
1167 # Anything put into ns now would show up in %who. Think twice before
1167 # Anything put into ns now would show up in %who. Think twice before
1168 # putting anything here, as we really want %who to show the user their
1168 # putting anything here, as we really want %who to show the user their
1169 # stuff, not our variables.
1169 # stuff, not our variables.
1170
1170
1171 # Finally, update the real user's namespace
1171 # Finally, update the real user's namespace
1172 self.user_ns.update(ns)
1172 self.user_ns.update(ns)
1173
1173
1174 @property
1174 @property
1175 def all_ns_refs(self):
1175 def all_ns_refs(self):
1176 """Get a list of references to all the namespace dictionaries in which
1176 """Get a list of references to all the namespace dictionaries in which
1177 IPython might store a user-created object.
1177 IPython might store a user-created object.
1178
1178
1179 Note that this does not include the displayhook, which also caches
1179 Note that this does not include the displayhook, which also caches
1180 objects from the output."""
1180 objects from the output."""
1181 return [self.user_ns, self.user_global_ns, self.user_ns_hidden] + \
1181 return [self.user_ns, self.user_global_ns, self.user_ns_hidden] + \
1182 [m.__dict__ for m in self._main_mod_cache.values()]
1182 [m.__dict__ for m in self._main_mod_cache.values()]
1183
1183
1184 def reset(self, new_session=True):
1184 def reset(self, new_session=True):
1185 """Clear all internal namespaces, and attempt to release references to
1185 """Clear all internal namespaces, and attempt to release references to
1186 user objects.
1186 user objects.
1187
1187
1188 If new_session is True, a new history session will be opened.
1188 If new_session is True, a new history session will be opened.
1189 """
1189 """
1190 # Clear histories
1190 # Clear histories
1191 self.history_manager.reset(new_session)
1191 self.history_manager.reset(new_session)
1192 # Reset counter used to index all histories
1192 # Reset counter used to index all histories
1193 if new_session:
1193 if new_session:
1194 self.execution_count = 1
1194 self.execution_count = 1
1195
1195
1196 # Flush cached output items
1196 # Flush cached output items
1197 if self.displayhook.do_full_cache:
1197 if self.displayhook.do_full_cache:
1198 self.displayhook.flush()
1198 self.displayhook.flush()
1199
1199
1200 # The main execution namespaces must be cleared very carefully,
1200 # The main execution namespaces must be cleared very carefully,
1201 # skipping the deletion of the builtin-related keys, because doing so
1201 # skipping the deletion of the builtin-related keys, because doing so
1202 # would cause errors in many object's __del__ methods.
1202 # would cause errors in many object's __del__ methods.
1203 if self.user_ns is not self.user_global_ns:
1203 if self.user_ns is not self.user_global_ns:
1204 self.user_ns.clear()
1204 self.user_ns.clear()
1205 ns = self.user_global_ns
1205 ns = self.user_global_ns
1206 drop_keys = set(ns.keys())
1206 drop_keys = set(ns.keys())
1207 drop_keys.discard('__builtin__')
1207 drop_keys.discard('__builtin__')
1208 drop_keys.discard('__builtins__')
1208 drop_keys.discard('__builtins__')
1209 drop_keys.discard('__name__')
1209 drop_keys.discard('__name__')
1210 for k in drop_keys:
1210 for k in drop_keys:
1211 del ns[k]
1211 del ns[k]
1212
1212
1213 self.user_ns_hidden.clear()
1213 self.user_ns_hidden.clear()
1214
1214
1215 # Restore the user namespaces to minimal usability
1215 # Restore the user namespaces to minimal usability
1216 self.init_user_ns()
1216 self.init_user_ns()
1217
1217
1218 # Restore the default and user aliases
1218 # Restore the default and user aliases
1219 self.alias_manager.clear_aliases()
1219 self.alias_manager.clear_aliases()
1220 self.alias_manager.init_aliases()
1220 self.alias_manager.init_aliases()
1221
1221
1222 # Flush the private list of module references kept for script
1222 # Flush the private list of module references kept for script
1223 # execution protection
1223 # execution protection
1224 self.clear_main_mod_cache()
1224 self.clear_main_mod_cache()
1225
1225
1226 def del_var(self, varname, by_name=False):
1226 def del_var(self, varname, by_name=False):
1227 """Delete a variable from the various namespaces, so that, as
1227 """Delete a variable from the various namespaces, so that, as
1228 far as possible, we're not keeping any hidden references to it.
1228 far as possible, we're not keeping any hidden references to it.
1229
1229
1230 Parameters
1230 Parameters
1231 ----------
1231 ----------
1232 varname : str
1232 varname : str
1233 The name of the variable to delete.
1233 The name of the variable to delete.
1234 by_name : bool
1234 by_name : bool
1235 If True, delete variables with the given name in each
1235 If True, delete variables with the given name in each
1236 namespace. If False (default), find the variable in the user
1236 namespace. If False (default), find the variable in the user
1237 namespace, and delete references to it.
1237 namespace, and delete references to it.
1238 """
1238 """
1239 if varname in ('__builtin__', '__builtins__'):
1239 if varname in ('__builtin__', '__builtins__'):
1240 raise ValueError("Refusing to delete %s" % varname)
1240 raise ValueError("Refusing to delete %s" % varname)
1241
1241
1242 ns_refs = self.all_ns_refs
1242 ns_refs = self.all_ns_refs
1243
1243
1244 if by_name: # Delete by name
1244 if by_name: # Delete by name
1245 for ns in ns_refs:
1245 for ns in ns_refs:
1246 try:
1246 try:
1247 del ns[varname]
1247 del ns[varname]
1248 except KeyError:
1248 except KeyError:
1249 pass
1249 pass
1250 else: # Delete by object
1250 else: # Delete by object
1251 try:
1251 try:
1252 obj = self.user_ns[varname]
1252 obj = self.user_ns[varname]
1253 except KeyError:
1253 except KeyError:
1254 raise NameError("name '%s' is not defined" % varname)
1254 raise NameError("name '%s' is not defined" % varname)
1255 # Also check in output history
1255 # Also check in output history
1256 ns_refs.append(self.history_manager.output_hist)
1256 ns_refs.append(self.history_manager.output_hist)
1257 for ns in ns_refs:
1257 for ns in ns_refs:
1258 to_delete = [n for n, o in iteritems(ns) if o is obj]
1258 to_delete = [n for n, o in ns.items() if o is obj]
1259 for name in to_delete:
1259 for name in to_delete:
1260 del ns[name]
1260 del ns[name]
1261
1261
1262 # displayhook keeps extra references, but not in a dictionary
1262 # displayhook keeps extra references, but not in a dictionary
1263 for name in ('_', '__', '___'):
1263 for name in ('_', '__', '___'):
1264 if getattr(self.displayhook, name) is obj:
1264 if getattr(self.displayhook, name) is obj:
1265 setattr(self.displayhook, name, None)
1265 setattr(self.displayhook, name, None)
1266
1266
1267 def reset_selective(self, regex=None):
1267 def reset_selective(self, regex=None):
1268 """Clear selective variables from internal namespaces based on a
1268 """Clear selective variables from internal namespaces based on a
1269 specified regular expression.
1269 specified regular expression.
1270
1270
1271 Parameters
1271 Parameters
1272 ----------
1272 ----------
1273 regex : string or compiled pattern, optional
1273 regex : string or compiled pattern, optional
1274 A regular expression pattern that will be used in searching
1274 A regular expression pattern that will be used in searching
1275 variable names in the users namespaces.
1275 variable names in the users namespaces.
1276 """
1276 """
1277 if regex is not None:
1277 if regex is not None:
1278 try:
1278 try:
1279 m = re.compile(regex)
1279 m = re.compile(regex)
1280 except TypeError:
1280 except TypeError:
1281 raise TypeError('regex must be a string or compiled pattern')
1281 raise TypeError('regex must be a string or compiled pattern')
1282 # Search for keys in each namespace that match the given regex
1282 # Search for keys in each namespace that match the given regex
1283 # If a match is found, delete the key/value pair.
1283 # If a match is found, delete the key/value pair.
1284 for ns in self.all_ns_refs:
1284 for ns in self.all_ns_refs:
1285 for var in ns:
1285 for var in ns:
1286 if m.search(var):
1286 if m.search(var):
1287 del ns[var]
1287 del ns[var]
1288
1288
1289 def push(self, variables, interactive=True):
1289 def push(self, variables, interactive=True):
1290 """Inject a group of variables into the IPython user namespace.
1290 """Inject a group of variables into the IPython user namespace.
1291
1291
1292 Parameters
1292 Parameters
1293 ----------
1293 ----------
1294 variables : dict, str or list/tuple of str
1294 variables : dict, str or list/tuple of str
1295 The variables to inject into the user's namespace. If a dict, a
1295 The variables to inject into the user's namespace. If a dict, a
1296 simple update is done. If a str, the string is assumed to have
1296 simple update is done. If a str, the string is assumed to have
1297 variable names separated by spaces. A list/tuple of str can also
1297 variable names separated by spaces. A list/tuple of str can also
1298 be used to give the variable names. If just the variable names are
1298 be used to give the variable names. If just the variable names are
1299 give (list/tuple/str) then the variable values looked up in the
1299 give (list/tuple/str) then the variable values looked up in the
1300 callers frame.
1300 callers frame.
1301 interactive : bool
1301 interactive : bool
1302 If True (default), the variables will be listed with the ``who``
1302 If True (default), the variables will be listed with the ``who``
1303 magic.
1303 magic.
1304 """
1304 """
1305 vdict = None
1305 vdict = None
1306
1306
1307 # We need a dict of name/value pairs to do namespace updates.
1307 # We need a dict of name/value pairs to do namespace updates.
1308 if isinstance(variables, dict):
1308 if isinstance(variables, dict):
1309 vdict = variables
1309 vdict = variables
1310 elif isinstance(variables, string_types+(list, tuple)):
1310 elif isinstance(variables, string_types+(list, tuple)):
1311 if isinstance(variables, string_types):
1311 if isinstance(variables, string_types):
1312 vlist = variables.split()
1312 vlist = variables.split()
1313 else:
1313 else:
1314 vlist = variables
1314 vlist = variables
1315 vdict = {}
1315 vdict = {}
1316 cf = sys._getframe(1)
1316 cf = sys._getframe(1)
1317 for name in vlist:
1317 for name in vlist:
1318 try:
1318 try:
1319 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1319 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1320 except:
1320 except:
1321 print('Could not get variable %s from %s' %
1321 print('Could not get variable %s from %s' %
1322 (name,cf.f_code.co_name))
1322 (name,cf.f_code.co_name))
1323 else:
1323 else:
1324 raise ValueError('variables must be a dict/str/list/tuple')
1324 raise ValueError('variables must be a dict/str/list/tuple')
1325
1325
1326 # Propagate variables to user namespace
1326 # Propagate variables to user namespace
1327 self.user_ns.update(vdict)
1327 self.user_ns.update(vdict)
1328
1328
1329 # And configure interactive visibility
1329 # And configure interactive visibility
1330 user_ns_hidden = self.user_ns_hidden
1330 user_ns_hidden = self.user_ns_hidden
1331 if interactive:
1331 if interactive:
1332 for name in vdict:
1332 for name in vdict:
1333 user_ns_hidden.pop(name, None)
1333 user_ns_hidden.pop(name, None)
1334 else:
1334 else:
1335 user_ns_hidden.update(vdict)
1335 user_ns_hidden.update(vdict)
1336
1336
1337 def drop_by_id(self, variables):
1337 def drop_by_id(self, variables):
1338 """Remove a dict of variables from the user namespace, if they are the
1338 """Remove a dict of variables from the user namespace, if they are the
1339 same as the values in the dictionary.
1339 same as the values in the dictionary.
1340
1340
1341 This is intended for use by extensions: variables that they've added can
1341 This is intended for use by extensions: variables that they've added can
1342 be taken back out if they are unloaded, without removing any that the
1342 be taken back out if they are unloaded, without removing any that the
1343 user has overwritten.
1343 user has overwritten.
1344
1344
1345 Parameters
1345 Parameters
1346 ----------
1346 ----------
1347 variables : dict
1347 variables : dict
1348 A dictionary mapping object names (as strings) to the objects.
1348 A dictionary mapping object names (as strings) to the objects.
1349 """
1349 """
1350 for name, obj in iteritems(variables):
1350 for name, obj in variables.items():
1351 if name in self.user_ns and self.user_ns[name] is obj:
1351 if name in self.user_ns and self.user_ns[name] is obj:
1352 del self.user_ns[name]
1352 del self.user_ns[name]
1353 self.user_ns_hidden.pop(name, None)
1353 self.user_ns_hidden.pop(name, None)
1354
1354
1355 #-------------------------------------------------------------------------
1355 #-------------------------------------------------------------------------
1356 # Things related to object introspection
1356 # Things related to object introspection
1357 #-------------------------------------------------------------------------
1357 #-------------------------------------------------------------------------
1358
1358
1359 def _ofind(self, oname, namespaces=None):
1359 def _ofind(self, oname, namespaces=None):
1360 """Find an object in the available namespaces.
1360 """Find an object in the available namespaces.
1361
1361
1362 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
1362 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
1363
1363
1364 Has special code to detect magic functions.
1364 Has special code to detect magic functions.
1365 """
1365 """
1366 oname = oname.strip()
1366 oname = oname.strip()
1367 #print '1- oname: <%r>' % oname # dbg
1367 #print '1- oname: <%r>' % oname # dbg
1368 if not oname.startswith(ESC_MAGIC) and \
1368 if not oname.startswith(ESC_MAGIC) and \
1369 not oname.startswith(ESC_MAGIC2) and \
1369 not oname.startswith(ESC_MAGIC2) and \
1370 not py3compat.isidentifier(oname, dotted=True):
1370 not py3compat.isidentifier(oname, dotted=True):
1371 return dict(found=False)
1371 return dict(found=False)
1372
1372
1373 if namespaces is None:
1373 if namespaces is None:
1374 # Namespaces to search in:
1374 # Namespaces to search in:
1375 # Put them in a list. The order is important so that we
1375 # Put them in a list. The order is important so that we
1376 # find things in the same order that Python finds them.
1376 # find things in the same order that Python finds them.
1377 namespaces = [ ('Interactive', self.user_ns),
1377 namespaces = [ ('Interactive', self.user_ns),
1378 ('Interactive (global)', self.user_global_ns),
1378 ('Interactive (global)', self.user_global_ns),
1379 ('Python builtin', builtin_mod.__dict__),
1379 ('Python builtin', builtin_mod.__dict__),
1380 ]
1380 ]
1381
1381
1382 # initialize results to 'null'
1382 # initialize results to 'null'
1383 found = False; obj = None; ospace = None;
1383 found = False; obj = None; ospace = None;
1384 ismagic = False; isalias = False; parent = None
1384 ismagic = False; isalias = False; parent = None
1385
1385
1386 # We need to special-case 'print', which as of python2.6 registers as a
1386 # We need to special-case 'print', which as of python2.6 registers as a
1387 # function but should only be treated as one if print_function was
1387 # function but should only be treated as one if print_function was
1388 # loaded with a future import. In this case, just bail.
1388 # loaded with a future import. In this case, just bail.
1389 if (oname == 'print' and not py3compat.PY3 and not \
1389 if (oname == 'print' and not py3compat.PY3 and not \
1390 (self.compile.compiler_flags & __future__.CO_FUTURE_PRINT_FUNCTION)):
1390 (self.compile.compiler_flags & __future__.CO_FUTURE_PRINT_FUNCTION)):
1391 return {'found':found, 'obj':obj, 'namespace':ospace,
1391 return {'found':found, 'obj':obj, 'namespace':ospace,
1392 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1392 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1393
1393
1394 # Look for the given name by splitting it in parts. If the head is
1394 # Look for the given name by splitting it in parts. If the head is
1395 # found, then we look for all the remaining parts as members, and only
1395 # found, then we look for all the remaining parts as members, and only
1396 # declare success if we can find them all.
1396 # declare success if we can find them all.
1397 oname_parts = oname.split('.')
1397 oname_parts = oname.split('.')
1398 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
1398 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
1399 for nsname,ns in namespaces:
1399 for nsname,ns in namespaces:
1400 try:
1400 try:
1401 obj = ns[oname_head]
1401 obj = ns[oname_head]
1402 except KeyError:
1402 except KeyError:
1403 continue
1403 continue
1404 else:
1404 else:
1405 #print 'oname_rest:', oname_rest # dbg
1405 #print 'oname_rest:', oname_rest # dbg
1406 for idx, part in enumerate(oname_rest):
1406 for idx, part in enumerate(oname_rest):
1407 try:
1407 try:
1408 parent = obj
1408 parent = obj
1409 # The last part is looked up in a special way to avoid
1409 # The last part is looked up in a special way to avoid
1410 # descriptor invocation as it may raise or have side
1410 # descriptor invocation as it may raise or have side
1411 # effects.
1411 # effects.
1412 if idx == len(oname_rest) - 1:
1412 if idx == len(oname_rest) - 1:
1413 obj = self._getattr_property(obj, part)
1413 obj = self._getattr_property(obj, part)
1414 else:
1414 else:
1415 obj = getattr(obj, part)
1415 obj = getattr(obj, part)
1416 except:
1416 except:
1417 # Blanket except b/c some badly implemented objects
1417 # Blanket except b/c some badly implemented objects
1418 # allow __getattr__ to raise exceptions other than
1418 # allow __getattr__ to raise exceptions other than
1419 # AttributeError, which then crashes IPython.
1419 # AttributeError, which then crashes IPython.
1420 break
1420 break
1421 else:
1421 else:
1422 # If we finish the for loop (no break), we got all members
1422 # If we finish the for loop (no break), we got all members
1423 found = True
1423 found = True
1424 ospace = nsname
1424 ospace = nsname
1425 break # namespace loop
1425 break # namespace loop
1426
1426
1427 # Try to see if it's magic
1427 # Try to see if it's magic
1428 if not found:
1428 if not found:
1429 obj = None
1429 obj = None
1430 if oname.startswith(ESC_MAGIC2):
1430 if oname.startswith(ESC_MAGIC2):
1431 oname = oname.lstrip(ESC_MAGIC2)
1431 oname = oname.lstrip(ESC_MAGIC2)
1432 obj = self.find_cell_magic(oname)
1432 obj = self.find_cell_magic(oname)
1433 elif oname.startswith(ESC_MAGIC):
1433 elif oname.startswith(ESC_MAGIC):
1434 oname = oname.lstrip(ESC_MAGIC)
1434 oname = oname.lstrip(ESC_MAGIC)
1435 obj = self.find_line_magic(oname)
1435 obj = self.find_line_magic(oname)
1436 else:
1436 else:
1437 # search without prefix, so run? will find %run?
1437 # search without prefix, so run? will find %run?
1438 obj = self.find_line_magic(oname)
1438 obj = self.find_line_magic(oname)
1439 if obj is None:
1439 if obj is None:
1440 obj = self.find_cell_magic(oname)
1440 obj = self.find_cell_magic(oname)
1441 if obj is not None:
1441 if obj is not None:
1442 found = True
1442 found = True
1443 ospace = 'IPython internal'
1443 ospace = 'IPython internal'
1444 ismagic = True
1444 ismagic = True
1445 isalias = isinstance(obj, Alias)
1445 isalias = isinstance(obj, Alias)
1446
1446
1447 # Last try: special-case some literals like '', [], {}, etc:
1447 # Last try: special-case some literals like '', [], {}, etc:
1448 if not found and oname_head in ["''",'""','[]','{}','()']:
1448 if not found and oname_head in ["''",'""','[]','{}','()']:
1449 obj = eval(oname_head)
1449 obj = eval(oname_head)
1450 found = True
1450 found = True
1451 ospace = 'Interactive'
1451 ospace = 'Interactive'
1452
1452
1453 return {'found':found, 'obj':obj, 'namespace':ospace,
1453 return {'found':found, 'obj':obj, 'namespace':ospace,
1454 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1454 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1455
1455
1456 @staticmethod
1456 @staticmethod
1457 def _getattr_property(obj, attrname):
1457 def _getattr_property(obj, attrname):
1458 """Property-aware getattr to use in object finding.
1458 """Property-aware getattr to use in object finding.
1459
1459
1460 If attrname represents a property, return it unevaluated (in case it has
1460 If attrname represents a property, return it unevaluated (in case it has
1461 side effects or raises an error.
1461 side effects or raises an error.
1462
1462
1463 """
1463 """
1464 if not isinstance(obj, type):
1464 if not isinstance(obj, type):
1465 try:
1465 try:
1466 # `getattr(type(obj), attrname)` is not guaranteed to return
1466 # `getattr(type(obj), attrname)` is not guaranteed to return
1467 # `obj`, but does so for property:
1467 # `obj`, but does so for property:
1468 #
1468 #
1469 # property.__get__(self, None, cls) -> self
1469 # property.__get__(self, None, cls) -> self
1470 #
1470 #
1471 # The universal alternative is to traverse the mro manually
1471 # The universal alternative is to traverse the mro manually
1472 # searching for attrname in class dicts.
1472 # searching for attrname in class dicts.
1473 attr = getattr(type(obj), attrname)
1473 attr = getattr(type(obj), attrname)
1474 except AttributeError:
1474 except AttributeError:
1475 pass
1475 pass
1476 else:
1476 else:
1477 # This relies on the fact that data descriptors (with both
1477 # This relies on the fact that data descriptors (with both
1478 # __get__ & __set__ magic methods) take precedence over
1478 # __get__ & __set__ magic methods) take precedence over
1479 # instance-level attributes:
1479 # instance-level attributes:
1480 #
1480 #
1481 # class A(object):
1481 # class A(object):
1482 # @property
1482 # @property
1483 # def foobar(self): return 123
1483 # def foobar(self): return 123
1484 # a = A()
1484 # a = A()
1485 # a.__dict__['foobar'] = 345
1485 # a.__dict__['foobar'] = 345
1486 # a.foobar # == 123
1486 # a.foobar # == 123
1487 #
1487 #
1488 # So, a property may be returned right away.
1488 # So, a property may be returned right away.
1489 if isinstance(attr, property):
1489 if isinstance(attr, property):
1490 return attr
1490 return attr
1491
1491
1492 # Nothing helped, fall back.
1492 # Nothing helped, fall back.
1493 return getattr(obj, attrname)
1493 return getattr(obj, attrname)
1494
1494
1495 def _object_find(self, oname, namespaces=None):
1495 def _object_find(self, oname, namespaces=None):
1496 """Find an object and return a struct with info about it."""
1496 """Find an object and return a struct with info about it."""
1497 return Struct(self._ofind(oname, namespaces))
1497 return Struct(self._ofind(oname, namespaces))
1498
1498
1499 def _inspect(self, meth, oname, namespaces=None, **kw):
1499 def _inspect(self, meth, oname, namespaces=None, **kw):
1500 """Generic interface to the inspector system.
1500 """Generic interface to the inspector system.
1501
1501
1502 This function is meant to be called by pdef, pdoc & friends.
1502 This function is meant to be called by pdef, pdoc & friends.
1503 """
1503 """
1504 info = self._object_find(oname, namespaces)
1504 info = self._object_find(oname, namespaces)
1505 docformat = sphinxify if self.sphinxify_docstring else None
1505 docformat = sphinxify if self.sphinxify_docstring else None
1506 if info.found:
1506 if info.found:
1507 pmethod = getattr(self.inspector, meth)
1507 pmethod = getattr(self.inspector, meth)
1508 # TODO: only apply format_screen to the plain/text repr of the mime
1508 # TODO: only apply format_screen to the plain/text repr of the mime
1509 # bundle.
1509 # bundle.
1510 formatter = format_screen if info.ismagic else docformat
1510 formatter = format_screen if info.ismagic else docformat
1511 if meth == 'pdoc':
1511 if meth == 'pdoc':
1512 pmethod(info.obj, oname, formatter)
1512 pmethod(info.obj, oname, formatter)
1513 elif meth == 'pinfo':
1513 elif meth == 'pinfo':
1514 pmethod(info.obj, oname, formatter, info,
1514 pmethod(info.obj, oname, formatter, info,
1515 enable_html_pager=self.enable_html_pager, **kw)
1515 enable_html_pager=self.enable_html_pager, **kw)
1516 else:
1516 else:
1517 pmethod(info.obj, oname)
1517 pmethod(info.obj, oname)
1518 else:
1518 else:
1519 print('Object `%s` not found.' % oname)
1519 print('Object `%s` not found.' % oname)
1520 return 'not found' # so callers can take other action
1520 return 'not found' # so callers can take other action
1521
1521
1522 def object_inspect(self, oname, detail_level=0):
1522 def object_inspect(self, oname, detail_level=0):
1523 """Get object info about oname"""
1523 """Get object info about oname"""
1524 with self.builtin_trap:
1524 with self.builtin_trap:
1525 info = self._object_find(oname)
1525 info = self._object_find(oname)
1526 if info.found:
1526 if info.found:
1527 return self.inspector.info(info.obj, oname, info=info,
1527 return self.inspector.info(info.obj, oname, info=info,
1528 detail_level=detail_level
1528 detail_level=detail_level
1529 )
1529 )
1530 else:
1530 else:
1531 return oinspect.object_info(name=oname, found=False)
1531 return oinspect.object_info(name=oname, found=False)
1532
1532
1533 def object_inspect_text(self, oname, detail_level=0):
1533 def object_inspect_text(self, oname, detail_level=0):
1534 """Get object info as formatted text"""
1534 """Get object info as formatted text"""
1535 return self.object_inspect_mime(oname, detail_level)['text/plain']
1535 return self.object_inspect_mime(oname, detail_level)['text/plain']
1536
1536
1537 def object_inspect_mime(self, oname, detail_level=0):
1537 def object_inspect_mime(self, oname, detail_level=0):
1538 """Get object info as a mimebundle of formatted representations.
1538 """Get object info as a mimebundle of formatted representations.
1539
1539
1540 A mimebundle is a dictionary, keyed by mime-type.
1540 A mimebundle is a dictionary, keyed by mime-type.
1541 It must always have the key `'text/plain'`.
1541 It must always have the key `'text/plain'`.
1542 """
1542 """
1543 with self.builtin_trap:
1543 with self.builtin_trap:
1544 info = self._object_find(oname)
1544 info = self._object_find(oname)
1545 if info.found:
1545 if info.found:
1546 return self.inspector._get_info(info.obj, oname, info=info,
1546 return self.inspector._get_info(info.obj, oname, info=info,
1547 detail_level=detail_level
1547 detail_level=detail_level
1548 )
1548 )
1549 else:
1549 else:
1550 raise KeyError(oname)
1550 raise KeyError(oname)
1551
1551
1552 #-------------------------------------------------------------------------
1552 #-------------------------------------------------------------------------
1553 # Things related to history management
1553 # Things related to history management
1554 #-------------------------------------------------------------------------
1554 #-------------------------------------------------------------------------
1555
1555
1556 def init_history(self):
1556 def init_history(self):
1557 """Sets up the command history, and starts regular autosaves."""
1557 """Sets up the command history, and starts regular autosaves."""
1558 self.history_manager = HistoryManager(shell=self, parent=self)
1558 self.history_manager = HistoryManager(shell=self, parent=self)
1559 self.configurables.append(self.history_manager)
1559 self.configurables.append(self.history_manager)
1560
1560
1561 #-------------------------------------------------------------------------
1561 #-------------------------------------------------------------------------
1562 # Things related to exception handling and tracebacks (not debugging)
1562 # Things related to exception handling and tracebacks (not debugging)
1563 #-------------------------------------------------------------------------
1563 #-------------------------------------------------------------------------
1564
1564
1565 debugger_cls = Pdb
1565 debugger_cls = Pdb
1566
1566
1567 def init_traceback_handlers(self, custom_exceptions):
1567 def init_traceback_handlers(self, custom_exceptions):
1568 # Syntax error handler.
1568 # Syntax error handler.
1569 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor', parent=self)
1569 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor', parent=self)
1570
1570
1571 # The interactive one is initialized with an offset, meaning we always
1571 # The interactive one is initialized with an offset, meaning we always
1572 # want to remove the topmost item in the traceback, which is our own
1572 # want to remove the topmost item in the traceback, which is our own
1573 # internal code. Valid modes: ['Plain','Context','Verbose']
1573 # internal code. Valid modes: ['Plain','Context','Verbose']
1574 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1574 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1575 color_scheme='NoColor',
1575 color_scheme='NoColor',
1576 tb_offset = 1,
1576 tb_offset = 1,
1577 check_cache=check_linecache_ipython,
1577 check_cache=check_linecache_ipython,
1578 debugger_cls=self.debugger_cls, parent=self)
1578 debugger_cls=self.debugger_cls, parent=self)
1579
1579
1580 # The instance will store a pointer to the system-wide exception hook,
1580 # The instance will store a pointer to the system-wide exception hook,
1581 # so that runtime code (such as magics) can access it. This is because
1581 # so that runtime code (such as magics) can access it. This is because
1582 # during the read-eval loop, it may get temporarily overwritten.
1582 # during the read-eval loop, it may get temporarily overwritten.
1583 self.sys_excepthook = sys.excepthook
1583 self.sys_excepthook = sys.excepthook
1584
1584
1585 # and add any custom exception handlers the user may have specified
1585 # and add any custom exception handlers the user may have specified
1586 self.set_custom_exc(*custom_exceptions)
1586 self.set_custom_exc(*custom_exceptions)
1587
1587
1588 # Set the exception mode
1588 # Set the exception mode
1589 self.InteractiveTB.set_mode(mode=self.xmode)
1589 self.InteractiveTB.set_mode(mode=self.xmode)
1590
1590
1591 def set_custom_exc(self, exc_tuple, handler):
1591 def set_custom_exc(self, exc_tuple, handler):
1592 """set_custom_exc(exc_tuple, handler)
1592 """set_custom_exc(exc_tuple, handler)
1593
1593
1594 Set a custom exception handler, which will be called if any of the
1594 Set a custom exception handler, which will be called if any of the
1595 exceptions in exc_tuple occur in the mainloop (specifically, in the
1595 exceptions in exc_tuple occur in the mainloop (specifically, in the
1596 run_code() method).
1596 run_code() method).
1597
1597
1598 Parameters
1598 Parameters
1599 ----------
1599 ----------
1600
1600
1601 exc_tuple : tuple of exception classes
1601 exc_tuple : tuple of exception classes
1602 A *tuple* of exception classes, for which to call the defined
1602 A *tuple* of exception classes, for which to call the defined
1603 handler. It is very important that you use a tuple, and NOT A
1603 handler. It is very important that you use a tuple, and NOT A
1604 LIST here, because of the way Python's except statement works. If
1604 LIST here, because of the way Python's except statement works. If
1605 you only want to trap a single exception, use a singleton tuple::
1605 you only want to trap a single exception, use a singleton tuple::
1606
1606
1607 exc_tuple == (MyCustomException,)
1607 exc_tuple == (MyCustomException,)
1608
1608
1609 handler : callable
1609 handler : callable
1610 handler must have the following signature::
1610 handler must have the following signature::
1611
1611
1612 def my_handler(self, etype, value, tb, tb_offset=None):
1612 def my_handler(self, etype, value, tb, tb_offset=None):
1613 ...
1613 ...
1614 return structured_traceback
1614 return structured_traceback
1615
1615
1616 Your handler must return a structured traceback (a list of strings),
1616 Your handler must return a structured traceback (a list of strings),
1617 or None.
1617 or None.
1618
1618
1619 This will be made into an instance method (via types.MethodType)
1619 This will be made into an instance method (via types.MethodType)
1620 of IPython itself, and it will be called if any of the exceptions
1620 of IPython itself, and it will be called if any of the exceptions
1621 listed in the exc_tuple are caught. If the handler is None, an
1621 listed in the exc_tuple are caught. If the handler is None, an
1622 internal basic one is used, which just prints basic info.
1622 internal basic one is used, which just prints basic info.
1623
1623
1624 To protect IPython from crashes, if your handler ever raises an
1624 To protect IPython from crashes, if your handler ever raises an
1625 exception or returns an invalid result, it will be immediately
1625 exception or returns an invalid result, it will be immediately
1626 disabled.
1626 disabled.
1627
1627
1628 WARNING: by putting in your own exception handler into IPython's main
1628 WARNING: by putting in your own exception handler into IPython's main
1629 execution loop, you run a very good chance of nasty crashes. This
1629 execution loop, you run a very good chance of nasty crashes. This
1630 facility should only be used if you really know what you are doing."""
1630 facility should only be used if you really know what you are doing."""
1631
1631
1632 assert type(exc_tuple)==type(()) , \
1632 assert type(exc_tuple)==type(()) , \
1633 "The custom exceptions must be given AS A TUPLE."
1633 "The custom exceptions must be given AS A TUPLE."
1634
1634
1635 def dummy_handler(self, etype, value, tb, tb_offset=None):
1635 def dummy_handler(self, etype, value, tb, tb_offset=None):
1636 print('*** Simple custom exception handler ***')
1636 print('*** Simple custom exception handler ***')
1637 print('Exception type :',etype)
1637 print('Exception type :',etype)
1638 print('Exception value:',value)
1638 print('Exception value:',value)
1639 print('Traceback :',tb)
1639 print('Traceback :',tb)
1640 #print 'Source code :','\n'.join(self.buffer)
1640 #print 'Source code :','\n'.join(self.buffer)
1641
1641
1642 def validate_stb(stb):
1642 def validate_stb(stb):
1643 """validate structured traceback return type
1643 """validate structured traceback return type
1644
1644
1645 return type of CustomTB *should* be a list of strings, but allow
1645 return type of CustomTB *should* be a list of strings, but allow
1646 single strings or None, which are harmless.
1646 single strings or None, which are harmless.
1647
1647
1648 This function will *always* return a list of strings,
1648 This function will *always* return a list of strings,
1649 and will raise a TypeError if stb is inappropriate.
1649 and will raise a TypeError if stb is inappropriate.
1650 """
1650 """
1651 msg = "CustomTB must return list of strings, not %r" % stb
1651 msg = "CustomTB must return list of strings, not %r" % stb
1652 if stb is None:
1652 if stb is None:
1653 return []
1653 return []
1654 elif isinstance(stb, string_types):
1654 elif isinstance(stb, string_types):
1655 return [stb]
1655 return [stb]
1656 elif not isinstance(stb, list):
1656 elif not isinstance(stb, list):
1657 raise TypeError(msg)
1657 raise TypeError(msg)
1658 # it's a list
1658 # it's a list
1659 for line in stb:
1659 for line in stb:
1660 # check every element
1660 # check every element
1661 if not isinstance(line, string_types):
1661 if not isinstance(line, string_types):
1662 raise TypeError(msg)
1662 raise TypeError(msg)
1663 return stb
1663 return stb
1664
1664
1665 if handler is None:
1665 if handler is None:
1666 wrapped = dummy_handler
1666 wrapped = dummy_handler
1667 else:
1667 else:
1668 def wrapped(self,etype,value,tb,tb_offset=None):
1668 def wrapped(self,etype,value,tb,tb_offset=None):
1669 """wrap CustomTB handler, to protect IPython from user code
1669 """wrap CustomTB handler, to protect IPython from user code
1670
1670
1671 This makes it harder (but not impossible) for custom exception
1671 This makes it harder (but not impossible) for custom exception
1672 handlers to crash IPython.
1672 handlers to crash IPython.
1673 """
1673 """
1674 try:
1674 try:
1675 stb = handler(self,etype,value,tb,tb_offset=tb_offset)
1675 stb = handler(self,etype,value,tb,tb_offset=tb_offset)
1676 return validate_stb(stb)
1676 return validate_stb(stb)
1677 except:
1677 except:
1678 # clear custom handler immediately
1678 # clear custom handler immediately
1679 self.set_custom_exc((), None)
1679 self.set_custom_exc((), None)
1680 print("Custom TB Handler failed, unregistering", file=sys.stderr)
1680 print("Custom TB Handler failed, unregistering", file=sys.stderr)
1681 # show the exception in handler first
1681 # show the exception in handler first
1682 stb = self.InteractiveTB.structured_traceback(*sys.exc_info())
1682 stb = self.InteractiveTB.structured_traceback(*sys.exc_info())
1683 print(self.InteractiveTB.stb2text(stb))
1683 print(self.InteractiveTB.stb2text(stb))
1684 print("The original exception:")
1684 print("The original exception:")
1685 stb = self.InteractiveTB.structured_traceback(
1685 stb = self.InteractiveTB.structured_traceback(
1686 (etype,value,tb), tb_offset=tb_offset
1686 (etype,value,tb), tb_offset=tb_offset
1687 )
1687 )
1688 return stb
1688 return stb
1689
1689
1690 self.CustomTB = types.MethodType(wrapped,self)
1690 self.CustomTB = types.MethodType(wrapped,self)
1691 self.custom_exceptions = exc_tuple
1691 self.custom_exceptions = exc_tuple
1692
1692
1693 def excepthook(self, etype, value, tb):
1693 def excepthook(self, etype, value, tb):
1694 """One more defense for GUI apps that call sys.excepthook.
1694 """One more defense for GUI apps that call sys.excepthook.
1695
1695
1696 GUI frameworks like wxPython trap exceptions and call
1696 GUI frameworks like wxPython trap exceptions and call
1697 sys.excepthook themselves. I guess this is a feature that
1697 sys.excepthook themselves. I guess this is a feature that
1698 enables them to keep running after exceptions that would
1698 enables them to keep running after exceptions that would
1699 otherwise kill their mainloop. This is a bother for IPython
1699 otherwise kill their mainloop. This is a bother for IPython
1700 which excepts to catch all of the program exceptions with a try:
1700 which excepts to catch all of the program exceptions with a try:
1701 except: statement.
1701 except: statement.
1702
1702
1703 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1703 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1704 any app directly invokes sys.excepthook, it will look to the user like
1704 any app directly invokes sys.excepthook, it will look to the user like
1705 IPython crashed. In order to work around this, we can disable the
1705 IPython crashed. In order to work around this, we can disable the
1706 CrashHandler and replace it with this excepthook instead, which prints a
1706 CrashHandler and replace it with this excepthook instead, which prints a
1707 regular traceback using our InteractiveTB. In this fashion, apps which
1707 regular traceback using our InteractiveTB. In this fashion, apps which
1708 call sys.excepthook will generate a regular-looking exception from
1708 call sys.excepthook will generate a regular-looking exception from
1709 IPython, and the CrashHandler will only be triggered by real IPython
1709 IPython, and the CrashHandler will only be triggered by real IPython
1710 crashes.
1710 crashes.
1711
1711
1712 This hook should be used sparingly, only in places which are not likely
1712 This hook should be used sparingly, only in places which are not likely
1713 to be true IPython errors.
1713 to be true IPython errors.
1714 """
1714 """
1715 self.showtraceback((etype, value, tb), tb_offset=0)
1715 self.showtraceback((etype, value, tb), tb_offset=0)
1716
1716
1717 def _get_exc_info(self, exc_tuple=None):
1717 def _get_exc_info(self, exc_tuple=None):
1718 """get exc_info from a given tuple, sys.exc_info() or sys.last_type etc.
1718 """get exc_info from a given tuple, sys.exc_info() or sys.last_type etc.
1719
1719
1720 Ensures sys.last_type,value,traceback hold the exc_info we found,
1720 Ensures sys.last_type,value,traceback hold the exc_info we found,
1721 from whichever source.
1721 from whichever source.
1722
1722
1723 raises ValueError if none of these contain any information
1723 raises ValueError if none of these contain any information
1724 """
1724 """
1725 if exc_tuple is None:
1725 if exc_tuple is None:
1726 etype, value, tb = sys.exc_info()
1726 etype, value, tb = sys.exc_info()
1727 else:
1727 else:
1728 etype, value, tb = exc_tuple
1728 etype, value, tb = exc_tuple
1729
1729
1730 if etype is None:
1730 if etype is None:
1731 if hasattr(sys, 'last_type'):
1731 if hasattr(sys, 'last_type'):
1732 etype, value, tb = sys.last_type, sys.last_value, \
1732 etype, value, tb = sys.last_type, sys.last_value, \
1733 sys.last_traceback
1733 sys.last_traceback
1734
1734
1735 if etype is None:
1735 if etype is None:
1736 raise ValueError("No exception to find")
1736 raise ValueError("No exception to find")
1737
1737
1738 # Now store the exception info in sys.last_type etc.
1738 # Now store the exception info in sys.last_type etc.
1739 # WARNING: these variables are somewhat deprecated and not
1739 # WARNING: these variables are somewhat deprecated and not
1740 # necessarily safe to use in a threaded environment, but tools
1740 # necessarily safe to use in a threaded environment, but tools
1741 # like pdb depend on their existence, so let's set them. If we
1741 # like pdb depend on their existence, so let's set them. If we
1742 # find problems in the field, we'll need to revisit their use.
1742 # find problems in the field, we'll need to revisit their use.
1743 sys.last_type = etype
1743 sys.last_type = etype
1744 sys.last_value = value
1744 sys.last_value = value
1745 sys.last_traceback = tb
1745 sys.last_traceback = tb
1746
1746
1747 return etype, value, tb
1747 return etype, value, tb
1748
1748
1749 def show_usage_error(self, exc):
1749 def show_usage_error(self, exc):
1750 """Show a short message for UsageErrors
1750 """Show a short message for UsageErrors
1751
1751
1752 These are special exceptions that shouldn't show a traceback.
1752 These are special exceptions that shouldn't show a traceback.
1753 """
1753 """
1754 print("UsageError: %s" % exc, file=sys.stderr)
1754 print("UsageError: %s" % exc, file=sys.stderr)
1755
1755
1756 def get_exception_only(self, exc_tuple=None):
1756 def get_exception_only(self, exc_tuple=None):
1757 """
1757 """
1758 Return as a string (ending with a newline) the exception that
1758 Return as a string (ending with a newline) the exception that
1759 just occurred, without any traceback.
1759 just occurred, without any traceback.
1760 """
1760 """
1761 etype, value, tb = self._get_exc_info(exc_tuple)
1761 etype, value, tb = self._get_exc_info(exc_tuple)
1762 msg = traceback.format_exception_only(etype, value)
1762 msg = traceback.format_exception_only(etype, value)
1763 return ''.join(msg)
1763 return ''.join(msg)
1764
1764
1765 def showtraceback(self, exc_tuple=None, filename=None, tb_offset=None,
1765 def showtraceback(self, exc_tuple=None, filename=None, tb_offset=None,
1766 exception_only=False):
1766 exception_only=False):
1767 """Display the exception that just occurred.
1767 """Display the exception that just occurred.
1768
1768
1769 If nothing is known about the exception, this is the method which
1769 If nothing is known about the exception, this is the method which
1770 should be used throughout the code for presenting user tracebacks,
1770 should be used throughout the code for presenting user tracebacks,
1771 rather than directly invoking the InteractiveTB object.
1771 rather than directly invoking the InteractiveTB object.
1772
1772
1773 A specific showsyntaxerror() also exists, but this method can take
1773 A specific showsyntaxerror() also exists, but this method can take
1774 care of calling it if needed, so unless you are explicitly catching a
1774 care of calling it if needed, so unless you are explicitly catching a
1775 SyntaxError exception, don't try to analyze the stack manually and
1775 SyntaxError exception, don't try to analyze the stack manually and
1776 simply call this method."""
1776 simply call this method."""
1777
1777
1778 try:
1778 try:
1779 try:
1779 try:
1780 etype, value, tb = self._get_exc_info(exc_tuple)
1780 etype, value, tb = self._get_exc_info(exc_tuple)
1781 except ValueError:
1781 except ValueError:
1782 print('No traceback available to show.', file=sys.stderr)
1782 print('No traceback available to show.', file=sys.stderr)
1783 return
1783 return
1784
1784
1785 if issubclass(etype, SyntaxError):
1785 if issubclass(etype, SyntaxError):
1786 # Though this won't be called by syntax errors in the input
1786 # Though this won't be called by syntax errors in the input
1787 # line, there may be SyntaxError cases with imported code.
1787 # line, there may be SyntaxError cases with imported code.
1788 self.showsyntaxerror(filename)
1788 self.showsyntaxerror(filename)
1789 elif etype is UsageError:
1789 elif etype is UsageError:
1790 self.show_usage_error(value)
1790 self.show_usage_error(value)
1791 else:
1791 else:
1792 if exception_only:
1792 if exception_only:
1793 stb = ['An exception has occurred, use %tb to see '
1793 stb = ['An exception has occurred, use %tb to see '
1794 'the full traceback.\n']
1794 'the full traceback.\n']
1795 stb.extend(self.InteractiveTB.get_exception_only(etype,
1795 stb.extend(self.InteractiveTB.get_exception_only(etype,
1796 value))
1796 value))
1797 else:
1797 else:
1798 try:
1798 try:
1799 # Exception classes can customise their traceback - we
1799 # Exception classes can customise their traceback - we
1800 # use this in IPython.parallel for exceptions occurring
1800 # use this in IPython.parallel for exceptions occurring
1801 # in the engines. This should return a list of strings.
1801 # in the engines. This should return a list of strings.
1802 stb = value._render_traceback_()
1802 stb = value._render_traceback_()
1803 except Exception:
1803 except Exception:
1804 stb = self.InteractiveTB.structured_traceback(etype,
1804 stb = self.InteractiveTB.structured_traceback(etype,
1805 value, tb, tb_offset=tb_offset)
1805 value, tb, tb_offset=tb_offset)
1806
1806
1807 self._showtraceback(etype, value, stb)
1807 self._showtraceback(etype, value, stb)
1808 if self.call_pdb:
1808 if self.call_pdb:
1809 # drop into debugger
1809 # drop into debugger
1810 self.debugger(force=True)
1810 self.debugger(force=True)
1811 return
1811 return
1812
1812
1813 # Actually show the traceback
1813 # Actually show the traceback
1814 self._showtraceback(etype, value, stb)
1814 self._showtraceback(etype, value, stb)
1815
1815
1816 except KeyboardInterrupt:
1816 except KeyboardInterrupt:
1817 print('\n' + self.get_exception_only(), file=sys.stderr)
1817 print('\n' + self.get_exception_only(), file=sys.stderr)
1818
1818
1819 def _showtraceback(self, etype, evalue, stb):
1819 def _showtraceback(self, etype, evalue, stb):
1820 """Actually show a traceback.
1820 """Actually show a traceback.
1821
1821
1822 Subclasses may override this method to put the traceback on a different
1822 Subclasses may override this method to put the traceback on a different
1823 place, like a side channel.
1823 place, like a side channel.
1824 """
1824 """
1825 print(self.InteractiveTB.stb2text(stb))
1825 print(self.InteractiveTB.stb2text(stb))
1826
1826
1827 def showsyntaxerror(self, filename=None):
1827 def showsyntaxerror(self, filename=None):
1828 """Display the syntax error that just occurred.
1828 """Display the syntax error that just occurred.
1829
1829
1830 This doesn't display a stack trace because there isn't one.
1830 This doesn't display a stack trace because there isn't one.
1831
1831
1832 If a filename is given, it is stuffed in the exception instead
1832 If a filename is given, it is stuffed in the exception instead
1833 of what was there before (because Python's parser always uses
1833 of what was there before (because Python's parser always uses
1834 "<string>" when reading from a string).
1834 "<string>" when reading from a string).
1835 """
1835 """
1836 etype, value, last_traceback = self._get_exc_info()
1836 etype, value, last_traceback = self._get_exc_info()
1837
1837
1838 if filename and issubclass(etype, SyntaxError):
1838 if filename and issubclass(etype, SyntaxError):
1839 try:
1839 try:
1840 value.filename = filename
1840 value.filename = filename
1841 except:
1841 except:
1842 # Not the format we expect; leave it alone
1842 # Not the format we expect; leave it alone
1843 pass
1843 pass
1844
1844
1845 stb = self.SyntaxTB.structured_traceback(etype, value, [])
1845 stb = self.SyntaxTB.structured_traceback(etype, value, [])
1846 self._showtraceback(etype, value, stb)
1846 self._showtraceback(etype, value, stb)
1847
1847
1848 # This is overridden in TerminalInteractiveShell to show a message about
1848 # This is overridden in TerminalInteractiveShell to show a message about
1849 # the %paste magic.
1849 # the %paste magic.
1850 def showindentationerror(self):
1850 def showindentationerror(self):
1851 """Called by run_cell when there's an IndentationError in code entered
1851 """Called by run_cell when there's an IndentationError in code entered
1852 at the prompt.
1852 at the prompt.
1853
1853
1854 This is overridden in TerminalInteractiveShell to show a message about
1854 This is overridden in TerminalInteractiveShell to show a message about
1855 the %paste magic."""
1855 the %paste magic."""
1856 self.showsyntaxerror()
1856 self.showsyntaxerror()
1857
1857
1858 #-------------------------------------------------------------------------
1858 #-------------------------------------------------------------------------
1859 # Things related to readline
1859 # Things related to readline
1860 #-------------------------------------------------------------------------
1860 #-------------------------------------------------------------------------
1861
1861
1862 def init_readline(self):
1862 def init_readline(self):
1863 """DEPRECATED
1863 """DEPRECATED
1864
1864
1865 Moved to terminal subclass, here only to simplify the init logic."""
1865 Moved to terminal subclass, here only to simplify the init logic."""
1866 # Set a number of methods that depend on readline to be no-op
1866 # Set a number of methods that depend on readline to be no-op
1867 warnings.warn('`init_readline` is no-op since IPython 5.0 and is Deprecated',
1867 warnings.warn('`init_readline` is no-op since IPython 5.0 and is Deprecated',
1868 DeprecationWarning, stacklevel=2)
1868 DeprecationWarning, stacklevel=2)
1869 self.set_custom_completer = no_op
1869 self.set_custom_completer = no_op
1870
1870
1871 @skip_doctest
1871 @skip_doctest
1872 def set_next_input(self, s, replace=False):
1872 def set_next_input(self, s, replace=False):
1873 """ Sets the 'default' input string for the next command line.
1873 """ Sets the 'default' input string for the next command line.
1874
1874
1875 Example::
1875 Example::
1876
1876
1877 In [1]: _ip.set_next_input("Hello Word")
1877 In [1]: _ip.set_next_input("Hello Word")
1878 In [2]: Hello Word_ # cursor is here
1878 In [2]: Hello Word_ # cursor is here
1879 """
1879 """
1880 self.rl_next_input = py3compat.cast_bytes_py2(s)
1880 self.rl_next_input = py3compat.cast_bytes_py2(s)
1881
1881
1882 def _indent_current_str(self):
1882 def _indent_current_str(self):
1883 """return the current level of indentation as a string"""
1883 """return the current level of indentation as a string"""
1884 return self.input_splitter.indent_spaces * ' '
1884 return self.input_splitter.indent_spaces * ' '
1885
1885
1886 #-------------------------------------------------------------------------
1886 #-------------------------------------------------------------------------
1887 # Things related to text completion
1887 # Things related to text completion
1888 #-------------------------------------------------------------------------
1888 #-------------------------------------------------------------------------
1889
1889
1890 def init_completer(self):
1890 def init_completer(self):
1891 """Initialize the completion machinery.
1891 """Initialize the completion machinery.
1892
1892
1893 This creates completion machinery that can be used by client code,
1893 This creates completion machinery that can be used by client code,
1894 either interactively in-process (typically triggered by the readline
1894 either interactively in-process (typically triggered by the readline
1895 library), programmatically (such as in test suites) or out-of-process
1895 library), programmatically (such as in test suites) or out-of-process
1896 (typically over the network by remote frontends).
1896 (typically over the network by remote frontends).
1897 """
1897 """
1898 from IPython.core.completer import IPCompleter
1898 from IPython.core.completer import IPCompleter
1899 from IPython.core.completerlib import (module_completer,
1899 from IPython.core.completerlib import (module_completer,
1900 magic_run_completer, cd_completer, reset_completer)
1900 magic_run_completer, cd_completer, reset_completer)
1901
1901
1902 self.Completer = IPCompleter(shell=self,
1902 self.Completer = IPCompleter(shell=self,
1903 namespace=self.user_ns,
1903 namespace=self.user_ns,
1904 global_namespace=self.user_global_ns,
1904 global_namespace=self.user_global_ns,
1905 parent=self,
1905 parent=self,
1906 )
1906 )
1907 self.configurables.append(self.Completer)
1907 self.configurables.append(self.Completer)
1908
1908
1909 # Add custom completers to the basic ones built into IPCompleter
1909 # Add custom completers to the basic ones built into IPCompleter
1910 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1910 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1911 self.strdispatchers['complete_command'] = sdisp
1911 self.strdispatchers['complete_command'] = sdisp
1912 self.Completer.custom_completers = sdisp
1912 self.Completer.custom_completers = sdisp
1913
1913
1914 self.set_hook('complete_command', module_completer, str_key = 'import')
1914 self.set_hook('complete_command', module_completer, str_key = 'import')
1915 self.set_hook('complete_command', module_completer, str_key = 'from')
1915 self.set_hook('complete_command', module_completer, str_key = 'from')
1916 self.set_hook('complete_command', module_completer, str_key = '%aimport')
1916 self.set_hook('complete_command', module_completer, str_key = '%aimport')
1917 self.set_hook('complete_command', magic_run_completer, str_key = '%run')
1917 self.set_hook('complete_command', magic_run_completer, str_key = '%run')
1918 self.set_hook('complete_command', cd_completer, str_key = '%cd')
1918 self.set_hook('complete_command', cd_completer, str_key = '%cd')
1919 self.set_hook('complete_command', reset_completer, str_key = '%reset')
1919 self.set_hook('complete_command', reset_completer, str_key = '%reset')
1920
1920
1921
1921
1922 def complete(self, text, line=None, cursor_pos=None):
1922 def complete(self, text, line=None, cursor_pos=None):
1923 """Return the completed text and a list of completions.
1923 """Return the completed text and a list of completions.
1924
1924
1925 Parameters
1925 Parameters
1926 ----------
1926 ----------
1927
1927
1928 text : string
1928 text : string
1929 A string of text to be completed on. It can be given as empty and
1929 A string of text to be completed on. It can be given as empty and
1930 instead a line/position pair are given. In this case, the
1930 instead a line/position pair are given. In this case, the
1931 completer itself will split the line like readline does.
1931 completer itself will split the line like readline does.
1932
1932
1933 line : string, optional
1933 line : string, optional
1934 The complete line that text is part of.
1934 The complete line that text is part of.
1935
1935
1936 cursor_pos : int, optional
1936 cursor_pos : int, optional
1937 The position of the cursor on the input line.
1937 The position of the cursor on the input line.
1938
1938
1939 Returns
1939 Returns
1940 -------
1940 -------
1941 text : string
1941 text : string
1942 The actual text that was completed.
1942 The actual text that was completed.
1943
1943
1944 matches : list
1944 matches : list
1945 A sorted list with all possible completions.
1945 A sorted list with all possible completions.
1946
1946
1947 The optional arguments allow the completion to take more context into
1947 The optional arguments allow the completion to take more context into
1948 account, and are part of the low-level completion API.
1948 account, and are part of the low-level completion API.
1949
1949
1950 This is a wrapper around the completion mechanism, similar to what
1950 This is a wrapper around the completion mechanism, similar to what
1951 readline does at the command line when the TAB key is hit. By
1951 readline does at the command line when the TAB key is hit. By
1952 exposing it as a method, it can be used by other non-readline
1952 exposing it as a method, it can be used by other non-readline
1953 environments (such as GUIs) for text completion.
1953 environments (such as GUIs) for text completion.
1954
1954
1955 Simple usage example:
1955 Simple usage example:
1956
1956
1957 In [1]: x = 'hello'
1957 In [1]: x = 'hello'
1958
1958
1959 In [2]: _ip.complete('x.l')
1959 In [2]: _ip.complete('x.l')
1960 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
1960 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
1961 """
1961 """
1962
1962
1963 # Inject names into __builtin__ so we can complete on the added names.
1963 # Inject names into __builtin__ so we can complete on the added names.
1964 with self.builtin_trap:
1964 with self.builtin_trap:
1965 return self.Completer.complete(text, line, cursor_pos)
1965 return self.Completer.complete(text, line, cursor_pos)
1966
1966
1967 def set_custom_completer(self, completer, pos=0):
1967 def set_custom_completer(self, completer, pos=0):
1968 """Adds a new custom completer function.
1968 """Adds a new custom completer function.
1969
1969
1970 The position argument (defaults to 0) is the index in the completers
1970 The position argument (defaults to 0) is the index in the completers
1971 list where you want the completer to be inserted."""
1971 list where you want the completer to be inserted."""
1972
1972
1973 newcomp = types.MethodType(completer,self.Completer)
1973 newcomp = types.MethodType(completer,self.Completer)
1974 self.Completer.matchers.insert(pos,newcomp)
1974 self.Completer.matchers.insert(pos,newcomp)
1975
1975
1976 def set_completer_frame(self, frame=None):
1976 def set_completer_frame(self, frame=None):
1977 """Set the frame of the completer."""
1977 """Set the frame of the completer."""
1978 if frame:
1978 if frame:
1979 self.Completer.namespace = frame.f_locals
1979 self.Completer.namespace = frame.f_locals
1980 self.Completer.global_namespace = frame.f_globals
1980 self.Completer.global_namespace = frame.f_globals
1981 else:
1981 else:
1982 self.Completer.namespace = self.user_ns
1982 self.Completer.namespace = self.user_ns
1983 self.Completer.global_namespace = self.user_global_ns
1983 self.Completer.global_namespace = self.user_global_ns
1984
1984
1985 #-------------------------------------------------------------------------
1985 #-------------------------------------------------------------------------
1986 # Things related to magics
1986 # Things related to magics
1987 #-------------------------------------------------------------------------
1987 #-------------------------------------------------------------------------
1988
1988
1989 def init_magics(self):
1989 def init_magics(self):
1990 from IPython.core import magics as m
1990 from IPython.core import magics as m
1991 self.magics_manager = magic.MagicsManager(shell=self,
1991 self.magics_manager = magic.MagicsManager(shell=self,
1992 parent=self,
1992 parent=self,
1993 user_magics=m.UserMagics(self))
1993 user_magics=m.UserMagics(self))
1994 self.configurables.append(self.magics_manager)
1994 self.configurables.append(self.magics_manager)
1995
1995
1996 # Expose as public API from the magics manager
1996 # Expose as public API from the magics manager
1997 self.register_magics = self.magics_manager.register
1997 self.register_magics = self.magics_manager.register
1998
1998
1999 self.register_magics(m.AutoMagics, m.BasicMagics, m.CodeMagics,
1999 self.register_magics(m.AutoMagics, m.BasicMagics, m.CodeMagics,
2000 m.ConfigMagics, m.DisplayMagics, m.ExecutionMagics,
2000 m.ConfigMagics, m.DisplayMagics, m.ExecutionMagics,
2001 m.ExtensionMagics, m.HistoryMagics, m.LoggingMagics,
2001 m.ExtensionMagics, m.HistoryMagics, m.LoggingMagics,
2002 m.NamespaceMagics, m.OSMagics, m.PylabMagics, m.ScriptMagics,
2002 m.NamespaceMagics, m.OSMagics, m.PylabMagics, m.ScriptMagics,
2003 )
2003 )
2004
2004
2005 # Register Magic Aliases
2005 # Register Magic Aliases
2006 mman = self.magics_manager
2006 mman = self.magics_manager
2007 # FIXME: magic aliases should be defined by the Magics classes
2007 # FIXME: magic aliases should be defined by the Magics classes
2008 # or in MagicsManager, not here
2008 # or in MagicsManager, not here
2009 mman.register_alias('ed', 'edit')
2009 mman.register_alias('ed', 'edit')
2010 mman.register_alias('hist', 'history')
2010 mman.register_alias('hist', 'history')
2011 mman.register_alias('rep', 'recall')
2011 mman.register_alias('rep', 'recall')
2012 mman.register_alias('SVG', 'svg', 'cell')
2012 mman.register_alias('SVG', 'svg', 'cell')
2013 mman.register_alias('HTML', 'html', 'cell')
2013 mman.register_alias('HTML', 'html', 'cell')
2014 mman.register_alias('file', 'writefile', 'cell')
2014 mman.register_alias('file', 'writefile', 'cell')
2015
2015
2016 # FIXME: Move the color initialization to the DisplayHook, which
2016 # FIXME: Move the color initialization to the DisplayHook, which
2017 # should be split into a prompt manager and displayhook. We probably
2017 # should be split into a prompt manager and displayhook. We probably
2018 # even need a centralize colors management object.
2018 # even need a centralize colors management object.
2019 self.magic('colors %s' % self.colors)
2019 self.magic('colors %s' % self.colors)
2020
2020
2021 # Defined here so that it's included in the documentation
2021 # Defined here so that it's included in the documentation
2022 @functools.wraps(magic.MagicsManager.register_function)
2022 @functools.wraps(magic.MagicsManager.register_function)
2023 def register_magic_function(self, func, magic_kind='line', magic_name=None):
2023 def register_magic_function(self, func, magic_kind='line', magic_name=None):
2024 self.magics_manager.register_function(func,
2024 self.magics_manager.register_function(func,
2025 magic_kind=magic_kind, magic_name=magic_name)
2025 magic_kind=magic_kind, magic_name=magic_name)
2026
2026
2027 def run_line_magic(self, magic_name, line):
2027 def run_line_magic(self, magic_name, line):
2028 """Execute the given line magic.
2028 """Execute the given line magic.
2029
2029
2030 Parameters
2030 Parameters
2031 ----------
2031 ----------
2032 magic_name : str
2032 magic_name : str
2033 Name of the desired magic function, without '%' prefix.
2033 Name of the desired magic function, without '%' prefix.
2034
2034
2035 line : str
2035 line : str
2036 The rest of the input line as a single string.
2036 The rest of the input line as a single string.
2037 """
2037 """
2038 fn = self.find_line_magic(magic_name)
2038 fn = self.find_line_magic(magic_name)
2039 if fn is None:
2039 if fn is None:
2040 cm = self.find_cell_magic(magic_name)
2040 cm = self.find_cell_magic(magic_name)
2041 etpl = "Line magic function `%%%s` not found%s."
2041 etpl = "Line magic function `%%%s` not found%s."
2042 extra = '' if cm is None else (' (But cell magic `%%%%%s` exists, '
2042 extra = '' if cm is None else (' (But cell magic `%%%%%s` exists, '
2043 'did you mean that instead?)' % magic_name )
2043 'did you mean that instead?)' % magic_name )
2044 error(etpl % (magic_name, extra))
2044 error(etpl % (magic_name, extra))
2045 else:
2045 else:
2046 # Note: this is the distance in the stack to the user's frame.
2046 # Note: this is the distance in the stack to the user's frame.
2047 # This will need to be updated if the internal calling logic gets
2047 # This will need to be updated if the internal calling logic gets
2048 # refactored, or else we'll be expanding the wrong variables.
2048 # refactored, or else we'll be expanding the wrong variables.
2049 stack_depth = 2
2049 stack_depth = 2
2050 magic_arg_s = self.var_expand(line, stack_depth)
2050 magic_arg_s = self.var_expand(line, stack_depth)
2051 # Put magic args in a list so we can call with f(*a) syntax
2051 # Put magic args in a list so we can call with f(*a) syntax
2052 args = [magic_arg_s]
2052 args = [magic_arg_s]
2053 kwargs = {}
2053 kwargs = {}
2054 # Grab local namespace if we need it:
2054 # Grab local namespace if we need it:
2055 if getattr(fn, "needs_local_scope", False):
2055 if getattr(fn, "needs_local_scope", False):
2056 kwargs['local_ns'] = sys._getframe(stack_depth).f_locals
2056 kwargs['local_ns'] = sys._getframe(stack_depth).f_locals
2057 with self.builtin_trap:
2057 with self.builtin_trap:
2058 result = fn(*args,**kwargs)
2058 result = fn(*args,**kwargs)
2059 return result
2059 return result
2060
2060
2061 def run_cell_magic(self, magic_name, line, cell):
2061 def run_cell_magic(self, magic_name, line, cell):
2062 """Execute the given cell magic.
2062 """Execute the given cell magic.
2063
2063
2064 Parameters
2064 Parameters
2065 ----------
2065 ----------
2066 magic_name : str
2066 magic_name : str
2067 Name of the desired magic function, without '%' prefix.
2067 Name of the desired magic function, without '%' prefix.
2068
2068
2069 line : str
2069 line : str
2070 The rest of the first input line as a single string.
2070 The rest of the first input line as a single string.
2071
2071
2072 cell : str
2072 cell : str
2073 The body of the cell as a (possibly multiline) string.
2073 The body of the cell as a (possibly multiline) string.
2074 """
2074 """
2075 fn = self.find_cell_magic(magic_name)
2075 fn = self.find_cell_magic(magic_name)
2076 if fn is None:
2076 if fn is None:
2077 lm = self.find_line_magic(magic_name)
2077 lm = self.find_line_magic(magic_name)
2078 etpl = "Cell magic `%%{0}` not found{1}."
2078 etpl = "Cell magic `%%{0}` not found{1}."
2079 extra = '' if lm is None else (' (But line magic `%{0}` exists, '
2079 extra = '' if lm is None else (' (But line magic `%{0}` exists, '
2080 'did you mean that instead?)'.format(magic_name))
2080 'did you mean that instead?)'.format(magic_name))
2081 error(etpl.format(magic_name, extra))
2081 error(etpl.format(magic_name, extra))
2082 elif cell == '':
2082 elif cell == '':
2083 message = '%%{0} is a cell magic, but the cell body is empty.'.format(magic_name)
2083 message = '%%{0} is a cell magic, but the cell body is empty.'.format(magic_name)
2084 if self.find_line_magic(magic_name) is not None:
2084 if self.find_line_magic(magic_name) is not None:
2085 message += ' Did you mean the line magic %{0} (single %)?'.format(magic_name)
2085 message += ' Did you mean the line magic %{0} (single %)?'.format(magic_name)
2086 raise UsageError(message)
2086 raise UsageError(message)
2087 else:
2087 else:
2088 # Note: this is the distance in the stack to the user's frame.
2088 # Note: this is the distance in the stack to the user's frame.
2089 # This will need to be updated if the internal calling logic gets
2089 # This will need to be updated if the internal calling logic gets
2090 # refactored, or else we'll be expanding the wrong variables.
2090 # refactored, or else we'll be expanding the wrong variables.
2091 stack_depth = 2
2091 stack_depth = 2
2092 magic_arg_s = self.var_expand(line, stack_depth)
2092 magic_arg_s = self.var_expand(line, stack_depth)
2093 with self.builtin_trap:
2093 with self.builtin_trap:
2094 result = fn(magic_arg_s, cell)
2094 result = fn(magic_arg_s, cell)
2095 return result
2095 return result
2096
2096
2097 def find_line_magic(self, magic_name):
2097 def find_line_magic(self, magic_name):
2098 """Find and return a line magic by name.
2098 """Find and return a line magic by name.
2099
2099
2100 Returns None if the magic isn't found."""
2100 Returns None if the magic isn't found."""
2101 return self.magics_manager.magics['line'].get(magic_name)
2101 return self.magics_manager.magics['line'].get(magic_name)
2102
2102
2103 def find_cell_magic(self, magic_name):
2103 def find_cell_magic(self, magic_name):
2104 """Find and return a cell magic by name.
2104 """Find and return a cell magic by name.
2105
2105
2106 Returns None if the magic isn't found."""
2106 Returns None if the magic isn't found."""
2107 return self.magics_manager.magics['cell'].get(magic_name)
2107 return self.magics_manager.magics['cell'].get(magic_name)
2108
2108
2109 def find_magic(self, magic_name, magic_kind='line'):
2109 def find_magic(self, magic_name, magic_kind='line'):
2110 """Find and return a magic of the given type by name.
2110 """Find and return a magic of the given type by name.
2111
2111
2112 Returns None if the magic isn't found."""
2112 Returns None if the magic isn't found."""
2113 return self.magics_manager.magics[magic_kind].get(magic_name)
2113 return self.magics_manager.magics[magic_kind].get(magic_name)
2114
2114
2115 def magic(self, arg_s):
2115 def magic(self, arg_s):
2116 """DEPRECATED. Use run_line_magic() instead.
2116 """DEPRECATED. Use run_line_magic() instead.
2117
2117
2118 Call a magic function by name.
2118 Call a magic function by name.
2119
2119
2120 Input: a string containing the name of the magic function to call and
2120 Input: a string containing the name of the magic function to call and
2121 any additional arguments to be passed to the magic.
2121 any additional arguments to be passed to the magic.
2122
2122
2123 magic('name -opt foo bar') is equivalent to typing at the ipython
2123 magic('name -opt foo bar') is equivalent to typing at the ipython
2124 prompt:
2124 prompt:
2125
2125
2126 In[1]: %name -opt foo bar
2126 In[1]: %name -opt foo bar
2127
2127
2128 To call a magic without arguments, simply use magic('name').
2128 To call a magic without arguments, simply use magic('name').
2129
2129
2130 This provides a proper Python function to call IPython's magics in any
2130 This provides a proper Python function to call IPython's magics in any
2131 valid Python code you can type at the interpreter, including loops and
2131 valid Python code you can type at the interpreter, including loops and
2132 compound statements.
2132 compound statements.
2133 """
2133 """
2134 # TODO: should we issue a loud deprecation warning here?
2134 # TODO: should we issue a loud deprecation warning here?
2135 magic_name, _, magic_arg_s = arg_s.partition(' ')
2135 magic_name, _, magic_arg_s = arg_s.partition(' ')
2136 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
2136 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
2137 return self.run_line_magic(magic_name, magic_arg_s)
2137 return self.run_line_magic(magic_name, magic_arg_s)
2138
2138
2139 #-------------------------------------------------------------------------
2139 #-------------------------------------------------------------------------
2140 # Things related to macros
2140 # Things related to macros
2141 #-------------------------------------------------------------------------
2141 #-------------------------------------------------------------------------
2142
2142
2143 def define_macro(self, name, themacro):
2143 def define_macro(self, name, themacro):
2144 """Define a new macro
2144 """Define a new macro
2145
2145
2146 Parameters
2146 Parameters
2147 ----------
2147 ----------
2148 name : str
2148 name : str
2149 The name of the macro.
2149 The name of the macro.
2150 themacro : str or Macro
2150 themacro : str or Macro
2151 The action to do upon invoking the macro. If a string, a new
2151 The action to do upon invoking the macro. If a string, a new
2152 Macro object is created by passing the string to it.
2152 Macro object is created by passing the string to it.
2153 """
2153 """
2154
2154
2155 from IPython.core import macro
2155 from IPython.core import macro
2156
2156
2157 if isinstance(themacro, string_types):
2157 if isinstance(themacro, string_types):
2158 themacro = macro.Macro(themacro)
2158 themacro = macro.Macro(themacro)
2159 if not isinstance(themacro, macro.Macro):
2159 if not isinstance(themacro, macro.Macro):
2160 raise ValueError('A macro must be a string or a Macro instance.')
2160 raise ValueError('A macro must be a string or a Macro instance.')
2161 self.user_ns[name] = themacro
2161 self.user_ns[name] = themacro
2162
2162
2163 #-------------------------------------------------------------------------
2163 #-------------------------------------------------------------------------
2164 # Things related to the running of system commands
2164 # Things related to the running of system commands
2165 #-------------------------------------------------------------------------
2165 #-------------------------------------------------------------------------
2166
2166
2167 def system_piped(self, cmd):
2167 def system_piped(self, cmd):
2168 """Call the given cmd in a subprocess, piping stdout/err
2168 """Call the given cmd in a subprocess, piping stdout/err
2169
2169
2170 Parameters
2170 Parameters
2171 ----------
2171 ----------
2172 cmd : str
2172 cmd : str
2173 Command to execute (can not end in '&', as background processes are
2173 Command to execute (can not end in '&', as background processes are
2174 not supported. Should not be a command that expects input
2174 not supported. Should not be a command that expects input
2175 other than simple text.
2175 other than simple text.
2176 """
2176 """
2177 if cmd.rstrip().endswith('&'):
2177 if cmd.rstrip().endswith('&'):
2178 # this is *far* from a rigorous test
2178 # this is *far* from a rigorous test
2179 # We do not support backgrounding processes because we either use
2179 # We do not support backgrounding processes because we either use
2180 # pexpect or pipes to read from. Users can always just call
2180 # pexpect or pipes to read from. Users can always just call
2181 # os.system() or use ip.system=ip.system_raw
2181 # os.system() or use ip.system=ip.system_raw
2182 # if they really want a background process.
2182 # if they really want a background process.
2183 raise OSError("Background processes not supported.")
2183 raise OSError("Background processes not supported.")
2184
2184
2185 # we explicitly do NOT return the subprocess status code, because
2185 # we explicitly do NOT return the subprocess status code, because
2186 # a non-None value would trigger :func:`sys.displayhook` calls.
2186 # a non-None value would trigger :func:`sys.displayhook` calls.
2187 # Instead, we store the exit_code in user_ns.
2187 # Instead, we store the exit_code in user_ns.
2188 self.user_ns['_exit_code'] = system(self.var_expand(cmd, depth=1))
2188 self.user_ns['_exit_code'] = system(self.var_expand(cmd, depth=1))
2189
2189
2190 def system_raw(self, cmd):
2190 def system_raw(self, cmd):
2191 """Call the given cmd in a subprocess using os.system on Windows or
2191 """Call the given cmd in a subprocess using os.system on Windows or
2192 subprocess.call using the system shell on other platforms.
2192 subprocess.call using the system shell on other platforms.
2193
2193
2194 Parameters
2194 Parameters
2195 ----------
2195 ----------
2196 cmd : str
2196 cmd : str
2197 Command to execute.
2197 Command to execute.
2198 """
2198 """
2199 cmd = self.var_expand(cmd, depth=1)
2199 cmd = self.var_expand(cmd, depth=1)
2200 # protect os.system from UNC paths on Windows, which it can't handle:
2200 # protect os.system from UNC paths on Windows, which it can't handle:
2201 if sys.platform == 'win32':
2201 if sys.platform == 'win32':
2202 from IPython.utils._process_win32 import AvoidUNCPath
2202 from IPython.utils._process_win32 import AvoidUNCPath
2203 with AvoidUNCPath() as path:
2203 with AvoidUNCPath() as path:
2204 if path is not None:
2204 if path is not None:
2205 cmd = '"pushd %s &&"%s' % (path, cmd)
2205 cmd = '"pushd %s &&"%s' % (path, cmd)
2206 cmd = py3compat.unicode_to_str(cmd)
2206 cmd = py3compat.unicode_to_str(cmd)
2207 try:
2207 try:
2208 ec = os.system(cmd)
2208 ec = os.system(cmd)
2209 except KeyboardInterrupt:
2209 except KeyboardInterrupt:
2210 print('\n' + self.get_exception_only(), file=sys.stderr)
2210 print('\n' + self.get_exception_only(), file=sys.stderr)
2211 ec = -2
2211 ec = -2
2212 else:
2212 else:
2213 cmd = py3compat.unicode_to_str(cmd)
2213 cmd = py3compat.unicode_to_str(cmd)
2214 # For posix the result of the subprocess.call() below is an exit
2214 # For posix the result of the subprocess.call() below is an exit
2215 # code, which by convention is zero for success, positive for
2215 # code, which by convention is zero for success, positive for
2216 # program failure. Exit codes above 128 are reserved for signals,
2216 # program failure. Exit codes above 128 are reserved for signals,
2217 # and the formula for converting a signal to an exit code is usually
2217 # and the formula for converting a signal to an exit code is usually
2218 # signal_number+128. To more easily differentiate between exit
2218 # signal_number+128. To more easily differentiate between exit
2219 # codes and signals, ipython uses negative numbers. For instance
2219 # codes and signals, ipython uses negative numbers. For instance
2220 # since control-c is signal 2 but exit code 130, ipython's
2220 # since control-c is signal 2 but exit code 130, ipython's
2221 # _exit_code variable will read -2. Note that some shells like
2221 # _exit_code variable will read -2. Note that some shells like
2222 # csh and fish don't follow sh/bash conventions for exit codes.
2222 # csh and fish don't follow sh/bash conventions for exit codes.
2223 executable = os.environ.get('SHELL', None)
2223 executable = os.environ.get('SHELL', None)
2224 try:
2224 try:
2225 # Use env shell instead of default /bin/sh
2225 # Use env shell instead of default /bin/sh
2226 ec = subprocess.call(cmd, shell=True, executable=executable)
2226 ec = subprocess.call(cmd, shell=True, executable=executable)
2227 except KeyboardInterrupt:
2227 except KeyboardInterrupt:
2228 # intercept control-C; a long traceback is not useful here
2228 # intercept control-C; a long traceback is not useful here
2229 print('\n' + self.get_exception_only(), file=sys.stderr)
2229 print('\n' + self.get_exception_only(), file=sys.stderr)
2230 ec = 130
2230 ec = 130
2231 if ec > 128:
2231 if ec > 128:
2232 ec = -(ec - 128)
2232 ec = -(ec - 128)
2233
2233
2234 # We explicitly do NOT return the subprocess status code, because
2234 # We explicitly do NOT return the subprocess status code, because
2235 # a non-None value would trigger :func:`sys.displayhook` calls.
2235 # a non-None value would trigger :func:`sys.displayhook` calls.
2236 # Instead, we store the exit_code in user_ns. Note the semantics
2236 # Instead, we store the exit_code in user_ns. Note the semantics
2237 # of _exit_code: for control-c, _exit_code == -signal.SIGNIT,
2237 # of _exit_code: for control-c, _exit_code == -signal.SIGNIT,
2238 # but raising SystemExit(_exit_code) will give status 254!
2238 # but raising SystemExit(_exit_code) will give status 254!
2239 self.user_ns['_exit_code'] = ec
2239 self.user_ns['_exit_code'] = ec
2240
2240
2241 # use piped system by default, because it is better behaved
2241 # use piped system by default, because it is better behaved
2242 system = system_piped
2242 system = system_piped
2243
2243
2244 def getoutput(self, cmd, split=True, depth=0):
2244 def getoutput(self, cmd, split=True, depth=0):
2245 """Get output (possibly including stderr) from a subprocess.
2245 """Get output (possibly including stderr) from a subprocess.
2246
2246
2247 Parameters
2247 Parameters
2248 ----------
2248 ----------
2249 cmd : str
2249 cmd : str
2250 Command to execute (can not end in '&', as background processes are
2250 Command to execute (can not end in '&', as background processes are
2251 not supported.
2251 not supported.
2252 split : bool, optional
2252 split : bool, optional
2253 If True, split the output into an IPython SList. Otherwise, an
2253 If True, split the output into an IPython SList. Otherwise, an
2254 IPython LSString is returned. These are objects similar to normal
2254 IPython LSString is returned. These are objects similar to normal
2255 lists and strings, with a few convenience attributes for easier
2255 lists and strings, with a few convenience attributes for easier
2256 manipulation of line-based output. You can use '?' on them for
2256 manipulation of line-based output. You can use '?' on them for
2257 details.
2257 details.
2258 depth : int, optional
2258 depth : int, optional
2259 How many frames above the caller are the local variables which should
2259 How many frames above the caller are the local variables which should
2260 be expanded in the command string? The default (0) assumes that the
2260 be expanded in the command string? The default (0) assumes that the
2261 expansion variables are in the stack frame calling this function.
2261 expansion variables are in the stack frame calling this function.
2262 """
2262 """
2263 if cmd.rstrip().endswith('&'):
2263 if cmd.rstrip().endswith('&'):
2264 # this is *far* from a rigorous test
2264 # this is *far* from a rigorous test
2265 raise OSError("Background processes not supported.")
2265 raise OSError("Background processes not supported.")
2266 out = getoutput(self.var_expand(cmd, depth=depth+1))
2266 out = getoutput(self.var_expand(cmd, depth=depth+1))
2267 if split:
2267 if split:
2268 out = SList(out.splitlines())
2268 out = SList(out.splitlines())
2269 else:
2269 else:
2270 out = LSString(out)
2270 out = LSString(out)
2271 return out
2271 return out
2272
2272
2273 #-------------------------------------------------------------------------
2273 #-------------------------------------------------------------------------
2274 # Things related to aliases
2274 # Things related to aliases
2275 #-------------------------------------------------------------------------
2275 #-------------------------------------------------------------------------
2276
2276
2277 def init_alias(self):
2277 def init_alias(self):
2278 self.alias_manager = AliasManager(shell=self, parent=self)
2278 self.alias_manager = AliasManager(shell=self, parent=self)
2279 self.configurables.append(self.alias_manager)
2279 self.configurables.append(self.alias_manager)
2280
2280
2281 #-------------------------------------------------------------------------
2281 #-------------------------------------------------------------------------
2282 # Things related to extensions
2282 # Things related to extensions
2283 #-------------------------------------------------------------------------
2283 #-------------------------------------------------------------------------
2284
2284
2285 def init_extension_manager(self):
2285 def init_extension_manager(self):
2286 self.extension_manager = ExtensionManager(shell=self, parent=self)
2286 self.extension_manager = ExtensionManager(shell=self, parent=self)
2287 self.configurables.append(self.extension_manager)
2287 self.configurables.append(self.extension_manager)
2288
2288
2289 #-------------------------------------------------------------------------
2289 #-------------------------------------------------------------------------
2290 # Things related to payloads
2290 # Things related to payloads
2291 #-------------------------------------------------------------------------
2291 #-------------------------------------------------------------------------
2292
2292
2293 def init_payload(self):
2293 def init_payload(self):
2294 self.payload_manager = PayloadManager(parent=self)
2294 self.payload_manager = PayloadManager(parent=self)
2295 self.configurables.append(self.payload_manager)
2295 self.configurables.append(self.payload_manager)
2296
2296
2297 #-------------------------------------------------------------------------
2297 #-------------------------------------------------------------------------
2298 # Things related to the prefilter
2298 # Things related to the prefilter
2299 #-------------------------------------------------------------------------
2299 #-------------------------------------------------------------------------
2300
2300
2301 def init_prefilter(self):
2301 def init_prefilter(self):
2302 self.prefilter_manager = PrefilterManager(shell=self, parent=self)
2302 self.prefilter_manager = PrefilterManager(shell=self, parent=self)
2303 self.configurables.append(self.prefilter_manager)
2303 self.configurables.append(self.prefilter_manager)
2304 # Ultimately this will be refactored in the new interpreter code, but
2304 # Ultimately this will be refactored in the new interpreter code, but
2305 # for now, we should expose the main prefilter method (there's legacy
2305 # for now, we should expose the main prefilter method (there's legacy
2306 # code out there that may rely on this).
2306 # code out there that may rely on this).
2307 self.prefilter = self.prefilter_manager.prefilter_lines
2307 self.prefilter = self.prefilter_manager.prefilter_lines
2308
2308
2309 def auto_rewrite_input(self, cmd):
2309 def auto_rewrite_input(self, cmd):
2310 """Print to the screen the rewritten form of the user's command.
2310 """Print to the screen the rewritten form of the user's command.
2311
2311
2312 This shows visual feedback by rewriting input lines that cause
2312 This shows visual feedback by rewriting input lines that cause
2313 automatic calling to kick in, like::
2313 automatic calling to kick in, like::
2314
2314
2315 /f x
2315 /f x
2316
2316
2317 into::
2317 into::
2318
2318
2319 ------> f(x)
2319 ------> f(x)
2320
2320
2321 after the user's input prompt. This helps the user understand that the
2321 after the user's input prompt. This helps the user understand that the
2322 input line was transformed automatically by IPython.
2322 input line was transformed automatically by IPython.
2323 """
2323 """
2324 if not self.show_rewritten_input:
2324 if not self.show_rewritten_input:
2325 return
2325 return
2326
2326
2327 # This is overridden in TerminalInteractiveShell to use fancy prompts
2327 # This is overridden in TerminalInteractiveShell to use fancy prompts
2328 print("------> " + cmd)
2328 print("------> " + cmd)
2329
2329
2330 #-------------------------------------------------------------------------
2330 #-------------------------------------------------------------------------
2331 # Things related to extracting values/expressions from kernel and user_ns
2331 # Things related to extracting values/expressions from kernel and user_ns
2332 #-------------------------------------------------------------------------
2332 #-------------------------------------------------------------------------
2333
2333
2334 def _user_obj_error(self):
2334 def _user_obj_error(self):
2335 """return simple exception dict
2335 """return simple exception dict
2336
2336
2337 for use in user_expressions
2337 for use in user_expressions
2338 """
2338 """
2339
2339
2340 etype, evalue, tb = self._get_exc_info()
2340 etype, evalue, tb = self._get_exc_info()
2341 stb = self.InteractiveTB.get_exception_only(etype, evalue)
2341 stb = self.InteractiveTB.get_exception_only(etype, evalue)
2342
2342
2343 exc_info = {
2343 exc_info = {
2344 u'status' : 'error',
2344 u'status' : 'error',
2345 u'traceback' : stb,
2345 u'traceback' : stb,
2346 u'ename' : unicode_type(etype.__name__),
2346 u'ename' : unicode_type(etype.__name__),
2347 u'evalue' : py3compat.safe_unicode(evalue),
2347 u'evalue' : py3compat.safe_unicode(evalue),
2348 }
2348 }
2349
2349
2350 return exc_info
2350 return exc_info
2351
2351
2352 def _format_user_obj(self, obj):
2352 def _format_user_obj(self, obj):
2353 """format a user object to display dict
2353 """format a user object to display dict
2354
2354
2355 for use in user_expressions
2355 for use in user_expressions
2356 """
2356 """
2357
2357
2358 data, md = self.display_formatter.format(obj)
2358 data, md = self.display_formatter.format(obj)
2359 value = {
2359 value = {
2360 'status' : 'ok',
2360 'status' : 'ok',
2361 'data' : data,
2361 'data' : data,
2362 'metadata' : md,
2362 'metadata' : md,
2363 }
2363 }
2364 return value
2364 return value
2365
2365
2366 def user_expressions(self, expressions):
2366 def user_expressions(self, expressions):
2367 """Evaluate a dict of expressions in the user's namespace.
2367 """Evaluate a dict of expressions in the user's namespace.
2368
2368
2369 Parameters
2369 Parameters
2370 ----------
2370 ----------
2371 expressions : dict
2371 expressions : dict
2372 A dict with string keys and string values. The expression values
2372 A dict with string keys and string values. The expression values
2373 should be valid Python expressions, each of which will be evaluated
2373 should be valid Python expressions, each of which will be evaluated
2374 in the user namespace.
2374 in the user namespace.
2375
2375
2376 Returns
2376 Returns
2377 -------
2377 -------
2378 A dict, keyed like the input expressions dict, with the rich mime-typed
2378 A dict, keyed like the input expressions dict, with the rich mime-typed
2379 display_data of each value.
2379 display_data of each value.
2380 """
2380 """
2381 out = {}
2381 out = {}
2382 user_ns = self.user_ns
2382 user_ns = self.user_ns
2383 global_ns = self.user_global_ns
2383 global_ns = self.user_global_ns
2384
2384
2385 for key, expr in iteritems(expressions):
2385 for key, expr in expressions.items():
2386 try:
2386 try:
2387 value = self._format_user_obj(eval(expr, global_ns, user_ns))
2387 value = self._format_user_obj(eval(expr, global_ns, user_ns))
2388 except:
2388 except:
2389 value = self._user_obj_error()
2389 value = self._user_obj_error()
2390 out[key] = value
2390 out[key] = value
2391 return out
2391 return out
2392
2392
2393 #-------------------------------------------------------------------------
2393 #-------------------------------------------------------------------------
2394 # Things related to the running of code
2394 # Things related to the running of code
2395 #-------------------------------------------------------------------------
2395 #-------------------------------------------------------------------------
2396
2396
2397 def ex(self, cmd):
2397 def ex(self, cmd):
2398 """Execute a normal python statement in user namespace."""
2398 """Execute a normal python statement in user namespace."""
2399 with self.builtin_trap:
2399 with self.builtin_trap:
2400 exec(cmd, self.user_global_ns, self.user_ns)
2400 exec(cmd, self.user_global_ns, self.user_ns)
2401
2401
2402 def ev(self, expr):
2402 def ev(self, expr):
2403 """Evaluate python expression expr in user namespace.
2403 """Evaluate python expression expr in user namespace.
2404
2404
2405 Returns the result of evaluation
2405 Returns the result of evaluation
2406 """
2406 """
2407 with self.builtin_trap:
2407 with self.builtin_trap:
2408 return eval(expr, self.user_global_ns, self.user_ns)
2408 return eval(expr, self.user_global_ns, self.user_ns)
2409
2409
2410 def safe_execfile(self, fname, *where, **kw):
2410 def safe_execfile(self, fname, *where, **kw):
2411 """A safe version of the builtin execfile().
2411 """A safe version of the builtin execfile().
2412
2412
2413 This version will never throw an exception, but instead print
2413 This version will never throw an exception, but instead print
2414 helpful error messages to the screen. This only works on pure
2414 helpful error messages to the screen. This only works on pure
2415 Python files with the .py extension.
2415 Python files with the .py extension.
2416
2416
2417 Parameters
2417 Parameters
2418 ----------
2418 ----------
2419 fname : string
2419 fname : string
2420 The name of the file to be executed.
2420 The name of the file to be executed.
2421 where : tuple
2421 where : tuple
2422 One or two namespaces, passed to execfile() as (globals,locals).
2422 One or two namespaces, passed to execfile() as (globals,locals).
2423 If only one is given, it is passed as both.
2423 If only one is given, it is passed as both.
2424 exit_ignore : bool (False)
2424 exit_ignore : bool (False)
2425 If True, then silence SystemExit for non-zero status (it is always
2425 If True, then silence SystemExit for non-zero status (it is always
2426 silenced for zero status, as it is so common).
2426 silenced for zero status, as it is so common).
2427 raise_exceptions : bool (False)
2427 raise_exceptions : bool (False)
2428 If True raise exceptions everywhere. Meant for testing.
2428 If True raise exceptions everywhere. Meant for testing.
2429 shell_futures : bool (False)
2429 shell_futures : bool (False)
2430 If True, the code will share future statements with the interactive
2430 If True, the code will share future statements with the interactive
2431 shell. It will both be affected by previous __future__ imports, and
2431 shell. It will both be affected by previous __future__ imports, and
2432 any __future__ imports in the code will affect the shell. If False,
2432 any __future__ imports in the code will affect the shell. If False,
2433 __future__ imports are not shared in either direction.
2433 __future__ imports are not shared in either direction.
2434
2434
2435 """
2435 """
2436 kw.setdefault('exit_ignore', False)
2436 kw.setdefault('exit_ignore', False)
2437 kw.setdefault('raise_exceptions', False)
2437 kw.setdefault('raise_exceptions', False)
2438 kw.setdefault('shell_futures', False)
2438 kw.setdefault('shell_futures', False)
2439
2439
2440 fname = os.path.abspath(os.path.expanduser(fname))
2440 fname = os.path.abspath(os.path.expanduser(fname))
2441
2441
2442 # Make sure we can open the file
2442 # Make sure we can open the file
2443 try:
2443 try:
2444 with open(fname):
2444 with open(fname):
2445 pass
2445 pass
2446 except:
2446 except:
2447 warn('Could not open file <%s> for safe execution.' % fname)
2447 warn('Could not open file <%s> for safe execution.' % fname)
2448 return
2448 return
2449
2449
2450 # Find things also in current directory. This is needed to mimic the
2450 # Find things also in current directory. This is needed to mimic the
2451 # behavior of running a script from the system command line, where
2451 # behavior of running a script from the system command line, where
2452 # Python inserts the script's directory into sys.path
2452 # Python inserts the script's directory into sys.path
2453 dname = os.path.dirname(fname)
2453 dname = os.path.dirname(fname)
2454
2454
2455 with prepended_to_syspath(dname), self.builtin_trap:
2455 with prepended_to_syspath(dname), self.builtin_trap:
2456 try:
2456 try:
2457 glob, loc = (where + (None, ))[:2]
2457 glob, loc = (where + (None, ))[:2]
2458 py3compat.execfile(
2458 py3compat.execfile(
2459 fname, glob, loc,
2459 fname, glob, loc,
2460 self.compile if kw['shell_futures'] else None)
2460 self.compile if kw['shell_futures'] else None)
2461 except SystemExit as status:
2461 except SystemExit as status:
2462 # If the call was made with 0 or None exit status (sys.exit(0)
2462 # If the call was made with 0 or None exit status (sys.exit(0)
2463 # or sys.exit() ), don't bother showing a traceback, as both of
2463 # or sys.exit() ), don't bother showing a traceback, as both of
2464 # these are considered normal by the OS:
2464 # these are considered normal by the OS:
2465 # > python -c'import sys;sys.exit(0)'; echo $?
2465 # > python -c'import sys;sys.exit(0)'; echo $?
2466 # 0
2466 # 0
2467 # > python -c'import sys;sys.exit()'; echo $?
2467 # > python -c'import sys;sys.exit()'; echo $?
2468 # 0
2468 # 0
2469 # For other exit status, we show the exception unless
2469 # For other exit status, we show the exception unless
2470 # explicitly silenced, but only in short form.
2470 # explicitly silenced, but only in short form.
2471 if status.code:
2471 if status.code:
2472 if kw['raise_exceptions']:
2472 if kw['raise_exceptions']:
2473 raise
2473 raise
2474 if not kw['exit_ignore']:
2474 if not kw['exit_ignore']:
2475 self.showtraceback(exception_only=True)
2475 self.showtraceback(exception_only=True)
2476 except:
2476 except:
2477 if kw['raise_exceptions']:
2477 if kw['raise_exceptions']:
2478 raise
2478 raise
2479 # tb offset is 2 because we wrap execfile
2479 # tb offset is 2 because we wrap execfile
2480 self.showtraceback(tb_offset=2)
2480 self.showtraceback(tb_offset=2)
2481
2481
2482 def safe_execfile_ipy(self, fname, shell_futures=False, raise_exceptions=False):
2482 def safe_execfile_ipy(self, fname, shell_futures=False, raise_exceptions=False):
2483 """Like safe_execfile, but for .ipy or .ipynb files with IPython syntax.
2483 """Like safe_execfile, but for .ipy or .ipynb files with IPython syntax.
2484
2484
2485 Parameters
2485 Parameters
2486 ----------
2486 ----------
2487 fname : str
2487 fname : str
2488 The name of the file to execute. The filename must have a
2488 The name of the file to execute. The filename must have a
2489 .ipy or .ipynb extension.
2489 .ipy or .ipynb extension.
2490 shell_futures : bool (False)
2490 shell_futures : bool (False)
2491 If True, the code will share future statements with the interactive
2491 If True, the code will share future statements with the interactive
2492 shell. It will both be affected by previous __future__ imports, and
2492 shell. It will both be affected by previous __future__ imports, and
2493 any __future__ imports in the code will affect the shell. If False,
2493 any __future__ imports in the code will affect the shell. If False,
2494 __future__ imports are not shared in either direction.
2494 __future__ imports are not shared in either direction.
2495 raise_exceptions : bool (False)
2495 raise_exceptions : bool (False)
2496 If True raise exceptions everywhere. Meant for testing.
2496 If True raise exceptions everywhere. Meant for testing.
2497 """
2497 """
2498 fname = os.path.abspath(os.path.expanduser(fname))
2498 fname = os.path.abspath(os.path.expanduser(fname))
2499
2499
2500 # Make sure we can open the file
2500 # Make sure we can open the file
2501 try:
2501 try:
2502 with open(fname):
2502 with open(fname):
2503 pass
2503 pass
2504 except:
2504 except:
2505 warn('Could not open file <%s> for safe execution.' % fname)
2505 warn('Could not open file <%s> for safe execution.' % fname)
2506 return
2506 return
2507
2507
2508 # Find things also in current directory. This is needed to mimic the
2508 # Find things also in current directory. This is needed to mimic the
2509 # behavior of running a script from the system command line, where
2509 # behavior of running a script from the system command line, where
2510 # Python inserts the script's directory into sys.path
2510 # Python inserts the script's directory into sys.path
2511 dname = os.path.dirname(fname)
2511 dname = os.path.dirname(fname)
2512
2512
2513 def get_cells():
2513 def get_cells():
2514 """generator for sequence of code blocks to run"""
2514 """generator for sequence of code blocks to run"""
2515 if fname.endswith('.ipynb'):
2515 if fname.endswith('.ipynb'):
2516 from nbformat import read
2516 from nbformat import read
2517 with io_open(fname) as f:
2517 with io_open(fname) as f:
2518 nb = read(f, as_version=4)
2518 nb = read(f, as_version=4)
2519 if not nb.cells:
2519 if not nb.cells:
2520 return
2520 return
2521 for cell in nb.cells:
2521 for cell in nb.cells:
2522 if cell.cell_type == 'code':
2522 if cell.cell_type == 'code':
2523 yield cell.source
2523 yield cell.source
2524 else:
2524 else:
2525 with open(fname) as f:
2525 with open(fname) as f:
2526 yield f.read()
2526 yield f.read()
2527
2527
2528 with prepended_to_syspath(dname):
2528 with prepended_to_syspath(dname):
2529 try:
2529 try:
2530 for cell in get_cells():
2530 for cell in get_cells():
2531 result = self.run_cell(cell, silent=True, shell_futures=shell_futures)
2531 result = self.run_cell(cell, silent=True, shell_futures=shell_futures)
2532 if raise_exceptions:
2532 if raise_exceptions:
2533 result.raise_error()
2533 result.raise_error()
2534 elif not result.success:
2534 elif not result.success:
2535 break
2535 break
2536 except:
2536 except:
2537 if raise_exceptions:
2537 if raise_exceptions:
2538 raise
2538 raise
2539 self.showtraceback()
2539 self.showtraceback()
2540 warn('Unknown failure executing file: <%s>' % fname)
2540 warn('Unknown failure executing file: <%s>' % fname)
2541
2541
2542 def safe_run_module(self, mod_name, where):
2542 def safe_run_module(self, mod_name, where):
2543 """A safe version of runpy.run_module().
2543 """A safe version of runpy.run_module().
2544
2544
2545 This version will never throw an exception, but instead print
2545 This version will never throw an exception, but instead print
2546 helpful error messages to the screen.
2546 helpful error messages to the screen.
2547
2547
2548 `SystemExit` exceptions with status code 0 or None are ignored.
2548 `SystemExit` exceptions with status code 0 or None are ignored.
2549
2549
2550 Parameters
2550 Parameters
2551 ----------
2551 ----------
2552 mod_name : string
2552 mod_name : string
2553 The name of the module to be executed.
2553 The name of the module to be executed.
2554 where : dict
2554 where : dict
2555 The globals namespace.
2555 The globals namespace.
2556 """
2556 """
2557 try:
2557 try:
2558 try:
2558 try:
2559 where.update(
2559 where.update(
2560 runpy.run_module(str(mod_name), run_name="__main__",
2560 runpy.run_module(str(mod_name), run_name="__main__",
2561 alter_sys=True)
2561 alter_sys=True)
2562 )
2562 )
2563 except SystemExit as status:
2563 except SystemExit as status:
2564 if status.code:
2564 if status.code:
2565 raise
2565 raise
2566 except:
2566 except:
2567 self.showtraceback()
2567 self.showtraceback()
2568 warn('Unknown failure executing module: <%s>' % mod_name)
2568 warn('Unknown failure executing module: <%s>' % mod_name)
2569
2569
2570 def run_cell(self, raw_cell, store_history=False, silent=False, shell_futures=True):
2570 def run_cell(self, raw_cell, store_history=False, silent=False, shell_futures=True):
2571 """Run a complete IPython cell.
2571 """Run a complete IPython cell.
2572
2572
2573 Parameters
2573 Parameters
2574 ----------
2574 ----------
2575 raw_cell : str
2575 raw_cell : str
2576 The code (including IPython code such as %magic functions) to run.
2576 The code (including IPython code such as %magic functions) to run.
2577 store_history : bool
2577 store_history : bool
2578 If True, the raw and translated cell will be stored in IPython's
2578 If True, the raw and translated cell will be stored in IPython's
2579 history. For user code calling back into IPython's machinery, this
2579 history. For user code calling back into IPython's machinery, this
2580 should be set to False.
2580 should be set to False.
2581 silent : bool
2581 silent : bool
2582 If True, avoid side-effects, such as implicit displayhooks and
2582 If True, avoid side-effects, such as implicit displayhooks and
2583 and logging. silent=True forces store_history=False.
2583 and logging. silent=True forces store_history=False.
2584 shell_futures : bool
2584 shell_futures : bool
2585 If True, the code will share future statements with the interactive
2585 If True, the code will share future statements with the interactive
2586 shell. It will both be affected by previous __future__ imports, and
2586 shell. It will both be affected by previous __future__ imports, and
2587 any __future__ imports in the code will affect the shell. If False,
2587 any __future__ imports in the code will affect the shell. If False,
2588 __future__ imports are not shared in either direction.
2588 __future__ imports are not shared in either direction.
2589
2589
2590 Returns
2590 Returns
2591 -------
2591 -------
2592 result : :class:`ExecutionResult`
2592 result : :class:`ExecutionResult`
2593 """
2593 """
2594 result = ExecutionResult()
2594 result = ExecutionResult()
2595
2595
2596 if (not raw_cell) or raw_cell.isspace():
2596 if (not raw_cell) or raw_cell.isspace():
2597 self.last_execution_succeeded = True
2597 self.last_execution_succeeded = True
2598 return result
2598 return result
2599
2599
2600 if silent:
2600 if silent:
2601 store_history = False
2601 store_history = False
2602
2602
2603 if store_history:
2603 if store_history:
2604 result.execution_count = self.execution_count
2604 result.execution_count = self.execution_count
2605
2605
2606 def error_before_exec(value):
2606 def error_before_exec(value):
2607 result.error_before_exec = value
2607 result.error_before_exec = value
2608 self.last_execution_succeeded = False
2608 self.last_execution_succeeded = False
2609 return result
2609 return result
2610
2610
2611 self.events.trigger('pre_execute')
2611 self.events.trigger('pre_execute')
2612 if not silent:
2612 if not silent:
2613 self.events.trigger('pre_run_cell')
2613 self.events.trigger('pre_run_cell')
2614
2614
2615 # If any of our input transformation (input_transformer_manager or
2615 # If any of our input transformation (input_transformer_manager or
2616 # prefilter_manager) raises an exception, we store it in this variable
2616 # prefilter_manager) raises an exception, we store it in this variable
2617 # so that we can display the error after logging the input and storing
2617 # so that we can display the error after logging the input and storing
2618 # it in the history.
2618 # it in the history.
2619 preprocessing_exc_tuple = None
2619 preprocessing_exc_tuple = None
2620 try:
2620 try:
2621 # Static input transformations
2621 # Static input transformations
2622 cell = self.input_transformer_manager.transform_cell(raw_cell)
2622 cell = self.input_transformer_manager.transform_cell(raw_cell)
2623 except SyntaxError:
2623 except SyntaxError:
2624 preprocessing_exc_tuple = sys.exc_info()
2624 preprocessing_exc_tuple = sys.exc_info()
2625 cell = raw_cell # cell has to exist so it can be stored/logged
2625 cell = raw_cell # cell has to exist so it can be stored/logged
2626 else:
2626 else:
2627 if len(cell.splitlines()) == 1:
2627 if len(cell.splitlines()) == 1:
2628 # Dynamic transformations - only applied for single line commands
2628 # Dynamic transformations - only applied for single line commands
2629 with self.builtin_trap:
2629 with self.builtin_trap:
2630 try:
2630 try:
2631 # use prefilter_lines to handle trailing newlines
2631 # use prefilter_lines to handle trailing newlines
2632 # restore trailing newline for ast.parse
2632 # restore trailing newline for ast.parse
2633 cell = self.prefilter_manager.prefilter_lines(cell) + '\n'
2633 cell = self.prefilter_manager.prefilter_lines(cell) + '\n'
2634 except Exception:
2634 except Exception:
2635 # don't allow prefilter errors to crash IPython
2635 # don't allow prefilter errors to crash IPython
2636 preprocessing_exc_tuple = sys.exc_info()
2636 preprocessing_exc_tuple = sys.exc_info()
2637
2637
2638 # Store raw and processed history
2638 # Store raw and processed history
2639 if store_history:
2639 if store_history:
2640 self.history_manager.store_inputs(self.execution_count,
2640 self.history_manager.store_inputs(self.execution_count,
2641 cell, raw_cell)
2641 cell, raw_cell)
2642 if not silent:
2642 if not silent:
2643 self.logger.log(cell, raw_cell)
2643 self.logger.log(cell, raw_cell)
2644
2644
2645 # Display the exception if input processing failed.
2645 # Display the exception if input processing failed.
2646 if preprocessing_exc_tuple is not None:
2646 if preprocessing_exc_tuple is not None:
2647 self.showtraceback(preprocessing_exc_tuple)
2647 self.showtraceback(preprocessing_exc_tuple)
2648 if store_history:
2648 if store_history:
2649 self.execution_count += 1
2649 self.execution_count += 1
2650 return error_before_exec(preprocessing_exc_tuple[2])
2650 return error_before_exec(preprocessing_exc_tuple[2])
2651
2651
2652 # Our own compiler remembers the __future__ environment. If we want to
2652 # Our own compiler remembers the __future__ environment. If we want to
2653 # run code with a separate __future__ environment, use the default
2653 # run code with a separate __future__ environment, use the default
2654 # compiler
2654 # compiler
2655 compiler = self.compile if shell_futures else CachingCompiler()
2655 compiler = self.compile if shell_futures else CachingCompiler()
2656
2656
2657 with self.builtin_trap:
2657 with self.builtin_trap:
2658 cell_name = self.compile.cache(cell, self.execution_count)
2658 cell_name = self.compile.cache(cell, self.execution_count)
2659
2659
2660 with self.display_trap:
2660 with self.display_trap:
2661 # Compile to bytecode
2661 # Compile to bytecode
2662 try:
2662 try:
2663 code_ast = compiler.ast_parse(cell, filename=cell_name)
2663 code_ast = compiler.ast_parse(cell, filename=cell_name)
2664 except self.custom_exceptions as e:
2664 except self.custom_exceptions as e:
2665 etype, value, tb = sys.exc_info()
2665 etype, value, tb = sys.exc_info()
2666 self.CustomTB(etype, value, tb)
2666 self.CustomTB(etype, value, tb)
2667 return error_before_exec(e)
2667 return error_before_exec(e)
2668 except IndentationError as e:
2668 except IndentationError as e:
2669 self.showindentationerror()
2669 self.showindentationerror()
2670 if store_history:
2670 if store_history:
2671 self.execution_count += 1
2671 self.execution_count += 1
2672 return error_before_exec(e)
2672 return error_before_exec(e)
2673 except (OverflowError, SyntaxError, ValueError, TypeError,
2673 except (OverflowError, SyntaxError, ValueError, TypeError,
2674 MemoryError) as e:
2674 MemoryError) as e:
2675 self.showsyntaxerror()
2675 self.showsyntaxerror()
2676 if store_history:
2676 if store_history:
2677 self.execution_count += 1
2677 self.execution_count += 1
2678 return error_before_exec(e)
2678 return error_before_exec(e)
2679
2679
2680 # Apply AST transformations
2680 # Apply AST transformations
2681 try:
2681 try:
2682 code_ast = self.transform_ast(code_ast)
2682 code_ast = self.transform_ast(code_ast)
2683 except InputRejected as e:
2683 except InputRejected as e:
2684 self.showtraceback()
2684 self.showtraceback()
2685 if store_history:
2685 if store_history:
2686 self.execution_count += 1
2686 self.execution_count += 1
2687 return error_before_exec(e)
2687 return error_before_exec(e)
2688
2688
2689 # Give the displayhook a reference to our ExecutionResult so it
2689 # Give the displayhook a reference to our ExecutionResult so it
2690 # can fill in the output value.
2690 # can fill in the output value.
2691 self.displayhook.exec_result = result
2691 self.displayhook.exec_result = result
2692
2692
2693 # Execute the user code
2693 # Execute the user code
2694 interactivity = "none" if silent else self.ast_node_interactivity
2694 interactivity = "none" if silent else self.ast_node_interactivity
2695 has_raised = self.run_ast_nodes(code_ast.body, cell_name,
2695 has_raised = self.run_ast_nodes(code_ast.body, cell_name,
2696 interactivity=interactivity, compiler=compiler, result=result)
2696 interactivity=interactivity, compiler=compiler, result=result)
2697
2697
2698 self.last_execution_succeeded = not has_raised
2698 self.last_execution_succeeded = not has_raised
2699
2699
2700 # Reset this so later displayed values do not modify the
2700 # Reset this so later displayed values do not modify the
2701 # ExecutionResult
2701 # ExecutionResult
2702 self.displayhook.exec_result = None
2702 self.displayhook.exec_result = None
2703
2703
2704 self.events.trigger('post_execute')
2704 self.events.trigger('post_execute')
2705 if not silent:
2705 if not silent:
2706 self.events.trigger('post_run_cell')
2706 self.events.trigger('post_run_cell')
2707
2707
2708 if store_history:
2708 if store_history:
2709 # Write output to the database. Does nothing unless
2709 # Write output to the database. Does nothing unless
2710 # history output logging is enabled.
2710 # history output logging is enabled.
2711 self.history_manager.store_output(self.execution_count)
2711 self.history_manager.store_output(self.execution_count)
2712 # Each cell is a *single* input, regardless of how many lines it has
2712 # Each cell is a *single* input, regardless of how many lines it has
2713 self.execution_count += 1
2713 self.execution_count += 1
2714
2714
2715 return result
2715 return result
2716
2716
2717 def transform_ast(self, node):
2717 def transform_ast(self, node):
2718 """Apply the AST transformations from self.ast_transformers
2718 """Apply the AST transformations from self.ast_transformers
2719
2719
2720 Parameters
2720 Parameters
2721 ----------
2721 ----------
2722 node : ast.Node
2722 node : ast.Node
2723 The root node to be transformed. Typically called with the ast.Module
2723 The root node to be transformed. Typically called with the ast.Module
2724 produced by parsing user input.
2724 produced by parsing user input.
2725
2725
2726 Returns
2726 Returns
2727 -------
2727 -------
2728 An ast.Node corresponding to the node it was called with. Note that it
2728 An ast.Node corresponding to the node it was called with. Note that it
2729 may also modify the passed object, so don't rely on references to the
2729 may also modify the passed object, so don't rely on references to the
2730 original AST.
2730 original AST.
2731 """
2731 """
2732 for transformer in self.ast_transformers:
2732 for transformer in self.ast_transformers:
2733 try:
2733 try:
2734 node = transformer.visit(node)
2734 node = transformer.visit(node)
2735 except InputRejected:
2735 except InputRejected:
2736 # User-supplied AST transformers can reject an input by raising
2736 # User-supplied AST transformers can reject an input by raising
2737 # an InputRejected. Short-circuit in this case so that we
2737 # an InputRejected. Short-circuit in this case so that we
2738 # don't unregister the transform.
2738 # don't unregister the transform.
2739 raise
2739 raise
2740 except Exception:
2740 except Exception:
2741 warn("AST transformer %r threw an error. It will be unregistered." % transformer)
2741 warn("AST transformer %r threw an error. It will be unregistered." % transformer)
2742 self.ast_transformers.remove(transformer)
2742 self.ast_transformers.remove(transformer)
2743
2743
2744 if self.ast_transformers:
2744 if self.ast_transformers:
2745 ast.fix_missing_locations(node)
2745 ast.fix_missing_locations(node)
2746 return node
2746 return node
2747
2747
2748
2748
2749 def run_ast_nodes(self, nodelist, cell_name, interactivity='last_expr',
2749 def run_ast_nodes(self, nodelist, cell_name, interactivity='last_expr',
2750 compiler=compile, result=None):
2750 compiler=compile, result=None):
2751 """Run a sequence of AST nodes. The execution mode depends on the
2751 """Run a sequence of AST nodes. The execution mode depends on the
2752 interactivity parameter.
2752 interactivity parameter.
2753
2753
2754 Parameters
2754 Parameters
2755 ----------
2755 ----------
2756 nodelist : list
2756 nodelist : list
2757 A sequence of AST nodes to run.
2757 A sequence of AST nodes to run.
2758 cell_name : str
2758 cell_name : str
2759 Will be passed to the compiler as the filename of the cell. Typically
2759 Will be passed to the compiler as the filename of the cell. Typically
2760 the value returned by ip.compile.cache(cell).
2760 the value returned by ip.compile.cache(cell).
2761 interactivity : str
2761 interactivity : str
2762 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
2762 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
2763 run interactively (displaying output from expressions). 'last_expr'
2763 run interactively (displaying output from expressions). 'last_expr'
2764 will run the last node interactively only if it is an expression (i.e.
2764 will run the last node interactively only if it is an expression (i.e.
2765 expressions in loops or other blocks are not displayed. Other values
2765 expressions in loops or other blocks are not displayed. Other values
2766 for this parameter will raise a ValueError.
2766 for this parameter will raise a ValueError.
2767 compiler : callable
2767 compiler : callable
2768 A function with the same interface as the built-in compile(), to turn
2768 A function with the same interface as the built-in compile(), to turn
2769 the AST nodes into code objects. Default is the built-in compile().
2769 the AST nodes into code objects. Default is the built-in compile().
2770 result : ExecutionResult, optional
2770 result : ExecutionResult, optional
2771 An object to store exceptions that occur during execution.
2771 An object to store exceptions that occur during execution.
2772
2772
2773 Returns
2773 Returns
2774 -------
2774 -------
2775 True if an exception occurred while running code, False if it finished
2775 True if an exception occurred while running code, False if it finished
2776 running.
2776 running.
2777 """
2777 """
2778 if not nodelist:
2778 if not nodelist:
2779 return
2779 return
2780
2780
2781 if interactivity == 'last_expr':
2781 if interactivity == 'last_expr':
2782 if isinstance(nodelist[-1], ast.Expr):
2782 if isinstance(nodelist[-1], ast.Expr):
2783 interactivity = "last"
2783 interactivity = "last"
2784 else:
2784 else:
2785 interactivity = "none"
2785 interactivity = "none"
2786
2786
2787 if interactivity == 'none':
2787 if interactivity == 'none':
2788 to_run_exec, to_run_interactive = nodelist, []
2788 to_run_exec, to_run_interactive = nodelist, []
2789 elif interactivity == 'last':
2789 elif interactivity == 'last':
2790 to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:]
2790 to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:]
2791 elif interactivity == 'all':
2791 elif interactivity == 'all':
2792 to_run_exec, to_run_interactive = [], nodelist
2792 to_run_exec, to_run_interactive = [], nodelist
2793 else:
2793 else:
2794 raise ValueError("Interactivity was %r" % interactivity)
2794 raise ValueError("Interactivity was %r" % interactivity)
2795
2795
2796 try:
2796 try:
2797 for i, node in enumerate(to_run_exec):
2797 for i, node in enumerate(to_run_exec):
2798 mod = ast.Module([node])
2798 mod = ast.Module([node])
2799 code = compiler(mod, cell_name, "exec")
2799 code = compiler(mod, cell_name, "exec")
2800 if self.run_code(code, result):
2800 if self.run_code(code, result):
2801 return True
2801 return True
2802
2802
2803 for i, node in enumerate(to_run_interactive):
2803 for i, node in enumerate(to_run_interactive):
2804 mod = ast.Interactive([node])
2804 mod = ast.Interactive([node])
2805 code = compiler(mod, cell_name, "single")
2805 code = compiler(mod, cell_name, "single")
2806 if self.run_code(code, result):
2806 if self.run_code(code, result):
2807 return True
2807 return True
2808
2808
2809 # Flush softspace
2809 # Flush softspace
2810 if softspace(sys.stdout, 0):
2810 if softspace(sys.stdout, 0):
2811 print()
2811 print()
2812
2812
2813 except:
2813 except:
2814 # It's possible to have exceptions raised here, typically by
2814 # It's possible to have exceptions raised here, typically by
2815 # compilation of odd code (such as a naked 'return' outside a
2815 # compilation of odd code (such as a naked 'return' outside a
2816 # function) that did parse but isn't valid. Typically the exception
2816 # function) that did parse but isn't valid. Typically the exception
2817 # is a SyntaxError, but it's safest just to catch anything and show
2817 # is a SyntaxError, but it's safest just to catch anything and show
2818 # the user a traceback.
2818 # the user a traceback.
2819
2819
2820 # We do only one try/except outside the loop to minimize the impact
2820 # We do only one try/except outside the loop to minimize the impact
2821 # on runtime, and also because if any node in the node list is
2821 # on runtime, and also because if any node in the node list is
2822 # broken, we should stop execution completely.
2822 # broken, we should stop execution completely.
2823 if result:
2823 if result:
2824 result.error_before_exec = sys.exc_info()[1]
2824 result.error_before_exec = sys.exc_info()[1]
2825 self.showtraceback()
2825 self.showtraceback()
2826 return True
2826 return True
2827
2827
2828 return False
2828 return False
2829
2829
2830 def run_code(self, code_obj, result=None):
2830 def run_code(self, code_obj, result=None):
2831 """Execute a code object.
2831 """Execute a code object.
2832
2832
2833 When an exception occurs, self.showtraceback() is called to display a
2833 When an exception occurs, self.showtraceback() is called to display a
2834 traceback.
2834 traceback.
2835
2835
2836 Parameters
2836 Parameters
2837 ----------
2837 ----------
2838 code_obj : code object
2838 code_obj : code object
2839 A compiled code object, to be executed
2839 A compiled code object, to be executed
2840 result : ExecutionResult, optional
2840 result : ExecutionResult, optional
2841 An object to store exceptions that occur during execution.
2841 An object to store exceptions that occur during execution.
2842
2842
2843 Returns
2843 Returns
2844 -------
2844 -------
2845 False : successful execution.
2845 False : successful execution.
2846 True : an error occurred.
2846 True : an error occurred.
2847 """
2847 """
2848 # Set our own excepthook in case the user code tries to call it
2848 # Set our own excepthook in case the user code tries to call it
2849 # directly, so that the IPython crash handler doesn't get triggered
2849 # directly, so that the IPython crash handler doesn't get triggered
2850 old_excepthook, sys.excepthook = sys.excepthook, self.excepthook
2850 old_excepthook, sys.excepthook = sys.excepthook, self.excepthook
2851
2851
2852 # we save the original sys.excepthook in the instance, in case config
2852 # we save the original sys.excepthook in the instance, in case config
2853 # code (such as magics) needs access to it.
2853 # code (such as magics) needs access to it.
2854 self.sys_excepthook = old_excepthook
2854 self.sys_excepthook = old_excepthook
2855 outflag = 1 # happens in more places, so it's easier as default
2855 outflag = 1 # happens in more places, so it's easier as default
2856 try:
2856 try:
2857 try:
2857 try:
2858 self.hooks.pre_run_code_hook()
2858 self.hooks.pre_run_code_hook()
2859 #rprint('Running code', repr(code_obj)) # dbg
2859 #rprint('Running code', repr(code_obj)) # dbg
2860 exec(code_obj, self.user_global_ns, self.user_ns)
2860 exec(code_obj, self.user_global_ns, self.user_ns)
2861 finally:
2861 finally:
2862 # Reset our crash handler in place
2862 # Reset our crash handler in place
2863 sys.excepthook = old_excepthook
2863 sys.excepthook = old_excepthook
2864 except SystemExit as e:
2864 except SystemExit as e:
2865 if result is not None:
2865 if result is not None:
2866 result.error_in_exec = e
2866 result.error_in_exec = e
2867 self.showtraceback(exception_only=True)
2867 self.showtraceback(exception_only=True)
2868 warn("To exit: use 'exit', 'quit', or Ctrl-D.", stacklevel=1)
2868 warn("To exit: use 'exit', 'quit', or Ctrl-D.", stacklevel=1)
2869 except self.custom_exceptions:
2869 except self.custom_exceptions:
2870 etype, value, tb = sys.exc_info()
2870 etype, value, tb = sys.exc_info()
2871 if result is not None:
2871 if result is not None:
2872 result.error_in_exec = value
2872 result.error_in_exec = value
2873 self.CustomTB(etype, value, tb)
2873 self.CustomTB(etype, value, tb)
2874 except:
2874 except:
2875 if result is not None:
2875 if result is not None:
2876 result.error_in_exec = sys.exc_info()[1]
2876 result.error_in_exec = sys.exc_info()[1]
2877 self.showtraceback()
2877 self.showtraceback()
2878 else:
2878 else:
2879 outflag = 0
2879 outflag = 0
2880 return outflag
2880 return outflag
2881
2881
2882 # For backwards compatibility
2882 # For backwards compatibility
2883 runcode = run_code
2883 runcode = run_code
2884
2884
2885 #-------------------------------------------------------------------------
2885 #-------------------------------------------------------------------------
2886 # Things related to GUI support and pylab
2886 # Things related to GUI support and pylab
2887 #-------------------------------------------------------------------------
2887 #-------------------------------------------------------------------------
2888
2888
2889 active_eventloop = None
2889 active_eventloop = None
2890
2890
2891 def enable_gui(self, gui=None):
2891 def enable_gui(self, gui=None):
2892 raise NotImplementedError('Implement enable_gui in a subclass')
2892 raise NotImplementedError('Implement enable_gui in a subclass')
2893
2893
2894 def enable_matplotlib(self, gui=None):
2894 def enable_matplotlib(self, gui=None):
2895 """Enable interactive matplotlib and inline figure support.
2895 """Enable interactive matplotlib and inline figure support.
2896
2896
2897 This takes the following steps:
2897 This takes the following steps:
2898
2898
2899 1. select the appropriate eventloop and matplotlib backend
2899 1. select the appropriate eventloop and matplotlib backend
2900 2. set up matplotlib for interactive use with that backend
2900 2. set up matplotlib for interactive use with that backend
2901 3. configure formatters for inline figure display
2901 3. configure formatters for inline figure display
2902 4. enable the selected gui eventloop
2902 4. enable the selected gui eventloop
2903
2903
2904 Parameters
2904 Parameters
2905 ----------
2905 ----------
2906 gui : optional, string
2906 gui : optional, string
2907 If given, dictates the choice of matplotlib GUI backend to use
2907 If given, dictates the choice of matplotlib GUI backend to use
2908 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
2908 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
2909 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
2909 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
2910 matplotlib (as dictated by the matplotlib build-time options plus the
2910 matplotlib (as dictated by the matplotlib build-time options plus the
2911 user's matplotlibrc configuration file). Note that not all backends
2911 user's matplotlibrc configuration file). Note that not all backends
2912 make sense in all contexts, for example a terminal ipython can't
2912 make sense in all contexts, for example a terminal ipython can't
2913 display figures inline.
2913 display figures inline.
2914 """
2914 """
2915 from IPython.core import pylabtools as pt
2915 from IPython.core import pylabtools as pt
2916 gui, backend = pt.find_gui_and_backend(gui, self.pylab_gui_select)
2916 gui, backend = pt.find_gui_and_backend(gui, self.pylab_gui_select)
2917
2917
2918 if gui != 'inline':
2918 if gui != 'inline':
2919 # If we have our first gui selection, store it
2919 # If we have our first gui selection, store it
2920 if self.pylab_gui_select is None:
2920 if self.pylab_gui_select is None:
2921 self.pylab_gui_select = gui
2921 self.pylab_gui_select = gui
2922 # Otherwise if they are different
2922 # Otherwise if they are different
2923 elif gui != self.pylab_gui_select:
2923 elif gui != self.pylab_gui_select:
2924 print ('Warning: Cannot change to a different GUI toolkit: %s.'
2924 print ('Warning: Cannot change to a different GUI toolkit: %s.'
2925 ' Using %s instead.' % (gui, self.pylab_gui_select))
2925 ' Using %s instead.' % (gui, self.pylab_gui_select))
2926 gui, backend = pt.find_gui_and_backend(self.pylab_gui_select)
2926 gui, backend = pt.find_gui_and_backend(self.pylab_gui_select)
2927
2927
2928 pt.activate_matplotlib(backend)
2928 pt.activate_matplotlib(backend)
2929 pt.configure_inline_support(self, backend)
2929 pt.configure_inline_support(self, backend)
2930
2930
2931 # Now we must activate the gui pylab wants to use, and fix %run to take
2931 # Now we must activate the gui pylab wants to use, and fix %run to take
2932 # plot updates into account
2932 # plot updates into account
2933 self.enable_gui(gui)
2933 self.enable_gui(gui)
2934 self.magics_manager.registry['ExecutionMagics'].default_runner = \
2934 self.magics_manager.registry['ExecutionMagics'].default_runner = \
2935 pt.mpl_runner(self.safe_execfile)
2935 pt.mpl_runner(self.safe_execfile)
2936
2936
2937 return gui, backend
2937 return gui, backend
2938
2938
2939 def enable_pylab(self, gui=None, import_all=True, welcome_message=False):
2939 def enable_pylab(self, gui=None, import_all=True, welcome_message=False):
2940 """Activate pylab support at runtime.
2940 """Activate pylab support at runtime.
2941
2941
2942 This turns on support for matplotlib, preloads into the interactive
2942 This turns on support for matplotlib, preloads into the interactive
2943 namespace all of numpy and pylab, and configures IPython to correctly
2943 namespace all of numpy and pylab, and configures IPython to correctly
2944 interact with the GUI event loop. The GUI backend to be used can be
2944 interact with the GUI event loop. The GUI backend to be used can be
2945 optionally selected with the optional ``gui`` argument.
2945 optionally selected with the optional ``gui`` argument.
2946
2946
2947 This method only adds preloading the namespace to InteractiveShell.enable_matplotlib.
2947 This method only adds preloading the namespace to InteractiveShell.enable_matplotlib.
2948
2948
2949 Parameters
2949 Parameters
2950 ----------
2950 ----------
2951 gui : optional, string
2951 gui : optional, string
2952 If given, dictates the choice of matplotlib GUI backend to use
2952 If given, dictates the choice of matplotlib GUI backend to use
2953 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
2953 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
2954 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
2954 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
2955 matplotlib (as dictated by the matplotlib build-time options plus the
2955 matplotlib (as dictated by the matplotlib build-time options plus the
2956 user's matplotlibrc configuration file). Note that not all backends
2956 user's matplotlibrc configuration file). Note that not all backends
2957 make sense in all contexts, for example a terminal ipython can't
2957 make sense in all contexts, for example a terminal ipython can't
2958 display figures inline.
2958 display figures inline.
2959 import_all : optional, bool, default: True
2959 import_all : optional, bool, default: True
2960 Whether to do `from numpy import *` and `from pylab import *`
2960 Whether to do `from numpy import *` and `from pylab import *`
2961 in addition to module imports.
2961 in addition to module imports.
2962 welcome_message : deprecated
2962 welcome_message : deprecated
2963 This argument is ignored, no welcome message will be displayed.
2963 This argument is ignored, no welcome message will be displayed.
2964 """
2964 """
2965 from IPython.core.pylabtools import import_pylab
2965 from IPython.core.pylabtools import import_pylab
2966
2966
2967 gui, backend = self.enable_matplotlib(gui)
2967 gui, backend = self.enable_matplotlib(gui)
2968
2968
2969 # We want to prevent the loading of pylab to pollute the user's
2969 # We want to prevent the loading of pylab to pollute the user's
2970 # namespace as shown by the %who* magics, so we execute the activation
2970 # namespace as shown by the %who* magics, so we execute the activation
2971 # code in an empty namespace, and we update *both* user_ns and
2971 # code in an empty namespace, and we update *both* user_ns and
2972 # user_ns_hidden with this information.
2972 # user_ns_hidden with this information.
2973 ns = {}
2973 ns = {}
2974 import_pylab(ns, import_all)
2974 import_pylab(ns, import_all)
2975 # warn about clobbered names
2975 # warn about clobbered names
2976 ignored = {"__builtins__"}
2976 ignored = {"__builtins__"}
2977 both = set(ns).intersection(self.user_ns).difference(ignored)
2977 both = set(ns).intersection(self.user_ns).difference(ignored)
2978 clobbered = [ name for name in both if self.user_ns[name] is not ns[name] ]
2978 clobbered = [ name for name in both if self.user_ns[name] is not ns[name] ]
2979 self.user_ns.update(ns)
2979 self.user_ns.update(ns)
2980 self.user_ns_hidden.update(ns)
2980 self.user_ns_hidden.update(ns)
2981 return gui, backend, clobbered
2981 return gui, backend, clobbered
2982
2982
2983 #-------------------------------------------------------------------------
2983 #-------------------------------------------------------------------------
2984 # Utilities
2984 # Utilities
2985 #-------------------------------------------------------------------------
2985 #-------------------------------------------------------------------------
2986
2986
2987 def var_expand(self, cmd, depth=0, formatter=DollarFormatter()):
2987 def var_expand(self, cmd, depth=0, formatter=DollarFormatter()):
2988 """Expand python variables in a string.
2988 """Expand python variables in a string.
2989
2989
2990 The depth argument indicates how many frames above the caller should
2990 The depth argument indicates how many frames above the caller should
2991 be walked to look for the local namespace where to expand variables.
2991 be walked to look for the local namespace where to expand variables.
2992
2992
2993 The global namespace for expansion is always the user's interactive
2993 The global namespace for expansion is always the user's interactive
2994 namespace.
2994 namespace.
2995 """
2995 """
2996 ns = self.user_ns.copy()
2996 ns = self.user_ns.copy()
2997 try:
2997 try:
2998 frame = sys._getframe(depth+1)
2998 frame = sys._getframe(depth+1)
2999 except ValueError:
2999 except ValueError:
3000 # This is thrown if there aren't that many frames on the stack,
3000 # This is thrown if there aren't that many frames on the stack,
3001 # e.g. if a script called run_line_magic() directly.
3001 # e.g. if a script called run_line_magic() directly.
3002 pass
3002 pass
3003 else:
3003 else:
3004 ns.update(frame.f_locals)
3004 ns.update(frame.f_locals)
3005
3005
3006 try:
3006 try:
3007 # We have to use .vformat() here, because 'self' is a valid and common
3007 # We have to use .vformat() here, because 'self' is a valid and common
3008 # name, and expanding **ns for .format() would make it collide with
3008 # name, and expanding **ns for .format() would make it collide with
3009 # the 'self' argument of the method.
3009 # the 'self' argument of the method.
3010 cmd = formatter.vformat(cmd, args=[], kwargs=ns)
3010 cmd = formatter.vformat(cmd, args=[], kwargs=ns)
3011 except Exception:
3011 except Exception:
3012 # if formatter couldn't format, just let it go untransformed
3012 # if formatter couldn't format, just let it go untransformed
3013 pass
3013 pass
3014 return cmd
3014 return cmd
3015
3015
3016 def mktempfile(self, data=None, prefix='ipython_edit_'):
3016 def mktempfile(self, data=None, prefix='ipython_edit_'):
3017 """Make a new tempfile and return its filename.
3017 """Make a new tempfile and return its filename.
3018
3018
3019 This makes a call to tempfile.mkstemp (created in a tempfile.mkdtemp),
3019 This makes a call to tempfile.mkstemp (created in a tempfile.mkdtemp),
3020 but it registers the created filename internally so ipython cleans it up
3020 but it registers the created filename internally so ipython cleans it up
3021 at exit time.
3021 at exit time.
3022
3022
3023 Optional inputs:
3023 Optional inputs:
3024
3024
3025 - data(None): if data is given, it gets written out to the temp file
3025 - data(None): if data is given, it gets written out to the temp file
3026 immediately, and the file is closed again."""
3026 immediately, and the file is closed again."""
3027
3027
3028 dirname = tempfile.mkdtemp(prefix=prefix)
3028 dirname = tempfile.mkdtemp(prefix=prefix)
3029 self.tempdirs.append(dirname)
3029 self.tempdirs.append(dirname)
3030
3030
3031 handle, filename = tempfile.mkstemp('.py', prefix, dir=dirname)
3031 handle, filename = tempfile.mkstemp('.py', prefix, dir=dirname)
3032 os.close(handle) # On Windows, there can only be one open handle on a file
3032 os.close(handle) # On Windows, there can only be one open handle on a file
3033 self.tempfiles.append(filename)
3033 self.tempfiles.append(filename)
3034
3034
3035 if data:
3035 if data:
3036 tmp_file = open(filename,'w')
3036 tmp_file = open(filename,'w')
3037 tmp_file.write(data)
3037 tmp_file.write(data)
3038 tmp_file.close()
3038 tmp_file.close()
3039 return filename
3039 return filename
3040
3040
3041 @undoc
3041 @undoc
3042 def write(self,data):
3042 def write(self,data):
3043 """DEPRECATED: Write a string to the default output"""
3043 """DEPRECATED: Write a string to the default output"""
3044 warn('InteractiveShell.write() is deprecated, use sys.stdout instead',
3044 warn('InteractiveShell.write() is deprecated, use sys.stdout instead',
3045 DeprecationWarning, stacklevel=2)
3045 DeprecationWarning, stacklevel=2)
3046 sys.stdout.write(data)
3046 sys.stdout.write(data)
3047
3047
3048 @undoc
3048 @undoc
3049 def write_err(self,data):
3049 def write_err(self,data):
3050 """DEPRECATED: Write a string to the default error output"""
3050 """DEPRECATED: Write a string to the default error output"""
3051 warn('InteractiveShell.write_err() is deprecated, use sys.stderr instead',
3051 warn('InteractiveShell.write_err() is deprecated, use sys.stderr instead',
3052 DeprecationWarning, stacklevel=2)
3052 DeprecationWarning, stacklevel=2)
3053 sys.stderr.write(data)
3053 sys.stderr.write(data)
3054
3054
3055 def ask_yes_no(self, prompt, default=None, interrupt=None):
3055 def ask_yes_no(self, prompt, default=None, interrupt=None):
3056 if self.quiet:
3056 if self.quiet:
3057 return True
3057 return True
3058 return ask_yes_no(prompt,default,interrupt)
3058 return ask_yes_no(prompt,default,interrupt)
3059
3059
3060 def show_usage(self):
3060 def show_usage(self):
3061 """Show a usage message"""
3061 """Show a usage message"""
3062 page.page(IPython.core.usage.interactive_usage)
3062 page.page(IPython.core.usage.interactive_usage)
3063
3063
3064 def extract_input_lines(self, range_str, raw=False):
3064 def extract_input_lines(self, range_str, raw=False):
3065 """Return as a string a set of input history slices.
3065 """Return as a string a set of input history slices.
3066
3066
3067 Parameters
3067 Parameters
3068 ----------
3068 ----------
3069 range_str : string
3069 range_str : string
3070 The set of slices is given as a string, like "~5/6-~4/2 4:8 9",
3070 The set of slices is given as a string, like "~5/6-~4/2 4:8 9",
3071 since this function is for use by magic functions which get their
3071 since this function is for use by magic functions which get their
3072 arguments as strings. The number before the / is the session
3072 arguments as strings. The number before the / is the session
3073 number: ~n goes n back from the current session.
3073 number: ~n goes n back from the current session.
3074
3074
3075 raw : bool, optional
3075 raw : bool, optional
3076 By default, the processed input is used. If this is true, the raw
3076 By default, the processed input is used. If this is true, the raw
3077 input history is used instead.
3077 input history is used instead.
3078
3078
3079 Notes
3079 Notes
3080 -----
3080 -----
3081
3081
3082 Slices can be described with two notations:
3082 Slices can be described with two notations:
3083
3083
3084 * ``N:M`` -> standard python form, means including items N...(M-1).
3084 * ``N:M`` -> standard python form, means including items N...(M-1).
3085 * ``N-M`` -> include items N..M (closed endpoint).
3085 * ``N-M`` -> include items N..M (closed endpoint).
3086 """
3086 """
3087 lines = self.history_manager.get_range_by_str(range_str, raw=raw)
3087 lines = self.history_manager.get_range_by_str(range_str, raw=raw)
3088 return "\n".join(x for _, _, x in lines)
3088 return "\n".join(x for _, _, x in lines)
3089
3089
3090 def find_user_code(self, target, raw=True, py_only=False, skip_encoding_cookie=True, search_ns=False):
3090 def find_user_code(self, target, raw=True, py_only=False, skip_encoding_cookie=True, search_ns=False):
3091 """Get a code string from history, file, url, or a string or macro.
3091 """Get a code string from history, file, url, or a string or macro.
3092
3092
3093 This is mainly used by magic functions.
3093 This is mainly used by magic functions.
3094
3094
3095 Parameters
3095 Parameters
3096 ----------
3096 ----------
3097
3097
3098 target : str
3098 target : str
3099
3099
3100 A string specifying code to retrieve. This will be tried respectively
3100 A string specifying code to retrieve. This will be tried respectively
3101 as: ranges of input history (see %history for syntax), url,
3101 as: ranges of input history (see %history for syntax), url,
3102 corresponding .py file, filename, or an expression evaluating to a
3102 corresponding .py file, filename, or an expression evaluating to a
3103 string or Macro in the user namespace.
3103 string or Macro in the user namespace.
3104
3104
3105 raw : bool
3105 raw : bool
3106 If true (default), retrieve raw history. Has no effect on the other
3106 If true (default), retrieve raw history. Has no effect on the other
3107 retrieval mechanisms.
3107 retrieval mechanisms.
3108
3108
3109 py_only : bool (default False)
3109 py_only : bool (default False)
3110 Only try to fetch python code, do not try alternative methods to decode file
3110 Only try to fetch python code, do not try alternative methods to decode file
3111 if unicode fails.
3111 if unicode fails.
3112
3112
3113 Returns
3113 Returns
3114 -------
3114 -------
3115 A string of code.
3115 A string of code.
3116
3116
3117 ValueError is raised if nothing is found, and TypeError if it evaluates
3117 ValueError is raised if nothing is found, and TypeError if it evaluates
3118 to an object of another type. In each case, .args[0] is a printable
3118 to an object of another type. In each case, .args[0] is a printable
3119 message.
3119 message.
3120 """
3120 """
3121 code = self.extract_input_lines(target, raw=raw) # Grab history
3121 code = self.extract_input_lines(target, raw=raw) # Grab history
3122 if code:
3122 if code:
3123 return code
3123 return code
3124 try:
3124 try:
3125 if target.startswith(('http://', 'https://')):
3125 if target.startswith(('http://', 'https://')):
3126 return openpy.read_py_url(target, skip_encoding_cookie=skip_encoding_cookie)
3126 return openpy.read_py_url(target, skip_encoding_cookie=skip_encoding_cookie)
3127 except UnicodeDecodeError:
3127 except UnicodeDecodeError:
3128 if not py_only :
3128 if not py_only :
3129 # Deferred import
3129 # Deferred import
3130 try:
3130 try:
3131 from urllib.request import urlopen # Py3
3131 from urllib.request import urlopen # Py3
3132 except ImportError:
3132 except ImportError:
3133 from urllib import urlopen
3133 from urllib import urlopen
3134 response = urlopen(target)
3134 response = urlopen(target)
3135 return response.read().decode('latin1')
3135 return response.read().decode('latin1')
3136 raise ValueError(("'%s' seem to be unreadable.") % target)
3136 raise ValueError(("'%s' seem to be unreadable.") % target)
3137
3137
3138 potential_target = [target]
3138 potential_target = [target]
3139 try :
3139 try :
3140 potential_target.insert(0,get_py_filename(target))
3140 potential_target.insert(0,get_py_filename(target))
3141 except IOError:
3141 except IOError:
3142 pass
3142 pass
3143
3143
3144 for tgt in potential_target :
3144 for tgt in potential_target :
3145 if os.path.isfile(tgt): # Read file
3145 if os.path.isfile(tgt): # Read file
3146 try :
3146 try :
3147 return openpy.read_py_file(tgt, skip_encoding_cookie=skip_encoding_cookie)
3147 return openpy.read_py_file(tgt, skip_encoding_cookie=skip_encoding_cookie)
3148 except UnicodeDecodeError :
3148 except UnicodeDecodeError :
3149 if not py_only :
3149 if not py_only :
3150 with io_open(tgt,'r', encoding='latin1') as f :
3150 with io_open(tgt,'r', encoding='latin1') as f :
3151 return f.read()
3151 return f.read()
3152 raise ValueError(("'%s' seem to be unreadable.") % target)
3152 raise ValueError(("'%s' seem to be unreadable.") % target)
3153 elif os.path.isdir(os.path.expanduser(tgt)):
3153 elif os.path.isdir(os.path.expanduser(tgt)):
3154 raise ValueError("'%s' is a directory, not a regular file." % target)
3154 raise ValueError("'%s' is a directory, not a regular file." % target)
3155
3155
3156 if search_ns:
3156 if search_ns:
3157 # Inspect namespace to load object source
3157 # Inspect namespace to load object source
3158 object_info = self.object_inspect(target, detail_level=1)
3158 object_info = self.object_inspect(target, detail_level=1)
3159 if object_info['found'] and object_info['source']:
3159 if object_info['found'] and object_info['source']:
3160 return object_info['source']
3160 return object_info['source']
3161
3161
3162 try: # User namespace
3162 try: # User namespace
3163 codeobj = eval(target, self.user_ns)
3163 codeobj = eval(target, self.user_ns)
3164 except Exception:
3164 except Exception:
3165 raise ValueError(("'%s' was not found in history, as a file, url, "
3165 raise ValueError(("'%s' was not found in history, as a file, url, "
3166 "nor in the user namespace.") % target)
3166 "nor in the user namespace.") % target)
3167
3167
3168 if isinstance(codeobj, string_types):
3168 if isinstance(codeobj, string_types):
3169 return codeobj
3169 return codeobj
3170 elif isinstance(codeobj, Macro):
3170 elif isinstance(codeobj, Macro):
3171 return codeobj.value
3171 return codeobj.value
3172
3172
3173 raise TypeError("%s is neither a string nor a macro." % target,
3173 raise TypeError("%s is neither a string nor a macro." % target,
3174 codeobj)
3174 codeobj)
3175
3175
3176 #-------------------------------------------------------------------------
3176 #-------------------------------------------------------------------------
3177 # Things related to IPython exiting
3177 # Things related to IPython exiting
3178 #-------------------------------------------------------------------------
3178 #-------------------------------------------------------------------------
3179 def atexit_operations(self):
3179 def atexit_operations(self):
3180 """This will be executed at the time of exit.
3180 """This will be executed at the time of exit.
3181
3181
3182 Cleanup operations and saving of persistent data that is done
3182 Cleanup operations and saving of persistent data that is done
3183 unconditionally by IPython should be performed here.
3183 unconditionally by IPython should be performed here.
3184
3184
3185 For things that may depend on startup flags or platform specifics (such
3185 For things that may depend on startup flags or platform specifics (such
3186 as having readline or not), register a separate atexit function in the
3186 as having readline or not), register a separate atexit function in the
3187 code that has the appropriate information, rather than trying to
3187 code that has the appropriate information, rather than trying to
3188 clutter
3188 clutter
3189 """
3189 """
3190 # Close the history session (this stores the end time and line count)
3190 # Close the history session (this stores the end time and line count)
3191 # this must be *before* the tempfile cleanup, in case of temporary
3191 # this must be *before* the tempfile cleanup, in case of temporary
3192 # history db
3192 # history db
3193 self.history_manager.end_session()
3193 self.history_manager.end_session()
3194
3194
3195 # Cleanup all tempfiles and folders left around
3195 # Cleanup all tempfiles and folders left around
3196 for tfile in self.tempfiles:
3196 for tfile in self.tempfiles:
3197 try:
3197 try:
3198 os.unlink(tfile)
3198 os.unlink(tfile)
3199 except OSError:
3199 except OSError:
3200 pass
3200 pass
3201
3201
3202 for tdir in self.tempdirs:
3202 for tdir in self.tempdirs:
3203 try:
3203 try:
3204 os.rmdir(tdir)
3204 os.rmdir(tdir)
3205 except OSError:
3205 except OSError:
3206 pass
3206 pass
3207
3207
3208 # Clear all user namespaces to release all references cleanly.
3208 # Clear all user namespaces to release all references cleanly.
3209 self.reset(new_session=False)
3209 self.reset(new_session=False)
3210
3210
3211 # Run user hooks
3211 # Run user hooks
3212 self.hooks.shutdown_hook()
3212 self.hooks.shutdown_hook()
3213
3213
3214 def cleanup(self):
3214 def cleanup(self):
3215 self.restore_sys_module_state()
3215 self.restore_sys_module_state()
3216
3216
3217
3217
3218 # Overridden in terminal subclass to change prompts
3218 # Overridden in terminal subclass to change prompts
3219 def switch_doctest_mode(self, mode):
3219 def switch_doctest_mode(self, mode):
3220 pass
3220 pass
3221
3221
3222
3222
3223 class InteractiveShellABC(with_metaclass(abc.ABCMeta, object)):
3223 class InteractiveShellABC(with_metaclass(abc.ABCMeta, object)):
3224 """An abstract base class for InteractiveShell."""
3224 """An abstract base class for InteractiveShell."""
3225
3225
3226 InteractiveShellABC.register(InteractiveShell)
3226 InteractiveShellABC.register(InteractiveShell)
@@ -1,679 +1,679 b''
1 # encoding: utf-8
1 # encoding: utf-8
2 """Magic functions for InteractiveShell.
2 """Magic functions for InteractiveShell.
3 """
3 """
4
4
5 #-----------------------------------------------------------------------------
5 #-----------------------------------------------------------------------------
6 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
6 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
7 # Copyright (C) 2001 Fernando Perez <fperez@colorado.edu>
7 # Copyright (C) 2001 Fernando Perez <fperez@colorado.edu>
8 # Copyright (C) 2008 The IPython Development Team
8 # Copyright (C) 2008 The IPython Development Team
9
9
10 # Distributed under the terms of the BSD License. The full license is in
10 # Distributed under the terms of the BSD License. The full license is in
11 # the file COPYING, distributed as part of this software.
11 # the file COPYING, distributed as part of this software.
12 #-----------------------------------------------------------------------------
12 #-----------------------------------------------------------------------------
13
13
14 import os
14 import os
15 import re
15 import re
16 import sys
16 import sys
17 import types
17 import types
18 from getopt import getopt, GetoptError
18 from getopt import getopt, GetoptError
19
19
20 from traitlets.config.configurable import Configurable
20 from traitlets.config.configurable import Configurable
21 from IPython.core import oinspect
21 from IPython.core import oinspect
22 from IPython.core.error import UsageError
22 from IPython.core.error import UsageError
23 from IPython.core.inputsplitter import ESC_MAGIC, ESC_MAGIC2
23 from IPython.core.inputsplitter import ESC_MAGIC, ESC_MAGIC2
24 from decorator import decorator
24 from decorator import decorator
25 from IPython.utils.ipstruct import Struct
25 from IPython.utils.ipstruct import Struct
26 from IPython.utils.process import arg_split
26 from IPython.utils.process import arg_split
27 from IPython.utils.py3compat import string_types, iteritems
27 from IPython.utils.py3compat import string_types
28 from IPython.utils.text import dedent
28 from IPython.utils.text import dedent
29 from traitlets import Bool, Dict, Instance, observe
29 from traitlets import Bool, Dict, Instance, observe
30 from logging import error
30 from logging import error
31
31
32 #-----------------------------------------------------------------------------
32 #-----------------------------------------------------------------------------
33 # Globals
33 # Globals
34 #-----------------------------------------------------------------------------
34 #-----------------------------------------------------------------------------
35
35
36 # A dict we'll use for each class that has magics, used as temporary storage to
36 # A dict we'll use for each class that has magics, used as temporary storage to
37 # pass information between the @line/cell_magic method decorators and the
37 # pass information between the @line/cell_magic method decorators and the
38 # @magics_class class decorator, because the method decorators have no
38 # @magics_class class decorator, because the method decorators have no
39 # access to the class when they run. See for more details:
39 # access to the class when they run. See for more details:
40 # http://stackoverflow.com/questions/2366713/can-a-python-decorator-of-an-instance-method-access-the-class
40 # http://stackoverflow.com/questions/2366713/can-a-python-decorator-of-an-instance-method-access-the-class
41
41
42 magics = dict(line={}, cell={})
42 magics = dict(line={}, cell={})
43
43
44 magic_kinds = ('line', 'cell')
44 magic_kinds = ('line', 'cell')
45 magic_spec = ('line', 'cell', 'line_cell')
45 magic_spec = ('line', 'cell', 'line_cell')
46 magic_escapes = dict(line=ESC_MAGIC, cell=ESC_MAGIC2)
46 magic_escapes = dict(line=ESC_MAGIC, cell=ESC_MAGIC2)
47
47
48 #-----------------------------------------------------------------------------
48 #-----------------------------------------------------------------------------
49 # Utility classes and functions
49 # Utility classes and functions
50 #-----------------------------------------------------------------------------
50 #-----------------------------------------------------------------------------
51
51
52 class Bunch: pass
52 class Bunch: pass
53
53
54
54
55 def on_off(tag):
55 def on_off(tag):
56 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
56 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
57 return ['OFF','ON'][tag]
57 return ['OFF','ON'][tag]
58
58
59
59
60 def compress_dhist(dh):
60 def compress_dhist(dh):
61 """Compress a directory history into a new one with at most 20 entries.
61 """Compress a directory history into a new one with at most 20 entries.
62
62
63 Return a new list made from the first and last 10 elements of dhist after
63 Return a new list made from the first and last 10 elements of dhist after
64 removal of duplicates.
64 removal of duplicates.
65 """
65 """
66 head, tail = dh[:-10], dh[-10:]
66 head, tail = dh[:-10], dh[-10:]
67
67
68 newhead = []
68 newhead = []
69 done = set()
69 done = set()
70 for h in head:
70 for h in head:
71 if h in done:
71 if h in done:
72 continue
72 continue
73 newhead.append(h)
73 newhead.append(h)
74 done.add(h)
74 done.add(h)
75
75
76 return newhead + tail
76 return newhead + tail
77
77
78
78
79 def needs_local_scope(func):
79 def needs_local_scope(func):
80 """Decorator to mark magic functions which need to local scope to run."""
80 """Decorator to mark magic functions which need to local scope to run."""
81 func.needs_local_scope = True
81 func.needs_local_scope = True
82 return func
82 return func
83
83
84 #-----------------------------------------------------------------------------
84 #-----------------------------------------------------------------------------
85 # Class and method decorators for registering magics
85 # Class and method decorators for registering magics
86 #-----------------------------------------------------------------------------
86 #-----------------------------------------------------------------------------
87
87
88 def magics_class(cls):
88 def magics_class(cls):
89 """Class decorator for all subclasses of the main Magics class.
89 """Class decorator for all subclasses of the main Magics class.
90
90
91 Any class that subclasses Magics *must* also apply this decorator, to
91 Any class that subclasses Magics *must* also apply this decorator, to
92 ensure that all the methods that have been decorated as line/cell magics
92 ensure that all the methods that have been decorated as line/cell magics
93 get correctly registered in the class instance. This is necessary because
93 get correctly registered in the class instance. This is necessary because
94 when method decorators run, the class does not exist yet, so they
94 when method decorators run, the class does not exist yet, so they
95 temporarily store their information into a module global. Application of
95 temporarily store their information into a module global. Application of
96 this class decorator copies that global data to the class instance and
96 this class decorator copies that global data to the class instance and
97 clears the global.
97 clears the global.
98
98
99 Obviously, this mechanism is not thread-safe, which means that the
99 Obviously, this mechanism is not thread-safe, which means that the
100 *creation* of subclasses of Magic should only be done in a single-thread
100 *creation* of subclasses of Magic should only be done in a single-thread
101 context. Instantiation of the classes has no restrictions. Given that
101 context. Instantiation of the classes has no restrictions. Given that
102 these classes are typically created at IPython startup time and before user
102 these classes are typically created at IPython startup time and before user
103 application code becomes active, in practice this should not pose any
103 application code becomes active, in practice this should not pose any
104 problems.
104 problems.
105 """
105 """
106 cls.registered = True
106 cls.registered = True
107 cls.magics = dict(line = magics['line'],
107 cls.magics = dict(line = magics['line'],
108 cell = magics['cell'])
108 cell = magics['cell'])
109 magics['line'] = {}
109 magics['line'] = {}
110 magics['cell'] = {}
110 magics['cell'] = {}
111 return cls
111 return cls
112
112
113
113
114 def record_magic(dct, magic_kind, magic_name, func):
114 def record_magic(dct, magic_kind, magic_name, func):
115 """Utility function to store a function as a magic of a specific kind.
115 """Utility function to store a function as a magic of a specific kind.
116
116
117 Parameters
117 Parameters
118 ----------
118 ----------
119 dct : dict
119 dct : dict
120 A dictionary with 'line' and 'cell' subdicts.
120 A dictionary with 'line' and 'cell' subdicts.
121
121
122 magic_kind : str
122 magic_kind : str
123 Kind of magic to be stored.
123 Kind of magic to be stored.
124
124
125 magic_name : str
125 magic_name : str
126 Key to store the magic as.
126 Key to store the magic as.
127
127
128 func : function
128 func : function
129 Callable object to store.
129 Callable object to store.
130 """
130 """
131 if magic_kind == 'line_cell':
131 if magic_kind == 'line_cell':
132 dct['line'][magic_name] = dct['cell'][magic_name] = func
132 dct['line'][magic_name] = dct['cell'][magic_name] = func
133 else:
133 else:
134 dct[magic_kind][magic_name] = func
134 dct[magic_kind][magic_name] = func
135
135
136
136
137 def validate_type(magic_kind):
137 def validate_type(magic_kind):
138 """Ensure that the given magic_kind is valid.
138 """Ensure that the given magic_kind is valid.
139
139
140 Check that the given magic_kind is one of the accepted spec types (stored
140 Check that the given magic_kind is one of the accepted spec types (stored
141 in the global `magic_spec`), raise ValueError otherwise.
141 in the global `magic_spec`), raise ValueError otherwise.
142 """
142 """
143 if magic_kind not in magic_spec:
143 if magic_kind not in magic_spec:
144 raise ValueError('magic_kind must be one of %s, %s given' %
144 raise ValueError('magic_kind must be one of %s, %s given' %
145 magic_kinds, magic_kind)
145 magic_kinds, magic_kind)
146
146
147
147
148 # The docstrings for the decorator below will be fairly similar for the two
148 # The docstrings for the decorator below will be fairly similar for the two
149 # types (method and function), so we generate them here once and reuse the
149 # types (method and function), so we generate them here once and reuse the
150 # templates below.
150 # templates below.
151 _docstring_template = \
151 _docstring_template = \
152 """Decorate the given {0} as {1} magic.
152 """Decorate the given {0} as {1} magic.
153
153
154 The decorator can be used with or without arguments, as follows.
154 The decorator can be used with or without arguments, as follows.
155
155
156 i) without arguments: it will create a {1} magic named as the {0} being
156 i) without arguments: it will create a {1} magic named as the {0} being
157 decorated::
157 decorated::
158
158
159 @deco
159 @deco
160 def foo(...)
160 def foo(...)
161
161
162 will create a {1} magic named `foo`.
162 will create a {1} magic named `foo`.
163
163
164 ii) with one string argument: which will be used as the actual name of the
164 ii) with one string argument: which will be used as the actual name of the
165 resulting magic::
165 resulting magic::
166
166
167 @deco('bar')
167 @deco('bar')
168 def foo(...)
168 def foo(...)
169
169
170 will create a {1} magic named `bar`.
170 will create a {1} magic named `bar`.
171 """
171 """
172
172
173 # These two are decorator factories. While they are conceptually very similar,
173 # These two are decorator factories. While they are conceptually very similar,
174 # there are enough differences in the details that it's simpler to have them
174 # there are enough differences in the details that it's simpler to have them
175 # written as completely standalone functions rather than trying to share code
175 # written as completely standalone functions rather than trying to share code
176 # and make a single one with convoluted logic.
176 # and make a single one with convoluted logic.
177
177
178 def _method_magic_marker(magic_kind):
178 def _method_magic_marker(magic_kind):
179 """Decorator factory for methods in Magics subclasses.
179 """Decorator factory for methods in Magics subclasses.
180 """
180 """
181
181
182 validate_type(magic_kind)
182 validate_type(magic_kind)
183
183
184 # This is a closure to capture the magic_kind. We could also use a class,
184 # This is a closure to capture the magic_kind. We could also use a class,
185 # but it's overkill for just that one bit of state.
185 # but it's overkill for just that one bit of state.
186 def magic_deco(arg):
186 def magic_deco(arg):
187 call = lambda f, *a, **k: f(*a, **k)
187 call = lambda f, *a, **k: f(*a, **k)
188
188
189 if callable(arg):
189 if callable(arg):
190 # "Naked" decorator call (just @foo, no args)
190 # "Naked" decorator call (just @foo, no args)
191 func = arg
191 func = arg
192 name = func.__name__
192 name = func.__name__
193 retval = decorator(call, func)
193 retval = decorator(call, func)
194 record_magic(magics, magic_kind, name, name)
194 record_magic(magics, magic_kind, name, name)
195 elif isinstance(arg, string_types):
195 elif isinstance(arg, string_types):
196 # Decorator called with arguments (@foo('bar'))
196 # Decorator called with arguments (@foo('bar'))
197 name = arg
197 name = arg
198 def mark(func, *a, **kw):
198 def mark(func, *a, **kw):
199 record_magic(magics, magic_kind, name, func.__name__)
199 record_magic(magics, magic_kind, name, func.__name__)
200 return decorator(call, func)
200 return decorator(call, func)
201 retval = mark
201 retval = mark
202 else:
202 else:
203 raise TypeError("Decorator can only be called with "
203 raise TypeError("Decorator can only be called with "
204 "string or function")
204 "string or function")
205 return retval
205 return retval
206
206
207 # Ensure the resulting decorator has a usable docstring
207 # Ensure the resulting decorator has a usable docstring
208 magic_deco.__doc__ = _docstring_template.format('method', magic_kind)
208 magic_deco.__doc__ = _docstring_template.format('method', magic_kind)
209 return magic_deco
209 return magic_deco
210
210
211
211
212 def _function_magic_marker(magic_kind):
212 def _function_magic_marker(magic_kind):
213 """Decorator factory for standalone functions.
213 """Decorator factory for standalone functions.
214 """
214 """
215 validate_type(magic_kind)
215 validate_type(magic_kind)
216
216
217 # This is a closure to capture the magic_kind. We could also use a class,
217 # This is a closure to capture the magic_kind. We could also use a class,
218 # but it's overkill for just that one bit of state.
218 # but it's overkill for just that one bit of state.
219 def magic_deco(arg):
219 def magic_deco(arg):
220 call = lambda f, *a, **k: f(*a, **k)
220 call = lambda f, *a, **k: f(*a, **k)
221
221
222 # Find get_ipython() in the caller's namespace
222 # Find get_ipython() in the caller's namespace
223 caller = sys._getframe(1)
223 caller = sys._getframe(1)
224 for ns in ['f_locals', 'f_globals', 'f_builtins']:
224 for ns in ['f_locals', 'f_globals', 'f_builtins']:
225 get_ipython = getattr(caller, ns).get('get_ipython')
225 get_ipython = getattr(caller, ns).get('get_ipython')
226 if get_ipython is not None:
226 if get_ipython is not None:
227 break
227 break
228 else:
228 else:
229 raise NameError('Decorator can only run in context where '
229 raise NameError('Decorator can only run in context where '
230 '`get_ipython` exists')
230 '`get_ipython` exists')
231
231
232 ip = get_ipython()
232 ip = get_ipython()
233
233
234 if callable(arg):
234 if callable(arg):
235 # "Naked" decorator call (just @foo, no args)
235 # "Naked" decorator call (just @foo, no args)
236 func = arg
236 func = arg
237 name = func.__name__
237 name = func.__name__
238 ip.register_magic_function(func, magic_kind, name)
238 ip.register_magic_function(func, magic_kind, name)
239 retval = decorator(call, func)
239 retval = decorator(call, func)
240 elif isinstance(arg, string_types):
240 elif isinstance(arg, string_types):
241 # Decorator called with arguments (@foo('bar'))
241 # Decorator called with arguments (@foo('bar'))
242 name = arg
242 name = arg
243 def mark(func, *a, **kw):
243 def mark(func, *a, **kw):
244 ip.register_magic_function(func, magic_kind, name)
244 ip.register_magic_function(func, magic_kind, name)
245 return decorator(call, func)
245 return decorator(call, func)
246 retval = mark
246 retval = mark
247 else:
247 else:
248 raise TypeError("Decorator can only be called with "
248 raise TypeError("Decorator can only be called with "
249 "string or function")
249 "string or function")
250 return retval
250 return retval
251
251
252 # Ensure the resulting decorator has a usable docstring
252 # Ensure the resulting decorator has a usable docstring
253 ds = _docstring_template.format('function', magic_kind)
253 ds = _docstring_template.format('function', magic_kind)
254
254
255 ds += dedent("""
255 ds += dedent("""
256 Note: this decorator can only be used in a context where IPython is already
256 Note: this decorator can only be used in a context where IPython is already
257 active, so that the `get_ipython()` call succeeds. You can therefore use
257 active, so that the `get_ipython()` call succeeds. You can therefore use
258 it in your startup files loaded after IPython initializes, but *not* in the
258 it in your startup files loaded after IPython initializes, but *not* in the
259 IPython configuration file itself, which is executed before IPython is
259 IPython configuration file itself, which is executed before IPython is
260 fully up and running. Any file located in the `startup` subdirectory of
260 fully up and running. Any file located in the `startup` subdirectory of
261 your configuration profile will be OK in this sense.
261 your configuration profile will be OK in this sense.
262 """)
262 """)
263
263
264 magic_deco.__doc__ = ds
264 magic_deco.__doc__ = ds
265 return magic_deco
265 return magic_deco
266
266
267
267
268 # Create the actual decorators for public use
268 # Create the actual decorators for public use
269
269
270 # These three are used to decorate methods in class definitions
270 # These three are used to decorate methods in class definitions
271 line_magic = _method_magic_marker('line')
271 line_magic = _method_magic_marker('line')
272 cell_magic = _method_magic_marker('cell')
272 cell_magic = _method_magic_marker('cell')
273 line_cell_magic = _method_magic_marker('line_cell')
273 line_cell_magic = _method_magic_marker('line_cell')
274
274
275 # These three decorate standalone functions and perform the decoration
275 # These three decorate standalone functions and perform the decoration
276 # immediately. They can only run where get_ipython() works
276 # immediately. They can only run where get_ipython() works
277 register_line_magic = _function_magic_marker('line')
277 register_line_magic = _function_magic_marker('line')
278 register_cell_magic = _function_magic_marker('cell')
278 register_cell_magic = _function_magic_marker('cell')
279 register_line_cell_magic = _function_magic_marker('line_cell')
279 register_line_cell_magic = _function_magic_marker('line_cell')
280
280
281 #-----------------------------------------------------------------------------
281 #-----------------------------------------------------------------------------
282 # Core Magic classes
282 # Core Magic classes
283 #-----------------------------------------------------------------------------
283 #-----------------------------------------------------------------------------
284
284
285 class MagicsManager(Configurable):
285 class MagicsManager(Configurable):
286 """Object that handles all magic-related functionality for IPython.
286 """Object that handles all magic-related functionality for IPython.
287 """
287 """
288 # Non-configurable class attributes
288 # Non-configurable class attributes
289
289
290 # A two-level dict, first keyed by magic type, then by magic function, and
290 # A two-level dict, first keyed by magic type, then by magic function, and
291 # holding the actual callable object as value. This is the dict used for
291 # holding the actual callable object as value. This is the dict used for
292 # magic function dispatch
292 # magic function dispatch
293 magics = Dict()
293 magics = Dict()
294
294
295 # A registry of the original objects that we've been given holding magics.
295 # A registry of the original objects that we've been given holding magics.
296 registry = Dict()
296 registry = Dict()
297
297
298 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC', allow_none=True)
298 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC', allow_none=True)
299
299
300 auto_magic = Bool(True, help=
300 auto_magic = Bool(True, help=
301 "Automatically call line magics without requiring explicit % prefix"
301 "Automatically call line magics without requiring explicit % prefix"
302 ).tag(config=True)
302 ).tag(config=True)
303 @observe('auto_magic')
303 @observe('auto_magic')
304 def _auto_magic_changed(self, change):
304 def _auto_magic_changed(self, change):
305 self.shell.automagic = change['new']
305 self.shell.automagic = change['new']
306
306
307 _auto_status = [
307 _auto_status = [
308 'Automagic is OFF, % prefix IS needed for line magics.',
308 'Automagic is OFF, % prefix IS needed for line magics.',
309 'Automagic is ON, % prefix IS NOT needed for line magics.']
309 'Automagic is ON, % prefix IS NOT needed for line magics.']
310
310
311 user_magics = Instance('IPython.core.magics.UserMagics', allow_none=True)
311 user_magics = Instance('IPython.core.magics.UserMagics', allow_none=True)
312
312
313 def __init__(self, shell=None, config=None, user_magics=None, **traits):
313 def __init__(self, shell=None, config=None, user_magics=None, **traits):
314
314
315 super(MagicsManager, self).__init__(shell=shell, config=config,
315 super(MagicsManager, self).__init__(shell=shell, config=config,
316 user_magics=user_magics, **traits)
316 user_magics=user_magics, **traits)
317 self.magics = dict(line={}, cell={})
317 self.magics = dict(line={}, cell={})
318 # Let's add the user_magics to the registry for uniformity, so *all*
318 # Let's add the user_magics to the registry for uniformity, so *all*
319 # registered magic containers can be found there.
319 # registered magic containers can be found there.
320 self.registry[user_magics.__class__.__name__] = user_magics
320 self.registry[user_magics.__class__.__name__] = user_magics
321
321
322 def auto_status(self):
322 def auto_status(self):
323 """Return descriptive string with automagic status."""
323 """Return descriptive string with automagic status."""
324 return self._auto_status[self.auto_magic]
324 return self._auto_status[self.auto_magic]
325
325
326 def lsmagic(self):
326 def lsmagic(self):
327 """Return a dict of currently available magic functions.
327 """Return a dict of currently available magic functions.
328
328
329 The return dict has the keys 'line' and 'cell', corresponding to the
329 The return dict has the keys 'line' and 'cell', corresponding to the
330 two types of magics we support. Each value is a list of names.
330 two types of magics we support. Each value is a list of names.
331 """
331 """
332 return self.magics
332 return self.magics
333
333
334 def lsmagic_docs(self, brief=False, missing=''):
334 def lsmagic_docs(self, brief=False, missing=''):
335 """Return dict of documentation of magic functions.
335 """Return dict of documentation of magic functions.
336
336
337 The return dict has the keys 'line' and 'cell', corresponding to the
337 The return dict has the keys 'line' and 'cell', corresponding to the
338 two types of magics we support. Each value is a dict keyed by magic
338 two types of magics we support. Each value is a dict keyed by magic
339 name whose value is the function docstring. If a docstring is
339 name whose value is the function docstring. If a docstring is
340 unavailable, the value of `missing` is used instead.
340 unavailable, the value of `missing` is used instead.
341
341
342 If brief is True, only the first line of each docstring will be returned.
342 If brief is True, only the first line of each docstring will be returned.
343 """
343 """
344 docs = {}
344 docs = {}
345 for m_type in self.magics:
345 for m_type in self.magics:
346 m_docs = {}
346 m_docs = {}
347 for m_name, m_func in iteritems(self.magics[m_type]):
347 for m_name, m_func in self.magics[m_type].items():
348 if m_func.__doc__:
348 if m_func.__doc__:
349 if brief:
349 if brief:
350 m_docs[m_name] = m_func.__doc__.split('\n', 1)[0]
350 m_docs[m_name] = m_func.__doc__.split('\n', 1)[0]
351 else:
351 else:
352 m_docs[m_name] = m_func.__doc__.rstrip()
352 m_docs[m_name] = m_func.__doc__.rstrip()
353 else:
353 else:
354 m_docs[m_name] = missing
354 m_docs[m_name] = missing
355 docs[m_type] = m_docs
355 docs[m_type] = m_docs
356 return docs
356 return docs
357
357
358 def register(self, *magic_objects):
358 def register(self, *magic_objects):
359 """Register one or more instances of Magics.
359 """Register one or more instances of Magics.
360
360
361 Take one or more classes or instances of classes that subclass the main
361 Take one or more classes or instances of classes that subclass the main
362 `core.Magic` class, and register them with IPython to use the magic
362 `core.Magic` class, and register them with IPython to use the magic
363 functions they provide. The registration process will then ensure that
363 functions they provide. The registration process will then ensure that
364 any methods that have decorated to provide line and/or cell magics will
364 any methods that have decorated to provide line and/or cell magics will
365 be recognized with the `%x`/`%%x` syntax as a line/cell magic
365 be recognized with the `%x`/`%%x` syntax as a line/cell magic
366 respectively.
366 respectively.
367
367
368 If classes are given, they will be instantiated with the default
368 If classes are given, they will be instantiated with the default
369 constructor. If your classes need a custom constructor, you should
369 constructor. If your classes need a custom constructor, you should
370 instanitate them first and pass the instance.
370 instanitate them first and pass the instance.
371
371
372 The provided arguments can be an arbitrary mix of classes and instances.
372 The provided arguments can be an arbitrary mix of classes and instances.
373
373
374 Parameters
374 Parameters
375 ----------
375 ----------
376 magic_objects : one or more classes or instances
376 magic_objects : one or more classes or instances
377 """
377 """
378 # Start by validating them to ensure they have all had their magic
378 # Start by validating them to ensure they have all had their magic
379 # methods registered at the instance level
379 # methods registered at the instance level
380 for m in magic_objects:
380 for m in magic_objects:
381 if not m.registered:
381 if not m.registered:
382 raise ValueError("Class of magics %r was constructed without "
382 raise ValueError("Class of magics %r was constructed without "
383 "the @register_magics class decorator")
383 "the @register_magics class decorator")
384 if isinstance(m, type):
384 if isinstance(m, type):
385 # If we're given an uninstantiated class
385 # If we're given an uninstantiated class
386 m = m(shell=self.shell)
386 m = m(shell=self.shell)
387
387
388 # Now that we have an instance, we can register it and update the
388 # Now that we have an instance, we can register it and update the
389 # table of callables
389 # table of callables
390 self.registry[m.__class__.__name__] = m
390 self.registry[m.__class__.__name__] = m
391 for mtype in magic_kinds:
391 for mtype in magic_kinds:
392 self.magics[mtype].update(m.magics[mtype])
392 self.magics[mtype].update(m.magics[mtype])
393
393
394 def register_function(self, func, magic_kind='line', magic_name=None):
394 def register_function(self, func, magic_kind='line', magic_name=None):
395 """Expose a standalone function as magic function for IPython.
395 """Expose a standalone function as magic function for IPython.
396
396
397 This will create an IPython magic (line, cell or both) from a
397 This will create an IPython magic (line, cell or both) from a
398 standalone function. The functions should have the following
398 standalone function. The functions should have the following
399 signatures:
399 signatures:
400
400
401 * For line magics: `def f(line)`
401 * For line magics: `def f(line)`
402 * For cell magics: `def f(line, cell)`
402 * For cell magics: `def f(line, cell)`
403 * For a function that does both: `def f(line, cell=None)`
403 * For a function that does both: `def f(line, cell=None)`
404
404
405 In the latter case, the function will be called with `cell==None` when
405 In the latter case, the function will be called with `cell==None` when
406 invoked as `%f`, and with cell as a string when invoked as `%%f`.
406 invoked as `%f`, and with cell as a string when invoked as `%%f`.
407
407
408 Parameters
408 Parameters
409 ----------
409 ----------
410 func : callable
410 func : callable
411 Function to be registered as a magic.
411 Function to be registered as a magic.
412
412
413 magic_kind : str
413 magic_kind : str
414 Kind of magic, one of 'line', 'cell' or 'line_cell'
414 Kind of magic, one of 'line', 'cell' or 'line_cell'
415
415
416 magic_name : optional str
416 magic_name : optional str
417 If given, the name the magic will have in the IPython namespace. By
417 If given, the name the magic will have in the IPython namespace. By
418 default, the name of the function itself is used.
418 default, the name of the function itself is used.
419 """
419 """
420
420
421 # Create the new method in the user_magics and register it in the
421 # Create the new method in the user_magics and register it in the
422 # global table
422 # global table
423 validate_type(magic_kind)
423 validate_type(magic_kind)
424 magic_name = func.__name__ if magic_name is None else magic_name
424 magic_name = func.__name__ if magic_name is None else magic_name
425 setattr(self.user_magics, magic_name, func)
425 setattr(self.user_magics, magic_name, func)
426 record_magic(self.magics, magic_kind, magic_name, func)
426 record_magic(self.magics, magic_kind, magic_name, func)
427
427
428 def register_alias(self, alias_name, magic_name, magic_kind='line'):
428 def register_alias(self, alias_name, magic_name, magic_kind='line'):
429 """Register an alias to a magic function.
429 """Register an alias to a magic function.
430
430
431 The alias is an instance of :class:`MagicAlias`, which holds the
431 The alias is an instance of :class:`MagicAlias`, which holds the
432 name and kind of the magic it should call. Binding is done at
432 name and kind of the magic it should call. Binding is done at
433 call time, so if the underlying magic function is changed the alias
433 call time, so if the underlying magic function is changed the alias
434 will call the new function.
434 will call the new function.
435
435
436 Parameters
436 Parameters
437 ----------
437 ----------
438 alias_name : str
438 alias_name : str
439 The name of the magic to be registered.
439 The name of the magic to be registered.
440
440
441 magic_name : str
441 magic_name : str
442 The name of an existing magic.
442 The name of an existing magic.
443
443
444 magic_kind : str
444 magic_kind : str
445 Kind of magic, one of 'line' or 'cell'
445 Kind of magic, one of 'line' or 'cell'
446 """
446 """
447
447
448 # `validate_type` is too permissive, as it allows 'line_cell'
448 # `validate_type` is too permissive, as it allows 'line_cell'
449 # which we do not handle.
449 # which we do not handle.
450 if magic_kind not in magic_kinds:
450 if magic_kind not in magic_kinds:
451 raise ValueError('magic_kind must be one of %s, %s given' %
451 raise ValueError('magic_kind must be one of %s, %s given' %
452 magic_kinds, magic_kind)
452 magic_kinds, magic_kind)
453
453
454 alias = MagicAlias(self.shell, magic_name, magic_kind)
454 alias = MagicAlias(self.shell, magic_name, magic_kind)
455 setattr(self.user_magics, alias_name, alias)
455 setattr(self.user_magics, alias_name, alias)
456 record_magic(self.magics, magic_kind, alias_name, alias)
456 record_magic(self.magics, magic_kind, alias_name, alias)
457
457
458 # Key base class that provides the central functionality for magics.
458 # Key base class that provides the central functionality for magics.
459
459
460
460
461 class Magics(Configurable):
461 class Magics(Configurable):
462 """Base class for implementing magic functions.
462 """Base class for implementing magic functions.
463
463
464 Shell functions which can be reached as %function_name. All magic
464 Shell functions which can be reached as %function_name. All magic
465 functions should accept a string, which they can parse for their own
465 functions should accept a string, which they can parse for their own
466 needs. This can make some functions easier to type, eg `%cd ../`
466 needs. This can make some functions easier to type, eg `%cd ../`
467 vs. `%cd("../")`
467 vs. `%cd("../")`
468
468
469 Classes providing magic functions need to subclass this class, and they
469 Classes providing magic functions need to subclass this class, and they
470 MUST:
470 MUST:
471
471
472 - Use the method decorators `@line_magic` and `@cell_magic` to decorate
472 - Use the method decorators `@line_magic` and `@cell_magic` to decorate
473 individual methods as magic functions, AND
473 individual methods as magic functions, AND
474
474
475 - Use the class decorator `@magics_class` to ensure that the magic
475 - Use the class decorator `@magics_class` to ensure that the magic
476 methods are properly registered at the instance level upon instance
476 methods are properly registered at the instance level upon instance
477 initialization.
477 initialization.
478
478
479 See :mod:`magic_functions` for examples of actual implementation classes.
479 See :mod:`magic_functions` for examples of actual implementation classes.
480 """
480 """
481 # Dict holding all command-line options for each magic.
481 # Dict holding all command-line options for each magic.
482 options_table = None
482 options_table = None
483 # Dict for the mapping of magic names to methods, set by class decorator
483 # Dict for the mapping of magic names to methods, set by class decorator
484 magics = None
484 magics = None
485 # Flag to check that the class decorator was properly applied
485 # Flag to check that the class decorator was properly applied
486 registered = False
486 registered = False
487 # Instance of IPython shell
487 # Instance of IPython shell
488 shell = None
488 shell = None
489
489
490 def __init__(self, shell=None, **kwargs):
490 def __init__(self, shell=None, **kwargs):
491 if not(self.__class__.registered):
491 if not(self.__class__.registered):
492 raise ValueError('Magics subclass without registration - '
492 raise ValueError('Magics subclass without registration - '
493 'did you forget to apply @magics_class?')
493 'did you forget to apply @magics_class?')
494 if shell is not None:
494 if shell is not None:
495 if hasattr(shell, 'configurables'):
495 if hasattr(shell, 'configurables'):
496 shell.configurables.append(self)
496 shell.configurables.append(self)
497 if hasattr(shell, 'config'):
497 if hasattr(shell, 'config'):
498 kwargs.setdefault('parent', shell)
498 kwargs.setdefault('parent', shell)
499
499
500 self.shell = shell
500 self.shell = shell
501 self.options_table = {}
501 self.options_table = {}
502 # The method decorators are run when the instance doesn't exist yet, so
502 # The method decorators are run when the instance doesn't exist yet, so
503 # they can only record the names of the methods they are supposed to
503 # they can only record the names of the methods they are supposed to
504 # grab. Only now, that the instance exists, can we create the proper
504 # grab. Only now, that the instance exists, can we create the proper
505 # mapping to bound methods. So we read the info off the original names
505 # mapping to bound methods. So we read the info off the original names
506 # table and replace each method name by the actual bound method.
506 # table and replace each method name by the actual bound method.
507 # But we mustn't clobber the *class* mapping, in case of multiple instances.
507 # But we mustn't clobber the *class* mapping, in case of multiple instances.
508 class_magics = self.magics
508 class_magics = self.magics
509 self.magics = {}
509 self.magics = {}
510 for mtype in magic_kinds:
510 for mtype in magic_kinds:
511 tab = self.magics[mtype] = {}
511 tab = self.magics[mtype] = {}
512 cls_tab = class_magics[mtype]
512 cls_tab = class_magics[mtype]
513 for magic_name, meth_name in iteritems(cls_tab):
513 for magic_name, meth_name in cls_tab.items():
514 if isinstance(meth_name, string_types):
514 if isinstance(meth_name, string_types):
515 # it's a method name, grab it
515 # it's a method name, grab it
516 tab[magic_name] = getattr(self, meth_name)
516 tab[magic_name] = getattr(self, meth_name)
517 else:
517 else:
518 # it's the real thing
518 # it's the real thing
519 tab[magic_name] = meth_name
519 tab[magic_name] = meth_name
520 # Configurable **needs** to be initiated at the end or the config
520 # Configurable **needs** to be initiated at the end or the config
521 # magics get screwed up.
521 # magics get screwed up.
522 super(Magics, self).__init__(**kwargs)
522 super(Magics, self).__init__(**kwargs)
523
523
524 def arg_err(self,func):
524 def arg_err(self,func):
525 """Print docstring if incorrect arguments were passed"""
525 """Print docstring if incorrect arguments were passed"""
526 print('Error in arguments:')
526 print('Error in arguments:')
527 print(oinspect.getdoc(func))
527 print(oinspect.getdoc(func))
528
528
529 def format_latex(self, strng):
529 def format_latex(self, strng):
530 """Format a string for latex inclusion."""
530 """Format a string for latex inclusion."""
531
531
532 # Characters that need to be escaped for latex:
532 # Characters that need to be escaped for latex:
533 escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
533 escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
534 # Magic command names as headers:
534 # Magic command names as headers:
535 cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC,
535 cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC,
536 re.MULTILINE)
536 re.MULTILINE)
537 # Magic commands
537 # Magic commands
538 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC,
538 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC,
539 re.MULTILINE)
539 re.MULTILINE)
540 # Paragraph continue
540 # Paragraph continue
541 par_re = re.compile(r'\\$',re.MULTILINE)
541 par_re = re.compile(r'\\$',re.MULTILINE)
542
542
543 # The "\n" symbol
543 # The "\n" symbol
544 newline_re = re.compile(r'\\n')
544 newline_re = re.compile(r'\\n')
545
545
546 # Now build the string for output:
546 # Now build the string for output:
547 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
547 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
548 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
548 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
549 strng)
549 strng)
550 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
550 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
551 strng = par_re.sub(r'\\\\',strng)
551 strng = par_re.sub(r'\\\\',strng)
552 strng = escape_re.sub(r'\\\1',strng)
552 strng = escape_re.sub(r'\\\1',strng)
553 strng = newline_re.sub(r'\\textbackslash{}n',strng)
553 strng = newline_re.sub(r'\\textbackslash{}n',strng)
554 return strng
554 return strng
555
555
556 def parse_options(self, arg_str, opt_str, *long_opts, **kw):
556 def parse_options(self, arg_str, opt_str, *long_opts, **kw):
557 """Parse options passed to an argument string.
557 """Parse options passed to an argument string.
558
558
559 The interface is similar to that of :func:`getopt.getopt`, but it
559 The interface is similar to that of :func:`getopt.getopt`, but it
560 returns a :class:`~IPython.utils.struct.Struct` with the options as keys
560 returns a :class:`~IPython.utils.struct.Struct` with the options as keys
561 and the stripped argument string still as a string.
561 and the stripped argument string still as a string.
562
562
563 arg_str is quoted as a true sys.argv vector by using shlex.split.
563 arg_str is quoted as a true sys.argv vector by using shlex.split.
564 This allows us to easily expand variables, glob files, quote
564 This allows us to easily expand variables, glob files, quote
565 arguments, etc.
565 arguments, etc.
566
566
567 Parameters
567 Parameters
568 ----------
568 ----------
569
569
570 arg_str : str
570 arg_str : str
571 The arguments to parse.
571 The arguments to parse.
572
572
573 opt_str : str
573 opt_str : str
574 The options specification.
574 The options specification.
575
575
576 mode : str, default 'string'
576 mode : str, default 'string'
577 If given as 'list', the argument string is returned as a list (split
577 If given as 'list', the argument string is returned as a list (split
578 on whitespace) instead of a string.
578 on whitespace) instead of a string.
579
579
580 list_all : bool, default False
580 list_all : bool, default False
581 Put all option values in lists. Normally only options
581 Put all option values in lists. Normally only options
582 appearing more than once are put in a list.
582 appearing more than once are put in a list.
583
583
584 posix : bool, default True
584 posix : bool, default True
585 Whether to split the input line in POSIX mode or not, as per the
585 Whether to split the input line in POSIX mode or not, as per the
586 conventions outlined in the :mod:`shlex` module from the standard
586 conventions outlined in the :mod:`shlex` module from the standard
587 library.
587 library.
588 """
588 """
589
589
590 # inject default options at the beginning of the input line
590 # inject default options at the beginning of the input line
591 caller = sys._getframe(1).f_code.co_name
591 caller = sys._getframe(1).f_code.co_name
592 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
592 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
593
593
594 mode = kw.get('mode','string')
594 mode = kw.get('mode','string')
595 if mode not in ['string','list']:
595 if mode not in ['string','list']:
596 raise ValueError('incorrect mode given: %s' % mode)
596 raise ValueError('incorrect mode given: %s' % mode)
597 # Get options
597 # Get options
598 list_all = kw.get('list_all',0)
598 list_all = kw.get('list_all',0)
599 posix = kw.get('posix', os.name == 'posix')
599 posix = kw.get('posix', os.name == 'posix')
600 strict = kw.get('strict', True)
600 strict = kw.get('strict', True)
601
601
602 # Check if we have more than one argument to warrant extra processing:
602 # Check if we have more than one argument to warrant extra processing:
603 odict = {} # Dictionary with options
603 odict = {} # Dictionary with options
604 args = arg_str.split()
604 args = arg_str.split()
605 if len(args) >= 1:
605 if len(args) >= 1:
606 # If the list of inputs only has 0 or 1 thing in it, there's no
606 # If the list of inputs only has 0 or 1 thing in it, there's no
607 # need to look for options
607 # need to look for options
608 argv = arg_split(arg_str, posix, strict)
608 argv = arg_split(arg_str, posix, strict)
609 # Do regular option processing
609 # Do regular option processing
610 try:
610 try:
611 opts,args = getopt(argv, opt_str, long_opts)
611 opts,args = getopt(argv, opt_str, long_opts)
612 except GetoptError as e:
612 except GetoptError as e:
613 raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
613 raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
614 " ".join(long_opts)))
614 " ".join(long_opts)))
615 for o,a in opts:
615 for o,a in opts:
616 if o.startswith('--'):
616 if o.startswith('--'):
617 o = o[2:]
617 o = o[2:]
618 else:
618 else:
619 o = o[1:]
619 o = o[1:]
620 try:
620 try:
621 odict[o].append(a)
621 odict[o].append(a)
622 except AttributeError:
622 except AttributeError:
623 odict[o] = [odict[o],a]
623 odict[o] = [odict[o],a]
624 except KeyError:
624 except KeyError:
625 if list_all:
625 if list_all:
626 odict[o] = [a]
626 odict[o] = [a]
627 else:
627 else:
628 odict[o] = a
628 odict[o] = a
629
629
630 # Prepare opts,args for return
630 # Prepare opts,args for return
631 opts = Struct(odict)
631 opts = Struct(odict)
632 if mode == 'string':
632 if mode == 'string':
633 args = ' '.join(args)
633 args = ' '.join(args)
634
634
635 return opts,args
635 return opts,args
636
636
637 def default_option(self, fn, optstr):
637 def default_option(self, fn, optstr):
638 """Make an entry in the options_table for fn, with value optstr"""
638 """Make an entry in the options_table for fn, with value optstr"""
639
639
640 if fn not in self.lsmagic():
640 if fn not in self.lsmagic():
641 error("%s is not a magic function" % fn)
641 error("%s is not a magic function" % fn)
642 self.options_table[fn] = optstr
642 self.options_table[fn] = optstr
643
643
644
644
645 class MagicAlias(object):
645 class MagicAlias(object):
646 """An alias to another magic function.
646 """An alias to another magic function.
647
647
648 An alias is determined by its magic name and magic kind. Lookup
648 An alias is determined by its magic name and magic kind. Lookup
649 is done at call time, so if the underlying magic changes the alias
649 is done at call time, so if the underlying magic changes the alias
650 will call the new function.
650 will call the new function.
651
651
652 Use the :meth:`MagicsManager.register_alias` method or the
652 Use the :meth:`MagicsManager.register_alias` method or the
653 `%alias_magic` magic function to create and register a new alias.
653 `%alias_magic` magic function to create and register a new alias.
654 """
654 """
655 def __init__(self, shell, magic_name, magic_kind):
655 def __init__(self, shell, magic_name, magic_kind):
656 self.shell = shell
656 self.shell = shell
657 self.magic_name = magic_name
657 self.magic_name = magic_name
658 self.magic_kind = magic_kind
658 self.magic_kind = magic_kind
659
659
660 self.pretty_target = '%s%s' % (magic_escapes[self.magic_kind], self.magic_name)
660 self.pretty_target = '%s%s' % (magic_escapes[self.magic_kind], self.magic_name)
661 self.__doc__ = "Alias for `%s`." % self.pretty_target
661 self.__doc__ = "Alias for `%s`." % self.pretty_target
662
662
663 self._in_call = False
663 self._in_call = False
664
664
665 def __call__(self, *args, **kwargs):
665 def __call__(self, *args, **kwargs):
666 """Call the magic alias."""
666 """Call the magic alias."""
667 fn = self.shell.find_magic(self.magic_name, self.magic_kind)
667 fn = self.shell.find_magic(self.magic_name, self.magic_kind)
668 if fn is None:
668 if fn is None:
669 raise UsageError("Magic `%s` not found." % self.pretty_target)
669 raise UsageError("Magic `%s` not found." % self.pretty_target)
670
670
671 # Protect against infinite recursion.
671 # Protect against infinite recursion.
672 if self._in_call:
672 if self._in_call:
673 raise UsageError("Infinite recursion detected; "
673 raise UsageError("Infinite recursion detected; "
674 "magic aliases cannot call themselves.")
674 "magic aliases cannot call themselves.")
675 self._in_call = True
675 self._in_call = True
676 try:
676 try:
677 return fn(*args, **kwargs)
677 return fn(*args, **kwargs)
678 finally:
678 finally:
679 self._in_call = False
679 self._in_call = False
@@ -1,1373 +1,1372 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
7
8 import ast
8 import ast
9 import bdb
9 import bdb
10 import gc
10 import gc
11 import itertools
11 import itertools
12 import os
12 import os
13 import sys
13 import sys
14 import time
14 import time
15 import timeit
15 import timeit
16 import math
16 import math
17 from pdb import Restart
17 from pdb import Restart
18
18
19 # cProfile was added in Python2.5
19 # cProfile was added in Python2.5
20 try:
20 try:
21 import cProfile as profile
21 import cProfile as profile
22 import pstats
22 import pstats
23 except ImportError:
23 except ImportError:
24 # profile isn't bundled by default in Debian for license reasons
24 # profile isn't bundled by default in Debian for license reasons
25 try:
25 try:
26 import profile, pstats
26 import profile, pstats
27 except ImportError:
27 except ImportError:
28 profile = pstats = None
28 profile = pstats = None
29
29
30 from IPython.core import oinspect
30 from IPython.core import oinspect
31 from IPython.core import magic_arguments
31 from IPython.core import magic_arguments
32 from IPython.core import page
32 from IPython.core import page
33 from IPython.core.error import UsageError
33 from IPython.core.error import UsageError
34 from IPython.core.macro import Macro
34 from IPython.core.macro import Macro
35 from IPython.core.magic import (Magics, magics_class, line_magic, cell_magic,
35 from IPython.core.magic import (Magics, magics_class, line_magic, cell_magic,
36 line_cell_magic, on_off, needs_local_scope)
36 line_cell_magic, on_off, needs_local_scope)
37 from IPython.testing.skipdoctest import skip_doctest
37 from IPython.testing.skipdoctest import skip_doctest
38 from IPython.utils import py3compat
38 from IPython.utils import py3compat
39 from IPython.utils.py3compat import builtin_mod, iteritems, PY3
39 from IPython.utils.py3compat import builtin_mod, PY3
40 from IPython.utils.contexts import preserve_keys
40 from IPython.utils.contexts import preserve_keys
41 from IPython.utils.capture import capture_output
41 from IPython.utils.capture import capture_output
42 from IPython.utils.ipstruct import Struct
42 from IPython.utils.ipstruct import Struct
43 from IPython.utils.module_paths import find_mod
43 from IPython.utils.module_paths import find_mod
44 from IPython.utils.path import get_py_filename, shellglob
44 from IPython.utils.path import get_py_filename, shellglob
45 from IPython.utils.timing import clock, clock2
45 from IPython.utils.timing import clock, clock2
46 from warnings import warn
46 from warnings import warn
47 from logging import error
47 from logging import error
48
48
49 if PY3:
49 if PY3:
50 from io import StringIO
50 from io import StringIO
51 else:
51 else:
52 from StringIO import StringIO
52 from StringIO import StringIO
53
53
54 #-----------------------------------------------------------------------------
54 #-----------------------------------------------------------------------------
55 # Magic implementation classes
55 # Magic implementation classes
56 #-----------------------------------------------------------------------------
56 #-----------------------------------------------------------------------------
57
57
58
58
59 class TimeitResult(object):
59 class TimeitResult(object):
60 """
60 """
61 Object returned by the timeit magic with info about the run.
61 Object returned by the timeit magic with info about the run.
62
62
63 Contains the following attributes :
63 Contains the following attributes :
64
64
65 loops: (int) number of loops done per measurement
65 loops: (int) number of loops done per measurement
66 repeat: (int) number of times the measurement has been repeated
66 repeat: (int) number of times the measurement has been repeated
67 best: (float) best execution time / number
67 best: (float) best execution time / number
68 all_runs: (list of float) execution time of each run (in s)
68 all_runs: (list of float) execution time of each run (in s)
69 compile_time: (float) time of statement compilation (s)
69 compile_time: (float) time of statement compilation (s)
70
70
71 """
71 """
72 def __init__(self, loops, repeat, best, worst, all_runs, compile_time, precision):
72 def __init__(self, loops, repeat, best, worst, all_runs, compile_time, precision):
73 self.loops = loops
73 self.loops = loops
74 self.repeat = repeat
74 self.repeat = repeat
75 self.best = best
75 self.best = best
76 self.worst = worst
76 self.worst = worst
77 self.all_runs = all_runs
77 self.all_runs = all_runs
78 self.compile_time = compile_time
78 self.compile_time = compile_time
79 self._precision = precision
79 self._precision = precision
80 self.timings = [ dt / self.loops for dt in all_runs]
80 self.timings = [ dt / self.loops for dt in all_runs]
81
81
82 @property
82 @property
83 def average(self):
83 def average(self):
84 return math.fsum(self.timings) / len(self.timings)
84 return math.fsum(self.timings) / len(self.timings)
85
85
86 @property
86 @property
87 def stdev(self):
87 def stdev(self):
88 mean = self.average
88 mean = self.average
89 return (math.fsum([(x - mean) ** 2 for x in self.timings]) / len(self.timings)) ** 0.5
89 return (math.fsum([(x - mean) ** 2 for x in self.timings]) / len(self.timings)) ** 0.5
90
90
91 def __str__(self):
91 def __str__(self):
92 return (u"%s loop%s, average of %d: %s +- %s per loop (using standard deviation)"
92 return (u"%s loop%s, average of %d: %s +- %s per loop (using standard deviation)"
93 % (self.loops,"" if self.loops == 1 else "s", self.repeat,
93 % (self.loops,"" if self.loops == 1 else "s", self.repeat,
94 _format_time(self.average, self._precision),
94 _format_time(self.average, self._precision),
95 _format_time(self.stdev, self._precision)))
95 _format_time(self.stdev, self._precision)))
96
96
97 def _repr_pretty_(self, p , cycle):
97 def _repr_pretty_(self, p , cycle):
98 unic = self.__str__()
98 unic = self.__str__()
99 p.text(u'<TimeitResult : '+unic+u'>')
99 p.text(u'<TimeitResult : '+unic+u'>')
100
100
101
101
102
102
103 class TimeitTemplateFiller(ast.NodeTransformer):
103 class TimeitTemplateFiller(ast.NodeTransformer):
104 """Fill in the AST template for timing execution.
104 """Fill in the AST template for timing execution.
105
105
106 This is quite closely tied to the template definition, which is in
106 This is quite closely tied to the template definition, which is in
107 :meth:`ExecutionMagics.timeit`.
107 :meth:`ExecutionMagics.timeit`.
108 """
108 """
109 def __init__(self, ast_setup, ast_stmt):
109 def __init__(self, ast_setup, ast_stmt):
110 self.ast_setup = ast_setup
110 self.ast_setup = ast_setup
111 self.ast_stmt = ast_stmt
111 self.ast_stmt = ast_stmt
112
112
113 def visit_FunctionDef(self, node):
113 def visit_FunctionDef(self, node):
114 "Fill in the setup statement"
114 "Fill in the setup statement"
115 self.generic_visit(node)
115 self.generic_visit(node)
116 if node.name == "inner":
116 if node.name == "inner":
117 node.body[:1] = self.ast_setup.body
117 node.body[:1] = self.ast_setup.body
118
118
119 return node
119 return node
120
120
121 def visit_For(self, node):
121 def visit_For(self, node):
122 "Fill in the statement to be timed"
122 "Fill in the statement to be timed"
123 if getattr(getattr(node.body[0], 'value', None), 'id', None) == 'stmt':
123 if getattr(getattr(node.body[0], 'value', None), 'id', None) == 'stmt':
124 node.body = self.ast_stmt.body
124 node.body = self.ast_stmt.body
125 return node
125 return node
126
126
127
127
128 class Timer(timeit.Timer):
128 class Timer(timeit.Timer):
129 """Timer class that explicitly uses self.inner
129 """Timer class that explicitly uses self.inner
130
130
131 which is an undocumented implementation detail of CPython,
131 which is an undocumented implementation detail of CPython,
132 not shared by PyPy.
132 not shared by PyPy.
133 """
133 """
134 # Timer.timeit copied from CPython 3.4.2
134 # Timer.timeit copied from CPython 3.4.2
135 def timeit(self, number=timeit.default_number):
135 def timeit(self, number=timeit.default_number):
136 """Time 'number' executions of the main statement.
136 """Time 'number' executions of the main statement.
137
137
138 To be precise, this executes the setup statement once, and
138 To be precise, this executes the setup statement once, and
139 then returns the time it takes to execute the main statement
139 then returns the time it takes to execute the main statement
140 a number of times, as a float measured in seconds. The
140 a number of times, as a float measured in seconds. The
141 argument is the number of times through the loop, defaulting
141 argument is the number of times through the loop, defaulting
142 to one million. The main statement, the setup statement and
142 to one million. The main statement, the setup statement and
143 the timer function to be used are passed to the constructor.
143 the timer function to be used are passed to the constructor.
144 """
144 """
145 it = itertools.repeat(None, number)
145 it = itertools.repeat(None, number)
146 gcold = gc.isenabled()
146 gcold = gc.isenabled()
147 gc.disable()
147 gc.disable()
148 try:
148 try:
149 timing = self.inner(it, self.timer)
149 timing = self.inner(it, self.timer)
150 finally:
150 finally:
151 if gcold:
151 if gcold:
152 gc.enable()
152 gc.enable()
153 return timing
153 return timing
154
154
155
155
156 @magics_class
156 @magics_class
157 class ExecutionMagics(Magics):
157 class ExecutionMagics(Magics):
158 """Magics related to code execution, debugging, profiling, etc.
158 """Magics related to code execution, debugging, profiling, etc.
159
159
160 """
160 """
161
161
162 def __init__(self, shell):
162 def __init__(self, shell):
163 super(ExecutionMagics, self).__init__(shell)
163 super(ExecutionMagics, self).__init__(shell)
164 if profile is None:
164 if profile is None:
165 self.prun = self.profile_missing_notice
165 self.prun = self.profile_missing_notice
166 # Default execution function used to actually run user code.
166 # Default execution function used to actually run user code.
167 self.default_runner = None
167 self.default_runner = None
168
168
169 def profile_missing_notice(self, *args, **kwargs):
169 def profile_missing_notice(self, *args, **kwargs):
170 error("""\
170 error("""\
171 The profile module could not be found. It has been removed from the standard
171 The profile module could not be found. It has been removed from the standard
172 python packages because of its non-free license. To use profiling, install the
172 python packages because of its non-free license. To use profiling, install the
173 python-profiler package from non-free.""")
173 python-profiler package from non-free.""")
174
174
175 @skip_doctest
175 @skip_doctest
176 @line_cell_magic
176 @line_cell_magic
177 def prun(self, parameter_s='', cell=None):
177 def prun(self, parameter_s='', cell=None):
178
178
179 """Run a statement through the python code profiler.
179 """Run a statement through the python code profiler.
180
180
181 Usage, in line mode:
181 Usage, in line mode:
182 %prun [options] statement
182 %prun [options] statement
183
183
184 Usage, in cell mode:
184 Usage, in cell mode:
185 %%prun [options] [statement]
185 %%prun [options] [statement]
186 code...
186 code...
187 code...
187 code...
188
188
189 In cell mode, the additional code lines are appended to the (possibly
189 In cell mode, the additional code lines are appended to the (possibly
190 empty) statement in the first line. Cell mode allows you to easily
190 empty) statement in the first line. Cell mode allows you to easily
191 profile multiline blocks without having to put them in a separate
191 profile multiline blocks without having to put them in a separate
192 function.
192 function.
193
193
194 The given statement (which doesn't require quote marks) is run via the
194 The given statement (which doesn't require quote marks) is run via the
195 python profiler in a manner similar to the profile.run() function.
195 python profiler in a manner similar to the profile.run() function.
196 Namespaces are internally managed to work correctly; profile.run
196 Namespaces are internally managed to work correctly; profile.run
197 cannot be used in IPython because it makes certain assumptions about
197 cannot be used in IPython because it makes certain assumptions about
198 namespaces which do not hold under IPython.
198 namespaces which do not hold under IPython.
199
199
200 Options:
200 Options:
201
201
202 -l <limit>
202 -l <limit>
203 you can place restrictions on what or how much of the
203 you can place restrictions on what or how much of the
204 profile gets printed. The limit value can be:
204 profile gets printed. The limit value can be:
205
205
206 * A string: only information for function names containing this string
206 * A string: only information for function names containing this string
207 is printed.
207 is printed.
208
208
209 * An integer: only these many lines are printed.
209 * An integer: only these many lines are printed.
210
210
211 * A float (between 0 and 1): this fraction of the report is printed
211 * A float (between 0 and 1): this fraction of the report is printed
212 (for example, use a limit of 0.4 to see the topmost 40% only).
212 (for example, use a limit of 0.4 to see the topmost 40% only).
213
213
214 You can combine several limits with repeated use of the option. For
214 You can combine several limits with repeated use of the option. For
215 example, ``-l __init__ -l 5`` will print only the topmost 5 lines of
215 example, ``-l __init__ -l 5`` will print only the topmost 5 lines of
216 information about class constructors.
216 information about class constructors.
217
217
218 -r
218 -r
219 return the pstats.Stats object generated by the profiling. This
219 return the pstats.Stats object generated by the profiling. This
220 object has all the information about the profile in it, and you can
220 object has all the information about the profile in it, and you can
221 later use it for further analysis or in other functions.
221 later use it for further analysis or in other functions.
222
222
223 -s <key>
223 -s <key>
224 sort profile by given key. You can provide more than one key
224 sort profile by given key. You can provide more than one key
225 by using the option several times: '-s key1 -s key2 -s key3...'. The
225 by using the option several times: '-s key1 -s key2 -s key3...'. The
226 default sorting key is 'time'.
226 default sorting key is 'time'.
227
227
228 The following is copied verbatim from the profile documentation
228 The following is copied verbatim from the profile documentation
229 referenced below:
229 referenced below:
230
230
231 When more than one key is provided, additional keys are used as
231 When more than one key is provided, additional keys are used as
232 secondary criteria when the there is equality in all keys selected
232 secondary criteria when the there is equality in all keys selected
233 before them.
233 before them.
234
234
235 Abbreviations can be used for any key names, as long as the
235 Abbreviations can be used for any key names, as long as the
236 abbreviation is unambiguous. The following are the keys currently
236 abbreviation is unambiguous. The following are the keys currently
237 defined:
237 defined:
238
238
239 ============ =====================
239 ============ =====================
240 Valid Arg Meaning
240 Valid Arg Meaning
241 ============ =====================
241 ============ =====================
242 "calls" call count
242 "calls" call count
243 "cumulative" cumulative time
243 "cumulative" cumulative time
244 "file" file name
244 "file" file name
245 "module" file name
245 "module" file name
246 "pcalls" primitive call count
246 "pcalls" primitive call count
247 "line" line number
247 "line" line number
248 "name" function name
248 "name" function name
249 "nfl" name/file/line
249 "nfl" name/file/line
250 "stdname" standard name
250 "stdname" standard name
251 "time" internal time
251 "time" internal time
252 ============ =====================
252 ============ =====================
253
253
254 Note that all sorts on statistics are in descending order (placing
254 Note that all sorts on statistics are in descending order (placing
255 most time consuming items first), where as name, file, and line number
255 most time consuming items first), where as name, file, and line number
256 searches are in ascending order (i.e., alphabetical). The subtle
256 searches are in ascending order (i.e., alphabetical). The subtle
257 distinction between "nfl" and "stdname" is that the standard name is a
257 distinction between "nfl" and "stdname" is that the standard name is a
258 sort of the name as printed, which means that the embedded line
258 sort of the name as printed, which means that the embedded line
259 numbers get compared in an odd way. For example, lines 3, 20, and 40
259 numbers get compared in an odd way. For example, lines 3, 20, and 40
260 would (if the file names were the same) appear in the string order
260 would (if the file names were the same) appear in the string order
261 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
261 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
262 line numbers. In fact, sort_stats("nfl") is the same as
262 line numbers. In fact, sort_stats("nfl") is the same as
263 sort_stats("name", "file", "line").
263 sort_stats("name", "file", "line").
264
264
265 -T <filename>
265 -T <filename>
266 save profile results as shown on screen to a text
266 save profile results as shown on screen to a text
267 file. The profile is still shown on screen.
267 file. The profile is still shown on screen.
268
268
269 -D <filename>
269 -D <filename>
270 save (via dump_stats) profile statistics to given
270 save (via dump_stats) profile statistics to given
271 filename. This data is in a format understood by the pstats module, and
271 filename. This data is in a format understood by the pstats module, and
272 is generated by a call to the dump_stats() method of profile
272 is generated by a call to the dump_stats() method of profile
273 objects. The profile is still shown on screen.
273 objects. The profile is still shown on screen.
274
274
275 -q
275 -q
276 suppress output to the pager. Best used with -T and/or -D above.
276 suppress output to the pager. Best used with -T and/or -D above.
277
277
278 If you want to run complete programs under the profiler's control, use
278 If you want to run complete programs under the profiler's control, use
279 ``%run -p [prof_opts] filename.py [args to program]`` where prof_opts
279 ``%run -p [prof_opts] filename.py [args to program]`` where prof_opts
280 contains profiler specific options as described here.
280 contains profiler specific options as described here.
281
281
282 You can read the complete documentation for the profile module with::
282 You can read the complete documentation for the profile module with::
283
283
284 In [1]: import profile; profile.help()
284 In [1]: import profile; profile.help()
285 """
285 """
286 opts, arg_str = self.parse_options(parameter_s, 'D:l:rs:T:q',
286 opts, arg_str = self.parse_options(parameter_s, 'D:l:rs:T:q',
287 list_all=True, posix=False)
287 list_all=True, posix=False)
288 if cell is not None:
288 if cell is not None:
289 arg_str += '\n' + cell
289 arg_str += '\n' + cell
290 arg_str = self.shell.input_splitter.transform_cell(arg_str)
290 arg_str = self.shell.input_splitter.transform_cell(arg_str)
291 return self._run_with_profiler(arg_str, opts, self.shell.user_ns)
291 return self._run_with_profiler(arg_str, opts, self.shell.user_ns)
292
292
293 def _run_with_profiler(self, code, opts, namespace):
293 def _run_with_profiler(self, code, opts, namespace):
294 """
294 """
295 Run `code` with profiler. Used by ``%prun`` and ``%run -p``.
295 Run `code` with profiler. Used by ``%prun`` and ``%run -p``.
296
296
297 Parameters
297 Parameters
298 ----------
298 ----------
299 code : str
299 code : str
300 Code to be executed.
300 Code to be executed.
301 opts : Struct
301 opts : Struct
302 Options parsed by `self.parse_options`.
302 Options parsed by `self.parse_options`.
303 namespace : dict
303 namespace : dict
304 A dictionary for Python namespace (e.g., `self.shell.user_ns`).
304 A dictionary for Python namespace (e.g., `self.shell.user_ns`).
305
305
306 """
306 """
307
307
308 # Fill default values for unspecified options:
308 # Fill default values for unspecified options:
309 opts.merge(Struct(D=[''], l=[], s=['time'], T=['']))
309 opts.merge(Struct(D=[''], l=[], s=['time'], T=['']))
310
310
311 prof = profile.Profile()
311 prof = profile.Profile()
312 try:
312 try:
313 prof = prof.runctx(code, namespace, namespace)
313 prof = prof.runctx(code, namespace, namespace)
314 sys_exit = ''
314 sys_exit = ''
315 except SystemExit:
315 except SystemExit:
316 sys_exit = """*** SystemExit exception caught in code being profiled."""
316 sys_exit = """*** SystemExit exception caught in code being profiled."""
317
317
318 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
318 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
319
319
320 lims = opts.l
320 lims = opts.l
321 if lims:
321 if lims:
322 lims = [] # rebuild lims with ints/floats/strings
322 lims = [] # rebuild lims with ints/floats/strings
323 for lim in opts.l:
323 for lim in opts.l:
324 try:
324 try:
325 lims.append(int(lim))
325 lims.append(int(lim))
326 except ValueError:
326 except ValueError:
327 try:
327 try:
328 lims.append(float(lim))
328 lims.append(float(lim))
329 except ValueError:
329 except ValueError:
330 lims.append(lim)
330 lims.append(lim)
331
331
332 # Trap output.
332 # Trap output.
333 stdout_trap = StringIO()
333 stdout_trap = StringIO()
334 stats_stream = stats.stream
334 stats_stream = stats.stream
335 try:
335 try:
336 stats.stream = stdout_trap
336 stats.stream = stdout_trap
337 stats.print_stats(*lims)
337 stats.print_stats(*lims)
338 finally:
338 finally:
339 stats.stream = stats_stream
339 stats.stream = stats_stream
340
340
341 output = stdout_trap.getvalue()
341 output = stdout_trap.getvalue()
342 output = output.rstrip()
342 output = output.rstrip()
343
343
344 if 'q' not in opts:
344 if 'q' not in opts:
345 page.page(output)
345 page.page(output)
346 print(sys_exit, end=' ')
346 print(sys_exit, end=' ')
347
347
348 dump_file = opts.D[0]
348 dump_file = opts.D[0]
349 text_file = opts.T[0]
349 text_file = opts.T[0]
350 if dump_file:
350 if dump_file:
351 prof.dump_stats(dump_file)
351 prof.dump_stats(dump_file)
352 print('\n*** Profile stats marshalled to file',\
352 print('\n*** Profile stats marshalled to file',\
353 repr(dump_file)+'.',sys_exit)
353 repr(dump_file)+'.',sys_exit)
354 if text_file:
354 if text_file:
355 pfile = open(text_file,'w')
355 pfile = open(text_file,'w')
356 pfile.write(output)
356 pfile.write(output)
357 pfile.close()
357 pfile.close()
358 print('\n*** Profile printout saved to text file',\
358 print('\n*** Profile printout saved to text file',\
359 repr(text_file)+'.',sys_exit)
359 repr(text_file)+'.',sys_exit)
360
360
361 if 'r' in opts:
361 if 'r' in opts:
362 return stats
362 return stats
363 else:
363 else:
364 return None
364 return None
365
365
366 @line_magic
366 @line_magic
367 def pdb(self, parameter_s=''):
367 def pdb(self, parameter_s=''):
368 """Control the automatic calling of the pdb interactive debugger.
368 """Control the automatic calling of the pdb interactive debugger.
369
369
370 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
370 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
371 argument it works as a toggle.
371 argument it works as a toggle.
372
372
373 When an exception is triggered, IPython can optionally call the
373 When an exception is triggered, IPython can optionally call the
374 interactive pdb debugger after the traceback printout. %pdb toggles
374 interactive pdb debugger after the traceback printout. %pdb toggles
375 this feature on and off.
375 this feature on and off.
376
376
377 The initial state of this feature is set in your configuration
377 The initial state of this feature is set in your configuration
378 file (the option is ``InteractiveShell.pdb``).
378 file (the option is ``InteractiveShell.pdb``).
379
379
380 If you want to just activate the debugger AFTER an exception has fired,
380 If you want to just activate the debugger AFTER an exception has fired,
381 without having to type '%pdb on' and rerunning your code, you can use
381 without having to type '%pdb on' and rerunning your code, you can use
382 the %debug magic."""
382 the %debug magic."""
383
383
384 par = parameter_s.strip().lower()
384 par = parameter_s.strip().lower()
385
385
386 if par:
386 if par:
387 try:
387 try:
388 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
388 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
389 except KeyError:
389 except KeyError:
390 print ('Incorrect argument. Use on/1, off/0, '
390 print ('Incorrect argument. Use on/1, off/0, '
391 'or nothing for a toggle.')
391 'or nothing for a toggle.')
392 return
392 return
393 else:
393 else:
394 # toggle
394 # toggle
395 new_pdb = not self.shell.call_pdb
395 new_pdb = not self.shell.call_pdb
396
396
397 # set on the shell
397 # set on the shell
398 self.shell.call_pdb = new_pdb
398 self.shell.call_pdb = new_pdb
399 print('Automatic pdb calling has been turned',on_off(new_pdb))
399 print('Automatic pdb calling has been turned',on_off(new_pdb))
400
400
401 @skip_doctest
401 @skip_doctest
402 @magic_arguments.magic_arguments()
402 @magic_arguments.magic_arguments()
403 @magic_arguments.argument('--breakpoint', '-b', metavar='FILE:LINE',
403 @magic_arguments.argument('--breakpoint', '-b', metavar='FILE:LINE',
404 help="""
404 help="""
405 Set break point at LINE in FILE.
405 Set break point at LINE in FILE.
406 """
406 """
407 )
407 )
408 @magic_arguments.argument('statement', nargs='*',
408 @magic_arguments.argument('statement', nargs='*',
409 help="""
409 help="""
410 Code to run in debugger.
410 Code to run in debugger.
411 You can omit this in cell magic mode.
411 You can omit this in cell magic mode.
412 """
412 """
413 )
413 )
414 @line_cell_magic
414 @line_cell_magic
415 def debug(self, line='', cell=None):
415 def debug(self, line='', cell=None):
416 """Activate the interactive debugger.
416 """Activate the interactive debugger.
417
417
418 This magic command support two ways of activating debugger.
418 This magic command support two ways of activating debugger.
419 One is to activate debugger before executing code. This way, you
419 One is to activate debugger before executing code. This way, you
420 can set a break point, to step through the code from the point.
420 can set a break point, to step through the code from the point.
421 You can use this mode by giving statements to execute and optionally
421 You can use this mode by giving statements to execute and optionally
422 a breakpoint.
422 a breakpoint.
423
423
424 The other one is to activate debugger in post-mortem mode. You can
424 The other one is to activate debugger in post-mortem mode. You can
425 activate this mode simply running %debug without any argument.
425 activate this mode simply running %debug without any argument.
426 If an exception has just occurred, this lets you inspect its stack
426 If an exception has just occurred, this lets you inspect its stack
427 frames interactively. Note that this will always work only on the last
427 frames interactively. Note that this will always work only on the last
428 traceback that occurred, so you must call this quickly after an
428 traceback that occurred, so you must call this quickly after an
429 exception that you wish to inspect has fired, because if another one
429 exception that you wish to inspect has fired, because if another one
430 occurs, it clobbers the previous one.
430 occurs, it clobbers the previous one.
431
431
432 If you want IPython to automatically do this on every exception, see
432 If you want IPython to automatically do this on every exception, see
433 the %pdb magic for more details.
433 the %pdb magic for more details.
434 """
434 """
435 args = magic_arguments.parse_argstring(self.debug, line)
435 args = magic_arguments.parse_argstring(self.debug, line)
436
436
437 if not (args.breakpoint or args.statement or cell):
437 if not (args.breakpoint or args.statement or cell):
438 self._debug_post_mortem()
438 self._debug_post_mortem()
439 else:
439 else:
440 code = "\n".join(args.statement)
440 code = "\n".join(args.statement)
441 if cell:
441 if cell:
442 code += "\n" + cell
442 code += "\n" + cell
443 self._debug_exec(code, args.breakpoint)
443 self._debug_exec(code, args.breakpoint)
444
444
445 def _debug_post_mortem(self):
445 def _debug_post_mortem(self):
446 self.shell.debugger(force=True)
446 self.shell.debugger(force=True)
447
447
448 def _debug_exec(self, code, breakpoint):
448 def _debug_exec(self, code, breakpoint):
449 if breakpoint:
449 if breakpoint:
450 (filename, bp_line) = breakpoint.rsplit(':', 1)
450 (filename, bp_line) = breakpoint.rsplit(':', 1)
451 bp_line = int(bp_line)
451 bp_line = int(bp_line)
452 else:
452 else:
453 (filename, bp_line) = (None, None)
453 (filename, bp_line) = (None, None)
454 self._run_with_debugger(code, self.shell.user_ns, filename, bp_line)
454 self._run_with_debugger(code, self.shell.user_ns, filename, bp_line)
455
455
456 @line_magic
456 @line_magic
457 def tb(self, s):
457 def tb(self, s):
458 """Print the last traceback with the currently active exception mode.
458 """Print the last traceback with the currently active exception mode.
459
459
460 See %xmode for changing exception reporting modes."""
460 See %xmode for changing exception reporting modes."""
461 self.shell.showtraceback()
461 self.shell.showtraceback()
462
462
463 @skip_doctest
463 @skip_doctest
464 @line_magic
464 @line_magic
465 def run(self, parameter_s='', runner=None,
465 def run(self, parameter_s='', runner=None,
466 file_finder=get_py_filename):
466 file_finder=get_py_filename):
467 """Run the named file inside IPython as a program.
467 """Run the named file inside IPython as a program.
468
468
469 Usage::
469 Usage::
470
470
471 %run [-n -i -e -G]
471 %run [-n -i -e -G]
472 [( -t [-N<N>] | -d [-b<N>] | -p [profile options] )]
472 [( -t [-N<N>] | -d [-b<N>] | -p [profile options] )]
473 ( -m mod | file ) [args]
473 ( -m mod | file ) [args]
474
474
475 Parameters after the filename are passed as command-line arguments to
475 Parameters after the filename are passed as command-line arguments to
476 the program (put in sys.argv). Then, control returns to IPython's
476 the program (put in sys.argv). Then, control returns to IPython's
477 prompt.
477 prompt.
478
478
479 This is similar to running at a system prompt ``python file args``,
479 This is similar to running at a system prompt ``python file args``,
480 but with the advantage of giving you IPython's tracebacks, and of
480 but with the advantage of giving you IPython's tracebacks, and of
481 loading all variables into your interactive namespace for further use
481 loading all variables into your interactive namespace for further use
482 (unless -p is used, see below).
482 (unless -p is used, see below).
483
483
484 The file is executed in a namespace initially consisting only of
484 The file is executed in a namespace initially consisting only of
485 ``__name__=='__main__'`` and sys.argv constructed as indicated. It thus
485 ``__name__=='__main__'`` and sys.argv constructed as indicated. It thus
486 sees its environment as if it were being run as a stand-alone program
486 sees its environment as if it were being run as a stand-alone program
487 (except for sharing global objects such as previously imported
487 (except for sharing global objects such as previously imported
488 modules). But after execution, the IPython interactive namespace gets
488 modules). But after execution, the IPython interactive namespace gets
489 updated with all variables defined in the program (except for __name__
489 updated with all variables defined in the program (except for __name__
490 and sys.argv). This allows for very convenient loading of code for
490 and sys.argv). This allows for very convenient loading of code for
491 interactive work, while giving each program a 'clean sheet' to run in.
491 interactive work, while giving each program a 'clean sheet' to run in.
492
492
493 Arguments are expanded using shell-like glob match. Patterns
493 Arguments are expanded using shell-like glob match. Patterns
494 '*', '?', '[seq]' and '[!seq]' can be used. Additionally,
494 '*', '?', '[seq]' and '[!seq]' can be used. Additionally,
495 tilde '~' will be expanded into user's home directory. Unlike
495 tilde '~' will be expanded into user's home directory. Unlike
496 real shells, quotation does not suppress expansions. Use
496 real shells, quotation does not suppress expansions. Use
497 *two* back slashes (e.g. ``\\\\*``) to suppress expansions.
497 *two* back slashes (e.g. ``\\\\*``) to suppress expansions.
498 To completely disable these expansions, you can use -G flag.
498 To completely disable these expansions, you can use -G flag.
499
499
500 Options:
500 Options:
501
501
502 -n
502 -n
503 __name__ is NOT set to '__main__', but to the running file's name
503 __name__ is NOT set to '__main__', but to the running file's name
504 without extension (as python does under import). This allows running
504 without extension (as python does under import). This allows running
505 scripts and reloading the definitions in them without calling code
505 scripts and reloading the definitions in them without calling code
506 protected by an ``if __name__ == "__main__"`` clause.
506 protected by an ``if __name__ == "__main__"`` clause.
507
507
508 -i
508 -i
509 run the file in IPython's namespace instead of an empty one. This
509 run the file in IPython's namespace instead of an empty one. This
510 is useful if you are experimenting with code written in a text editor
510 is useful if you are experimenting with code written in a text editor
511 which depends on variables defined interactively.
511 which depends on variables defined interactively.
512
512
513 -e
513 -e
514 ignore sys.exit() calls or SystemExit exceptions in the script
514 ignore sys.exit() calls or SystemExit exceptions in the script
515 being run. This is particularly useful if IPython is being used to
515 being run. This is particularly useful if IPython is being used to
516 run unittests, which always exit with a sys.exit() call. In such
516 run unittests, which always exit with a sys.exit() call. In such
517 cases you are interested in the output of the test results, not in
517 cases you are interested in the output of the test results, not in
518 seeing a traceback of the unittest module.
518 seeing a traceback of the unittest module.
519
519
520 -t
520 -t
521 print timing information at the end of the run. IPython will give
521 print timing information at the end of the run. IPython will give
522 you an estimated CPU time consumption for your script, which under
522 you an estimated CPU time consumption for your script, which under
523 Unix uses the resource module to avoid the wraparound problems of
523 Unix uses the resource module to avoid the wraparound problems of
524 time.clock(). Under Unix, an estimate of time spent on system tasks
524 time.clock(). Under Unix, an estimate of time spent on system tasks
525 is also given (for Windows platforms this is reported as 0.0).
525 is also given (for Windows platforms this is reported as 0.0).
526
526
527 If -t is given, an additional ``-N<N>`` option can be given, where <N>
527 If -t is given, an additional ``-N<N>`` option can be given, where <N>
528 must be an integer indicating how many times you want the script to
528 must be an integer indicating how many times you want the script to
529 run. The final timing report will include total and per run results.
529 run. The final timing report will include total and per run results.
530
530
531 For example (testing the script uniq_stable.py)::
531 For example (testing the script uniq_stable.py)::
532
532
533 In [1]: run -t uniq_stable
533 In [1]: run -t uniq_stable
534
534
535 IPython CPU timings (estimated):
535 IPython CPU timings (estimated):
536 User : 0.19597 s.
536 User : 0.19597 s.
537 System: 0.0 s.
537 System: 0.0 s.
538
538
539 In [2]: run -t -N5 uniq_stable
539 In [2]: run -t -N5 uniq_stable
540
540
541 IPython CPU timings (estimated):
541 IPython CPU timings (estimated):
542 Total runs performed: 5
542 Total runs performed: 5
543 Times : Total Per run
543 Times : Total Per run
544 User : 0.910862 s, 0.1821724 s.
544 User : 0.910862 s, 0.1821724 s.
545 System: 0.0 s, 0.0 s.
545 System: 0.0 s, 0.0 s.
546
546
547 -d
547 -d
548 run your program under the control of pdb, the Python debugger.
548 run your program under the control of pdb, the Python debugger.
549 This allows you to execute your program step by step, watch variables,
549 This allows you to execute your program step by step, watch variables,
550 etc. Internally, what IPython does is similar to calling::
550 etc. Internally, what IPython does is similar to calling::
551
551
552 pdb.run('execfile("YOURFILENAME")')
552 pdb.run('execfile("YOURFILENAME")')
553
553
554 with a breakpoint set on line 1 of your file. You can change the line
554 with a breakpoint set on line 1 of your file. You can change the line
555 number for this automatic breakpoint to be <N> by using the -bN option
555 number for this automatic breakpoint to be <N> by using the -bN option
556 (where N must be an integer). For example::
556 (where N must be an integer). For example::
557
557
558 %run -d -b40 myscript
558 %run -d -b40 myscript
559
559
560 will set the first breakpoint at line 40 in myscript.py. Note that
560 will set the first breakpoint at line 40 in myscript.py. Note that
561 the first breakpoint must be set on a line which actually does
561 the first breakpoint must be set on a line which actually does
562 something (not a comment or docstring) for it to stop execution.
562 something (not a comment or docstring) for it to stop execution.
563
563
564 Or you can specify a breakpoint in a different file::
564 Or you can specify a breakpoint in a different file::
565
565
566 %run -d -b myotherfile.py:20 myscript
566 %run -d -b myotherfile.py:20 myscript
567
567
568 When the pdb debugger starts, you will see a (Pdb) prompt. You must
568 When the pdb debugger starts, you will see a (Pdb) prompt. You must
569 first enter 'c' (without quotes) to start execution up to the first
569 first enter 'c' (without quotes) to start execution up to the first
570 breakpoint.
570 breakpoint.
571
571
572 Entering 'help' gives information about the use of the debugger. You
572 Entering 'help' gives information about the use of the debugger. You
573 can easily see pdb's full documentation with "import pdb;pdb.help()"
573 can easily see pdb's full documentation with "import pdb;pdb.help()"
574 at a prompt.
574 at a prompt.
575
575
576 -p
576 -p
577 run program under the control of the Python profiler module (which
577 run program under the control of the Python profiler module (which
578 prints a detailed report of execution times, function calls, etc).
578 prints a detailed report of execution times, function calls, etc).
579
579
580 You can pass other options after -p which affect the behavior of the
580 You can pass other options after -p which affect the behavior of the
581 profiler itself. See the docs for %prun for details.
581 profiler itself. See the docs for %prun for details.
582
582
583 In this mode, the program's variables do NOT propagate back to the
583 In this mode, the program's variables do NOT propagate back to the
584 IPython interactive namespace (because they remain in the namespace
584 IPython interactive namespace (because they remain in the namespace
585 where the profiler executes them).
585 where the profiler executes them).
586
586
587 Internally this triggers a call to %prun, see its documentation for
587 Internally this triggers a call to %prun, see its documentation for
588 details on the options available specifically for profiling.
588 details on the options available specifically for profiling.
589
589
590 There is one special usage for which the text above doesn't apply:
590 There is one special usage for which the text above doesn't apply:
591 if the filename ends with .ipy[nb], the file is run as ipython script,
591 if the filename ends with .ipy[nb], the file is run as ipython script,
592 just as if the commands were written on IPython prompt.
592 just as if the commands were written on IPython prompt.
593
593
594 -m
594 -m
595 specify module name to load instead of script path. Similar to
595 specify module name to load instead of script path. Similar to
596 the -m option for the python interpreter. Use this option last if you
596 the -m option for the python interpreter. Use this option last if you
597 want to combine with other %run options. Unlike the python interpreter
597 want to combine with other %run options. Unlike the python interpreter
598 only source modules are allowed no .pyc or .pyo files.
598 only source modules are allowed no .pyc or .pyo files.
599 For example::
599 For example::
600
600
601 %run -m example
601 %run -m example
602
602
603 will run the example module.
603 will run the example module.
604
604
605 -G
605 -G
606 disable shell-like glob expansion of arguments.
606 disable shell-like glob expansion of arguments.
607
607
608 """
608 """
609
609
610 # get arguments and set sys.argv for program to be run.
610 # get arguments and set sys.argv for program to be run.
611 opts, arg_lst = self.parse_options(parameter_s,
611 opts, arg_lst = self.parse_options(parameter_s,
612 'nidtN:b:pD:l:rs:T:em:G',
612 'nidtN:b:pD:l:rs:T:em:G',
613 mode='list', list_all=1)
613 mode='list', list_all=1)
614 if "m" in opts:
614 if "m" in opts:
615 modulename = opts["m"][0]
615 modulename = opts["m"][0]
616 modpath = find_mod(modulename)
616 modpath = find_mod(modulename)
617 if modpath is None:
617 if modpath is None:
618 warn('%r is not a valid modulename on sys.path'%modulename)
618 warn('%r is not a valid modulename on sys.path'%modulename)
619 return
619 return
620 arg_lst = [modpath] + arg_lst
620 arg_lst = [modpath] + arg_lst
621 try:
621 try:
622 filename = file_finder(arg_lst[0])
622 filename = file_finder(arg_lst[0])
623 except IndexError:
623 except IndexError:
624 warn('you must provide at least a filename.')
624 warn('you must provide at least a filename.')
625 print('\n%run:\n', oinspect.getdoc(self.run))
625 print('\n%run:\n', oinspect.getdoc(self.run))
626 return
626 return
627 except IOError as e:
627 except IOError as e:
628 try:
628 try:
629 msg = str(e)
629 msg = str(e)
630 except UnicodeError:
630 except UnicodeError:
631 msg = e.message
631 msg = e.message
632 error(msg)
632 error(msg)
633 return
633 return
634
634
635 if filename.lower().endswith(('.ipy', '.ipynb')):
635 if filename.lower().endswith(('.ipy', '.ipynb')):
636 with preserve_keys(self.shell.user_ns, '__file__'):
636 with preserve_keys(self.shell.user_ns, '__file__'):
637 self.shell.user_ns['__file__'] = filename
637 self.shell.user_ns['__file__'] = filename
638 self.shell.safe_execfile_ipy(filename)
638 self.shell.safe_execfile_ipy(filename)
639 return
639 return
640
640
641 # Control the response to exit() calls made by the script being run
641 # Control the response to exit() calls made by the script being run
642 exit_ignore = 'e' in opts
642 exit_ignore = 'e' in opts
643
643
644 # Make sure that the running script gets a proper sys.argv as if it
644 # Make sure that the running script gets a proper sys.argv as if it
645 # were run from a system shell.
645 # were run from a system shell.
646 save_argv = sys.argv # save it for later restoring
646 save_argv = sys.argv # save it for later restoring
647
647
648 if 'G' in opts:
648 if 'G' in opts:
649 args = arg_lst[1:]
649 args = arg_lst[1:]
650 else:
650 else:
651 # tilde and glob expansion
651 # tilde and glob expansion
652 args = shellglob(map(os.path.expanduser, arg_lst[1:]))
652 args = shellglob(map(os.path.expanduser, arg_lst[1:]))
653
653
654 sys.argv = [filename] + args # put in the proper filename
654 sys.argv = [filename] + args # put in the proper filename
655 # protect sys.argv from potential unicode strings on Python 2:
655 # protect sys.argv from potential unicode strings on Python 2:
656 if not py3compat.PY3:
656 if not py3compat.PY3:
657 sys.argv = [ py3compat.cast_bytes(a) for a in sys.argv ]
657 sys.argv = [ py3compat.cast_bytes(a) for a in sys.argv ]
658
658
659 if 'i' in opts:
659 if 'i' in opts:
660 # Run in user's interactive namespace
660 # Run in user's interactive namespace
661 prog_ns = self.shell.user_ns
661 prog_ns = self.shell.user_ns
662 __name__save = self.shell.user_ns['__name__']
662 __name__save = self.shell.user_ns['__name__']
663 prog_ns['__name__'] = '__main__'
663 prog_ns['__name__'] = '__main__'
664 main_mod = self.shell.user_module
664 main_mod = self.shell.user_module
665
665
666 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
666 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
667 # set the __file__ global in the script's namespace
667 # set the __file__ global in the script's namespace
668 # TK: Is this necessary in interactive mode?
668 # TK: Is this necessary in interactive mode?
669 prog_ns['__file__'] = filename
669 prog_ns['__file__'] = filename
670 else:
670 else:
671 # Run in a fresh, empty namespace
671 # Run in a fresh, empty namespace
672 if 'n' in opts:
672 if 'n' in opts:
673 name = os.path.splitext(os.path.basename(filename))[0]
673 name = os.path.splitext(os.path.basename(filename))[0]
674 else:
674 else:
675 name = '__main__'
675 name = '__main__'
676
676
677 # The shell MUST hold a reference to prog_ns so after %run
677 # The shell MUST hold a reference to prog_ns so after %run
678 # exits, the python deletion mechanism doesn't zero it out
678 # exits, the python deletion mechanism doesn't zero it out
679 # (leaving dangling references). See interactiveshell for details
679 # (leaving dangling references). See interactiveshell for details
680 main_mod = self.shell.new_main_mod(filename, name)
680 main_mod = self.shell.new_main_mod(filename, name)
681 prog_ns = main_mod.__dict__
681 prog_ns = main_mod.__dict__
682
682
683 # pickle fix. See interactiveshell for an explanation. But we need to
683 # pickle fix. See interactiveshell for an explanation. But we need to
684 # make sure that, if we overwrite __main__, we replace it at the end
684 # make sure that, if we overwrite __main__, we replace it at the end
685 main_mod_name = prog_ns['__name__']
685 main_mod_name = prog_ns['__name__']
686
686
687 if main_mod_name == '__main__':
687 if main_mod_name == '__main__':
688 restore_main = sys.modules['__main__']
688 restore_main = sys.modules['__main__']
689 else:
689 else:
690 restore_main = False
690 restore_main = False
691
691
692 # This needs to be undone at the end to prevent holding references to
692 # This needs to be undone at the end to prevent holding references to
693 # every single object ever created.
693 # every single object ever created.
694 sys.modules[main_mod_name] = main_mod
694 sys.modules[main_mod_name] = main_mod
695
695
696 if 'p' in opts or 'd' in opts:
696 if 'p' in opts or 'd' in opts:
697 if 'm' in opts:
697 if 'm' in opts:
698 code = 'run_module(modulename, prog_ns)'
698 code = 'run_module(modulename, prog_ns)'
699 code_ns = {
699 code_ns = {
700 'run_module': self.shell.safe_run_module,
700 'run_module': self.shell.safe_run_module,
701 'prog_ns': prog_ns,
701 'prog_ns': prog_ns,
702 'modulename': modulename,
702 'modulename': modulename,
703 }
703 }
704 else:
704 else:
705 if 'd' in opts:
705 if 'd' in opts:
706 # allow exceptions to raise in debug mode
706 # allow exceptions to raise in debug mode
707 code = 'execfile(filename, prog_ns, raise_exceptions=True)'
707 code = 'execfile(filename, prog_ns, raise_exceptions=True)'
708 else:
708 else:
709 code = 'execfile(filename, prog_ns)'
709 code = 'execfile(filename, prog_ns)'
710 code_ns = {
710 code_ns = {
711 'execfile': self.shell.safe_execfile,
711 'execfile': self.shell.safe_execfile,
712 'prog_ns': prog_ns,
712 'prog_ns': prog_ns,
713 'filename': get_py_filename(filename),
713 'filename': get_py_filename(filename),
714 }
714 }
715
715
716 try:
716 try:
717 stats = None
717 stats = None
718 if 'p' in opts:
718 if 'p' in opts:
719 stats = self._run_with_profiler(code, opts, code_ns)
719 stats = self._run_with_profiler(code, opts, code_ns)
720 else:
720 else:
721 if 'd' in opts:
721 if 'd' in opts:
722 bp_file, bp_line = parse_breakpoint(
722 bp_file, bp_line = parse_breakpoint(
723 opts.get('b', ['1'])[0], filename)
723 opts.get('b', ['1'])[0], filename)
724 self._run_with_debugger(
724 self._run_with_debugger(
725 code, code_ns, filename, bp_line, bp_file)
725 code, code_ns, filename, bp_line, bp_file)
726 else:
726 else:
727 if 'm' in opts:
727 if 'm' in opts:
728 def run():
728 def run():
729 self.shell.safe_run_module(modulename, prog_ns)
729 self.shell.safe_run_module(modulename, prog_ns)
730 else:
730 else:
731 if runner is None:
731 if runner is None:
732 runner = self.default_runner
732 runner = self.default_runner
733 if runner is None:
733 if runner is None:
734 runner = self.shell.safe_execfile
734 runner = self.shell.safe_execfile
735
735
736 def run():
736 def run():
737 runner(filename, prog_ns, prog_ns,
737 runner(filename, prog_ns, prog_ns,
738 exit_ignore=exit_ignore)
738 exit_ignore=exit_ignore)
739
739
740 if 't' in opts:
740 if 't' in opts:
741 # timed execution
741 # timed execution
742 try:
742 try:
743 nruns = int(opts['N'][0])
743 nruns = int(opts['N'][0])
744 if nruns < 1:
744 if nruns < 1:
745 error('Number of runs must be >=1')
745 error('Number of runs must be >=1')
746 return
746 return
747 except (KeyError):
747 except (KeyError):
748 nruns = 1
748 nruns = 1
749 self._run_with_timing(run, nruns)
749 self._run_with_timing(run, nruns)
750 else:
750 else:
751 # regular execution
751 # regular execution
752 run()
752 run()
753
753
754 if 'i' in opts:
754 if 'i' in opts:
755 self.shell.user_ns['__name__'] = __name__save
755 self.shell.user_ns['__name__'] = __name__save
756 else:
756 else:
757 # update IPython interactive namespace
757 # update IPython interactive namespace
758
758
759 # Some forms of read errors on the file may mean the
759 # Some forms of read errors on the file may mean the
760 # __name__ key was never set; using pop we don't have to
760 # __name__ key was never set; using pop we don't have to
761 # worry about a possible KeyError.
761 # worry about a possible KeyError.
762 prog_ns.pop('__name__', None)
762 prog_ns.pop('__name__', None)
763
763
764 with preserve_keys(self.shell.user_ns, '__file__'):
764 with preserve_keys(self.shell.user_ns, '__file__'):
765 self.shell.user_ns.update(prog_ns)
765 self.shell.user_ns.update(prog_ns)
766 finally:
766 finally:
767 # It's a bit of a mystery why, but __builtins__ can change from
767 # It's a bit of a mystery why, but __builtins__ can change from
768 # being a module to becoming a dict missing some key data after
768 # being a module to becoming a dict missing some key data after
769 # %run. As best I can see, this is NOT something IPython is doing
769 # %run. As best I can see, this is NOT something IPython is doing
770 # at all, and similar problems have been reported before:
770 # at all, and similar problems have been reported before:
771 # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html
771 # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html
772 # Since this seems to be done by the interpreter itself, the best
772 # Since this seems to be done by the interpreter itself, the best
773 # we can do is to at least restore __builtins__ for the user on
773 # we can do is to at least restore __builtins__ for the user on
774 # exit.
774 # exit.
775 self.shell.user_ns['__builtins__'] = builtin_mod
775 self.shell.user_ns['__builtins__'] = builtin_mod
776
776
777 # Ensure key global structures are restored
777 # Ensure key global structures are restored
778 sys.argv = save_argv
778 sys.argv = save_argv
779 if restore_main:
779 if restore_main:
780 sys.modules['__main__'] = restore_main
780 sys.modules['__main__'] = restore_main
781 else:
781 else:
782 # Remove from sys.modules the reference to main_mod we'd
782 # Remove from sys.modules the reference to main_mod we'd
783 # added. Otherwise it will trap references to objects
783 # added. Otherwise it will trap references to objects
784 # contained therein.
784 # contained therein.
785 del sys.modules[main_mod_name]
785 del sys.modules[main_mod_name]
786
786
787 return stats
787 return stats
788
788
789 def _run_with_debugger(self, code, code_ns, filename=None,
789 def _run_with_debugger(self, code, code_ns, filename=None,
790 bp_line=None, bp_file=None):
790 bp_line=None, bp_file=None):
791 """
791 """
792 Run `code` in debugger with a break point.
792 Run `code` in debugger with a break point.
793
793
794 Parameters
794 Parameters
795 ----------
795 ----------
796 code : str
796 code : str
797 Code to execute.
797 Code to execute.
798 code_ns : dict
798 code_ns : dict
799 A namespace in which `code` is executed.
799 A namespace in which `code` is executed.
800 filename : str
800 filename : str
801 `code` is ran as if it is in `filename`.
801 `code` is ran as if it is in `filename`.
802 bp_line : int, optional
802 bp_line : int, optional
803 Line number of the break point.
803 Line number of the break point.
804 bp_file : str, optional
804 bp_file : str, optional
805 Path to the file in which break point is specified.
805 Path to the file in which break point is specified.
806 `filename` is used if not given.
806 `filename` is used if not given.
807
807
808 Raises
808 Raises
809 ------
809 ------
810 UsageError
810 UsageError
811 If the break point given by `bp_line` is not valid.
811 If the break point given by `bp_line` is not valid.
812
812
813 """
813 """
814 deb = self.shell.InteractiveTB.pdb
814 deb = self.shell.InteractiveTB.pdb
815 if not deb:
815 if not deb:
816 self.shell.InteractiveTB.pdb = self.shell.InteractiveTB.debugger_cls()
816 self.shell.InteractiveTB.pdb = self.shell.InteractiveTB.debugger_cls()
817 deb = self.shell.InteractiveTB.pdb
817 deb = self.shell.InteractiveTB.pdb
818
818
819 # deb.checkline() fails if deb.curframe exists but is None; it can
819 # deb.checkline() fails if deb.curframe exists but is None; it can
820 # handle it not existing. https://github.com/ipython/ipython/issues/10028
820 # handle it not existing. https://github.com/ipython/ipython/issues/10028
821 if hasattr(deb, 'curframe'):
821 if hasattr(deb, 'curframe'):
822 del deb.curframe
822 del deb.curframe
823
823
824 # reset Breakpoint state, which is moronically kept
824 # reset Breakpoint state, which is moronically kept
825 # in a class
825 # in a class
826 bdb.Breakpoint.next = 1
826 bdb.Breakpoint.next = 1
827 bdb.Breakpoint.bplist = {}
827 bdb.Breakpoint.bplist = {}
828 bdb.Breakpoint.bpbynumber = [None]
828 bdb.Breakpoint.bpbynumber = [None]
829 if bp_line is not None:
829 if bp_line is not None:
830 # Set an initial breakpoint to stop execution
830 # Set an initial breakpoint to stop execution
831 maxtries = 10
831 maxtries = 10
832 bp_file = bp_file or filename
832 bp_file = bp_file or filename
833 checkline = deb.checkline(bp_file, bp_line)
833 checkline = deb.checkline(bp_file, bp_line)
834 if not checkline:
834 if not checkline:
835 for bp in range(bp_line + 1, bp_line + maxtries + 1):
835 for bp in range(bp_line + 1, bp_line + maxtries + 1):
836 if deb.checkline(bp_file, bp):
836 if deb.checkline(bp_file, bp):
837 break
837 break
838 else:
838 else:
839 msg = ("\nI failed to find a valid line to set "
839 msg = ("\nI failed to find a valid line to set "
840 "a breakpoint\n"
840 "a breakpoint\n"
841 "after trying up to line: %s.\n"
841 "after trying up to line: %s.\n"
842 "Please set a valid breakpoint manually "
842 "Please set a valid breakpoint manually "
843 "with the -b option." % bp)
843 "with the -b option." % bp)
844 raise UsageError(msg)
844 raise UsageError(msg)
845 # if we find a good linenumber, set the breakpoint
845 # if we find a good linenumber, set the breakpoint
846 deb.do_break('%s:%s' % (bp_file, bp_line))
846 deb.do_break('%s:%s' % (bp_file, bp_line))
847
847
848 if filename:
848 if filename:
849 # Mimic Pdb._runscript(...)
849 # Mimic Pdb._runscript(...)
850 deb._wait_for_mainpyfile = True
850 deb._wait_for_mainpyfile = True
851 deb.mainpyfile = deb.canonic(filename)
851 deb.mainpyfile = deb.canonic(filename)
852
852
853 # Start file run
853 # Start file run
854 print("NOTE: Enter 'c' at the %s prompt to continue execution." % deb.prompt)
854 print("NOTE: Enter 'c' at the %s prompt to continue execution." % deb.prompt)
855 try:
855 try:
856 if filename:
856 if filename:
857 # save filename so it can be used by methods on the deb object
857 # save filename so it can be used by methods on the deb object
858 deb._exec_filename = filename
858 deb._exec_filename = filename
859 while True:
859 while True:
860 try:
860 try:
861 deb.run(code, code_ns)
861 deb.run(code, code_ns)
862 except Restart:
862 except Restart:
863 print("Restarting")
863 print("Restarting")
864 if filename:
864 if filename:
865 deb._wait_for_mainpyfile = True
865 deb._wait_for_mainpyfile = True
866 deb.mainpyfile = deb.canonic(filename)
866 deb.mainpyfile = deb.canonic(filename)
867 continue
867 continue
868 else:
868 else:
869 break
869 break
870
870
871
871
872 except:
872 except:
873 etype, value, tb = sys.exc_info()
873 etype, value, tb = sys.exc_info()
874 # Skip three frames in the traceback: the %run one,
874 # Skip three frames in the traceback: the %run one,
875 # one inside bdb.py, and the command-line typed by the
875 # one inside bdb.py, and the command-line typed by the
876 # user (run by exec in pdb itself).
876 # user (run by exec in pdb itself).
877 self.shell.InteractiveTB(etype, value, tb, tb_offset=3)
877 self.shell.InteractiveTB(etype, value, tb, tb_offset=3)
878
878
879 @staticmethod
879 @staticmethod
880 def _run_with_timing(run, nruns):
880 def _run_with_timing(run, nruns):
881 """
881 """
882 Run function `run` and print timing information.
882 Run function `run` and print timing information.
883
883
884 Parameters
884 Parameters
885 ----------
885 ----------
886 run : callable
886 run : callable
887 Any callable object which takes no argument.
887 Any callable object which takes no argument.
888 nruns : int
888 nruns : int
889 Number of times to execute `run`.
889 Number of times to execute `run`.
890
890
891 """
891 """
892 twall0 = time.time()
892 twall0 = time.time()
893 if nruns == 1:
893 if nruns == 1:
894 t0 = clock2()
894 t0 = clock2()
895 run()
895 run()
896 t1 = clock2()
896 t1 = clock2()
897 t_usr = t1[0] - t0[0]
897 t_usr = t1[0] - t0[0]
898 t_sys = t1[1] - t0[1]
898 t_sys = t1[1] - t0[1]
899 print("\nIPython CPU timings (estimated):")
899 print("\nIPython CPU timings (estimated):")
900 print(" User : %10.2f s." % t_usr)
900 print(" User : %10.2f s." % t_usr)
901 print(" System : %10.2f s." % t_sys)
901 print(" System : %10.2f s." % t_sys)
902 else:
902 else:
903 runs = range(nruns)
903 runs = range(nruns)
904 t0 = clock2()
904 t0 = clock2()
905 for nr in runs:
905 for nr in runs:
906 run()
906 run()
907 t1 = clock2()
907 t1 = clock2()
908 t_usr = t1[0] - t0[0]
908 t_usr = t1[0] - t0[0]
909 t_sys = t1[1] - t0[1]
909 t_sys = t1[1] - t0[1]
910 print("\nIPython CPU timings (estimated):")
910 print("\nIPython CPU timings (estimated):")
911 print("Total runs performed:", nruns)
911 print("Total runs performed:", nruns)
912 print(" Times : %10s %10s" % ('Total', 'Per run'))
912 print(" Times : %10s %10s" % ('Total', 'Per run'))
913 print(" User : %10.2f s, %10.2f s." % (t_usr, t_usr / nruns))
913 print(" User : %10.2f s, %10.2f s." % (t_usr, t_usr / nruns))
914 print(" System : %10.2f s, %10.2f s." % (t_sys, t_sys / nruns))
914 print(" System : %10.2f s, %10.2f s." % (t_sys, t_sys / nruns))
915 twall1 = time.time()
915 twall1 = time.time()
916 print("Wall time: %10.2f s." % (twall1 - twall0))
916 print("Wall time: %10.2f s." % (twall1 - twall0))
917
917
918 @skip_doctest
918 @skip_doctest
919 @line_cell_magic
919 @line_cell_magic
920 def timeit(self, line='', cell=None):
920 def timeit(self, line='', cell=None):
921 """Time execution of a Python statement or expression
921 """Time execution of a Python statement or expression
922
922
923 Usage, in line mode:
923 Usage, in line mode:
924 %timeit [-n<N> -r<R> [-t|-c] -q -p<P> -o] statement
924 %timeit [-n<N> -r<R> [-t|-c] -q -p<P> -o] statement
925 or in cell mode:
925 or in cell mode:
926 %%timeit [-n<N> -r<R> [-t|-c] -q -p<P> -o] setup_code
926 %%timeit [-n<N> -r<R> [-t|-c] -q -p<P> -o] setup_code
927 code
927 code
928 code...
928 code...
929
929
930 Time execution of a Python statement or expression using the timeit
930 Time execution of a Python statement or expression using the timeit
931 module. This function can be used both as a line and cell magic:
931 module. This function can be used both as a line and cell magic:
932
932
933 - In line mode you can time a single-line statement (though multiple
933 - In line mode you can time a single-line statement (though multiple
934 ones can be chained with using semicolons).
934 ones can be chained with using semicolons).
935
935
936 - In cell mode, the statement in the first line is used as setup code
936 - In cell mode, the statement in the first line is used as setup code
937 (executed but not timed) and the body of the cell is timed. The cell
937 (executed but not timed) and the body of the cell is timed. The cell
938 body has access to any variables created in the setup code.
938 body has access to any variables created in the setup code.
939
939
940 Options:
940 Options:
941 -n<N>: execute the given statement <N> times in a loop. If this value
941 -n<N>: execute the given statement <N> times in a loop. If this value
942 is not given, a fitting value is chosen.
942 is not given, a fitting value is chosen.
943
943
944 -r<R>: repeat the loop iteration <R> times and take the best result.
944 -r<R>: repeat the loop iteration <R> times and take the best result.
945 Default: 3
945 Default: 3
946
946
947 -t: use time.time to measure the time, which is the default on Unix.
947 -t: use time.time to measure the time, which is the default on Unix.
948 This function measures wall time.
948 This function measures wall time.
949
949
950 -c: use time.clock to measure the time, which is the default on
950 -c: use time.clock to measure the time, which is the default on
951 Windows and measures wall time. On Unix, resource.getrusage is used
951 Windows and measures wall time. On Unix, resource.getrusage is used
952 instead and returns the CPU user time.
952 instead and returns the CPU user time.
953
953
954 -p<P>: use a precision of <P> digits to display the timing result.
954 -p<P>: use a precision of <P> digits to display the timing result.
955 Default: 3
955 Default: 3
956
956
957 -q: Quiet, do not print result.
957 -q: Quiet, do not print result.
958
958
959 -o: return a TimeitResult that can be stored in a variable to inspect
959 -o: return a TimeitResult that can be stored in a variable to inspect
960 the result in more details.
960 the result in more details.
961
961
962
962
963 Examples
963 Examples
964 --------
964 --------
965 ::
965 ::
966
966
967 In [1]: %timeit pass
967 In [1]: %timeit pass
968 100000000 loops, average of 7: 5.48 ns +- 0.354 ns per loop (using standard deviation)
968 100000000 loops, average of 7: 5.48 ns +- 0.354 ns per loop (using standard deviation)
969
969
970 In [2]: u = None
970 In [2]: u = None
971
971
972 In [3]: %timeit u is None
972 In [3]: %timeit u is None
973 10000000 loops, average of 7: 22.7 ns +- 2.33 ns per loop (using standard deviation)
973 10000000 loops, average of 7: 22.7 ns +- 2.33 ns per loop (using standard deviation)
974
974
975 In [4]: %timeit -r 4 u == None
975 In [4]: %timeit -r 4 u == None
976 10000000 loops, average of 4: 27.5 ns +- 2.91 ns per loop (using standard deviation)
976 10000000 loops, average of 4: 27.5 ns +- 2.91 ns per loop (using standard deviation)
977
977
978 In [5]: import time
978 In [5]: import time
979
979
980 In [6]: %timeit -n1 time.sleep(2)
980 In [6]: %timeit -n1 time.sleep(2)
981 1 loop, average of 7: 2 s +- 4.71 Β΅s per loop (using standard deviation)
981 1 loop, average of 7: 2 s +- 4.71 Β΅s per loop (using standard deviation)
982
982
983
983
984 The times reported by %timeit will be slightly higher than those
984 The times reported by %timeit will be slightly higher than those
985 reported by the timeit.py script when variables are accessed. This is
985 reported by the timeit.py script when variables are accessed. This is
986 due to the fact that %timeit executes the statement in the namespace
986 due to the fact that %timeit executes the statement in the namespace
987 of the shell, compared with timeit.py, which uses a single setup
987 of the shell, compared with timeit.py, which uses a single setup
988 statement to import function or create variables. Generally, the bias
988 statement to import function or create variables. Generally, the bias
989 does not matter as long as results from timeit.py are not mixed with
989 does not matter as long as results from timeit.py are not mixed with
990 those from %timeit."""
990 those from %timeit."""
991
991
992 opts, stmt = self.parse_options(line,'n:r:tcp:qo',
992 opts, stmt = self.parse_options(line,'n:r:tcp:qo',
993 posix=False, strict=False)
993 posix=False, strict=False)
994 if stmt == "" and cell is None:
994 if stmt == "" and cell is None:
995 return
995 return
996
996
997 timefunc = timeit.default_timer
997 timefunc = timeit.default_timer
998 number = int(getattr(opts, "n", 0))
998 number = int(getattr(opts, "n", 0))
999 default_repeat = 7 if timeit.default_repeat < 7 else timeit.default_repeat
999 default_repeat = 7 if timeit.default_repeat < 7 else timeit.default_repeat
1000 repeat = int(getattr(opts, "r", default_repeat))
1000 repeat = int(getattr(opts, "r", default_repeat))
1001 precision = int(getattr(opts, "p", 3))
1001 precision = int(getattr(opts, "p", 3))
1002 quiet = 'q' in opts
1002 quiet = 'q' in opts
1003 return_result = 'o' in opts
1003 return_result = 'o' in opts
1004 if hasattr(opts, "t"):
1004 if hasattr(opts, "t"):
1005 timefunc = time.time
1005 timefunc = time.time
1006 if hasattr(opts, "c"):
1006 if hasattr(opts, "c"):
1007 timefunc = clock
1007 timefunc = clock
1008
1008
1009 timer = Timer(timer=timefunc)
1009 timer = Timer(timer=timefunc)
1010 # this code has tight coupling to the inner workings of timeit.Timer,
1010 # this code has tight coupling to the inner workings of timeit.Timer,
1011 # but is there a better way to achieve that the code stmt has access
1011 # but is there a better way to achieve that the code stmt has access
1012 # to the shell namespace?
1012 # to the shell namespace?
1013 transform = self.shell.input_splitter.transform_cell
1013 transform = self.shell.input_splitter.transform_cell
1014
1014
1015 if cell is None:
1015 if cell is None:
1016 # called as line magic
1016 # called as line magic
1017 ast_setup = self.shell.compile.ast_parse("pass")
1017 ast_setup = self.shell.compile.ast_parse("pass")
1018 ast_stmt = self.shell.compile.ast_parse(transform(stmt))
1018 ast_stmt = self.shell.compile.ast_parse(transform(stmt))
1019 else:
1019 else:
1020 ast_setup = self.shell.compile.ast_parse(transform(stmt))
1020 ast_setup = self.shell.compile.ast_parse(transform(stmt))
1021 ast_stmt = self.shell.compile.ast_parse(transform(cell))
1021 ast_stmt = self.shell.compile.ast_parse(transform(cell))
1022
1022
1023 ast_setup = self.shell.transform_ast(ast_setup)
1023 ast_setup = self.shell.transform_ast(ast_setup)
1024 ast_stmt = self.shell.transform_ast(ast_stmt)
1024 ast_stmt = self.shell.transform_ast(ast_stmt)
1025
1025
1026 # This codestring is taken from timeit.template - we fill it in as an
1026 # This codestring is taken from timeit.template - we fill it in as an
1027 # AST, so that we can apply our AST transformations to the user code
1027 # AST, so that we can apply our AST transformations to the user code
1028 # without affecting the timing code.
1028 # without affecting the timing code.
1029 timeit_ast_template = ast.parse('def inner(_it, _timer):\n'
1029 timeit_ast_template = ast.parse('def inner(_it, _timer):\n'
1030 ' setup\n'
1030 ' setup\n'
1031 ' _t0 = _timer()\n'
1031 ' _t0 = _timer()\n'
1032 ' for _i in _it:\n'
1032 ' for _i in _it:\n'
1033 ' stmt\n'
1033 ' stmt\n'
1034 ' _t1 = _timer()\n'
1034 ' _t1 = _timer()\n'
1035 ' return _t1 - _t0\n')
1035 ' return _t1 - _t0\n')
1036
1036
1037 timeit_ast = TimeitTemplateFiller(ast_setup, ast_stmt).visit(timeit_ast_template)
1037 timeit_ast = TimeitTemplateFiller(ast_setup, ast_stmt).visit(timeit_ast_template)
1038 timeit_ast = ast.fix_missing_locations(timeit_ast)
1038 timeit_ast = ast.fix_missing_locations(timeit_ast)
1039
1039
1040 # Track compilation time so it can be reported if too long
1040 # Track compilation time so it can be reported if too long
1041 # Minimum time above which compilation time will be reported
1041 # Minimum time above which compilation time will be reported
1042 tc_min = 0.1
1042 tc_min = 0.1
1043
1043
1044 t0 = clock()
1044 t0 = clock()
1045 code = self.shell.compile(timeit_ast, "<magic-timeit>", "exec")
1045 code = self.shell.compile(timeit_ast, "<magic-timeit>", "exec")
1046 tc = clock()-t0
1046 tc = clock()-t0
1047
1047
1048 ns = {}
1048 ns = {}
1049 exec(code, self.shell.user_ns, ns)
1049 exec(code, self.shell.user_ns, ns)
1050 timer.inner = ns["inner"]
1050 timer.inner = ns["inner"]
1051
1051
1052 # This is used to check if there is a huge difference between the
1052 # This is used to check if there is a huge difference between the
1053 # best and worst timings.
1053 # best and worst timings.
1054 # Issue: https://github.com/ipython/ipython/issues/6471
1054 # Issue: https://github.com/ipython/ipython/issues/6471
1055 if number == 0:
1055 if number == 0:
1056 # determine number so that 0.2 <= total time < 2.0
1056 # determine number so that 0.2 <= total time < 2.0
1057 for index in range(0, 10):
1057 for index in range(0, 10):
1058 number = 10 ** index
1058 number = 10 ** index
1059 time_number = timer.timeit(number)
1059 time_number = timer.timeit(number)
1060 if time_number >= 0.2:
1060 if time_number >= 0.2:
1061 break
1061 break
1062
1062
1063 all_runs = timer.repeat(repeat, number)
1063 all_runs = timer.repeat(repeat, number)
1064 best = min(all_runs) / number
1064 best = min(all_runs) / number
1065 worst = max(all_runs) / number
1065 worst = max(all_runs) / number
1066 timeit_result = TimeitResult(number, repeat, best, worst, all_runs, tc, precision)
1066 timeit_result = TimeitResult(number, repeat, best, worst, all_runs, tc, precision)
1067
1067
1068 if not quiet :
1068 if not quiet :
1069 # Check best timing is greater than zero to avoid a
1069 # Check best timing is greater than zero to avoid a
1070 # ZeroDivisionError.
1070 # ZeroDivisionError.
1071 # In cases where the slowest timing is lesser than a micosecond
1071 # In cases where the slowest timing is lesser than a micosecond
1072 # we assume that it does not really matter if the fastest
1072 # we assume that it does not really matter if the fastest
1073 # timing is 4 times faster than the slowest timing or not.
1073 # timing is 4 times faster than the slowest timing or not.
1074 if worst > 4 * best and best > 0 and worst > 1e-6:
1074 if worst > 4 * best and best > 0 and worst > 1e-6:
1075 print("The slowest run took %0.2f times longer than the "
1075 print("The slowest run took %0.2f times longer than the "
1076 "fastest. This could mean that an intermediate result "
1076 "fastest. This could mean that an intermediate result "
1077 "is being cached." % (worst / best))
1077 "is being cached." % (worst / best))
1078
1078
1079 print( timeit_result )
1079 print( timeit_result )
1080
1080
1081 if tc > tc_min:
1081 if tc > tc_min:
1082 print("Compiler time: %.2f s" % tc)
1082 print("Compiler time: %.2f s" % tc)
1083 if return_result:
1083 if return_result:
1084 return timeit_result
1084 return timeit_result
1085
1085
1086 @skip_doctest
1086 @skip_doctest
1087 @needs_local_scope
1087 @needs_local_scope
1088 @line_cell_magic
1088 @line_cell_magic
1089 def time(self,line='', cell=None, local_ns=None):
1089 def time(self,line='', cell=None, local_ns=None):
1090 """Time execution of a Python statement or expression.
1090 """Time execution of a Python statement or expression.
1091
1091
1092 The CPU and wall clock times are printed, and the value of the
1092 The CPU and wall clock times are printed, and the value of the
1093 expression (if any) is returned. Note that under Win32, system time
1093 expression (if any) is returned. Note that under Win32, system time
1094 is always reported as 0, since it can not be measured.
1094 is always reported as 0, since it can not be measured.
1095
1095
1096 This function can be used both as a line and cell magic:
1096 This function can be used both as a line and cell magic:
1097
1097
1098 - In line mode you can time a single-line statement (though multiple
1098 - In line mode you can time a single-line statement (though multiple
1099 ones can be chained with using semicolons).
1099 ones can be chained with using semicolons).
1100
1100
1101 - In cell mode, you can time the cell body (a directly
1101 - In cell mode, you can time the cell body (a directly
1102 following statement raises an error).
1102 following statement raises an error).
1103
1103
1104 This function provides very basic timing functionality. Use the timeit
1104 This function provides very basic timing functionality. Use the timeit
1105 magic for more control over the measurement.
1105 magic for more control over the measurement.
1106
1106
1107 Examples
1107 Examples
1108 --------
1108 --------
1109 ::
1109 ::
1110
1110
1111 In [1]: %time 2**128
1111 In [1]: %time 2**128
1112 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
1113 Wall time: 0.00
1113 Wall time: 0.00
1114 Out[1]: 340282366920938463463374607431768211456L
1114 Out[1]: 340282366920938463463374607431768211456L
1115
1115
1116 In [2]: n = 1000000
1116 In [2]: n = 1000000
1117
1117
1118 In [3]: %time sum(range(n))
1118 In [3]: %time sum(range(n))
1119 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1119 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1120 Wall time: 1.37
1120 Wall time: 1.37
1121 Out[3]: 499999500000L
1121 Out[3]: 499999500000L
1122
1122
1123 In [4]: %time print 'hello world'
1123 In [4]: %time print 'hello world'
1124 hello world
1124 hello world
1125 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1125 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1126 Wall time: 0.00
1126 Wall time: 0.00
1127
1127
1128 Note that the time needed by Python to compile the given expression
1128 Note that the time needed by Python to compile the given expression
1129 will be reported if it is more than 0.1s. In this example, the
1129 will be reported if it is more than 0.1s. In this example, the
1130 actual exponentiation is done by Python at compilation time, so while
1130 actual exponentiation is done by Python at compilation time, so while
1131 the expression can take a noticeable amount of time to compute, that
1131 the expression can take a noticeable amount of time to compute, that
1132 time is purely due to the compilation:
1132 time is purely due to the compilation:
1133
1133
1134 In [5]: %time 3**9999;
1134 In [5]: %time 3**9999;
1135 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1135 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1136 Wall time: 0.00 s
1136 Wall time: 0.00 s
1137
1137
1138 In [6]: %time 3**999999;
1138 In [6]: %time 3**999999;
1139 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1139 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1140 Wall time: 0.00 s
1140 Wall time: 0.00 s
1141 Compiler : 0.78 s
1141 Compiler : 0.78 s
1142 """
1142 """
1143
1143
1144 # fail immediately if the given expression can't be compiled
1144 # fail immediately if the given expression can't be compiled
1145
1145
1146 if line and cell:
1146 if line and cell:
1147 raise UsageError("Can't use statement directly after '%%time'!")
1147 raise UsageError("Can't use statement directly after '%%time'!")
1148
1148
1149 if cell:
1149 if cell:
1150 expr = self.shell.input_transformer_manager.transform_cell(cell)
1150 expr = self.shell.input_transformer_manager.transform_cell(cell)
1151 else:
1151 else:
1152 expr = self.shell.input_transformer_manager.transform_cell(line)
1152 expr = self.shell.input_transformer_manager.transform_cell(line)
1153
1153
1154 # Minimum time above which parse time will be reported
1154 # Minimum time above which parse time will be reported
1155 tp_min = 0.1
1155 tp_min = 0.1
1156
1156
1157 t0 = clock()
1157 t0 = clock()
1158 expr_ast = self.shell.compile.ast_parse(expr)
1158 expr_ast = self.shell.compile.ast_parse(expr)
1159 tp = clock()-t0
1159 tp = clock()-t0
1160
1160
1161 # Apply AST transformations
1161 # Apply AST transformations
1162 expr_ast = self.shell.transform_ast(expr_ast)
1162 expr_ast = self.shell.transform_ast(expr_ast)
1163
1163
1164 # Minimum time above which compilation time will be reported
1164 # Minimum time above which compilation time will be reported
1165 tc_min = 0.1
1165 tc_min = 0.1
1166
1166
1167 if len(expr_ast.body)==1 and isinstance(expr_ast.body[0], ast.Expr):
1167 if len(expr_ast.body)==1 and isinstance(expr_ast.body[0], ast.Expr):
1168 mode = 'eval'
1168 mode = 'eval'
1169 source = '<timed eval>'
1169 source = '<timed eval>'
1170 expr_ast = ast.Expression(expr_ast.body[0].value)
1170 expr_ast = ast.Expression(expr_ast.body[0].value)
1171 else:
1171 else:
1172 mode = 'exec'
1172 mode = 'exec'
1173 source = '<timed exec>'
1173 source = '<timed exec>'
1174 t0 = clock()
1174 t0 = clock()
1175 code = self.shell.compile(expr_ast, source, mode)
1175 code = self.shell.compile(expr_ast, source, mode)
1176 tc = clock()-t0
1176 tc = clock()-t0
1177
1177
1178 # skew measurement as little as possible
1178 # skew measurement as little as possible
1179 glob = self.shell.user_ns
1179 glob = self.shell.user_ns
1180 wtime = time.time
1180 wtime = time.time
1181 # time execution
1181 # time execution
1182 wall_st = wtime()
1182 wall_st = wtime()
1183 if mode=='eval':
1183 if mode=='eval':
1184 st = clock2()
1184 st = clock2()
1185 out = eval(code, glob, local_ns)
1185 out = eval(code, glob, local_ns)
1186 end = clock2()
1186 end = clock2()
1187 else:
1187 else:
1188 st = clock2()
1188 st = clock2()
1189 exec(code, glob, local_ns)
1189 exec(code, glob, local_ns)
1190 end = clock2()
1190 end = clock2()
1191 out = None
1191 out = None
1192 wall_end = wtime()
1192 wall_end = wtime()
1193 # Compute actual times and report
1193 # Compute actual times and report
1194 wall_time = wall_end-wall_st
1194 wall_time = wall_end-wall_st
1195 cpu_user = end[0]-st[0]
1195 cpu_user = end[0]-st[0]
1196 cpu_sys = end[1]-st[1]
1196 cpu_sys = end[1]-st[1]
1197 cpu_tot = cpu_user+cpu_sys
1197 cpu_tot = cpu_user+cpu_sys
1198 # On windows cpu_sys is always zero, so no new information to the next print
1198 # On windows cpu_sys is always zero, so no new information to the next print
1199 if sys.platform != 'win32':
1199 if sys.platform != 'win32':
1200 print("CPU times: user %s, sys: %s, total: %s" % \
1200 print("CPU times: user %s, sys: %s, total: %s" % \
1201 (_format_time(cpu_user),_format_time(cpu_sys),_format_time(cpu_tot)))
1201 (_format_time(cpu_user),_format_time(cpu_sys),_format_time(cpu_tot)))
1202 print("Wall time: %s" % _format_time(wall_time))
1202 print("Wall time: %s" % _format_time(wall_time))
1203 if tc > tc_min:
1203 if tc > tc_min:
1204 print("Compiler : %s" % _format_time(tc))
1204 print("Compiler : %s" % _format_time(tc))
1205 if tp > tp_min:
1205 if tp > tp_min:
1206 print("Parser : %s" % _format_time(tp))
1206 print("Parser : %s" % _format_time(tp))
1207 return out
1207 return out
1208
1208
1209 @skip_doctest
1209 @skip_doctest
1210 @line_magic
1210 @line_magic
1211 def macro(self, parameter_s=''):
1211 def macro(self, parameter_s=''):
1212 """Define a macro for future re-execution. It accepts ranges of history,
1212 """Define a macro for future re-execution. It accepts ranges of history,
1213 filenames or string objects.
1213 filenames or string objects.
1214
1214
1215 Usage:\\
1215 Usage:\\
1216 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
1216 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
1217
1217
1218 Options:
1218 Options:
1219
1219
1220 -r: use 'raw' input. By default, the 'processed' history is used,
1220 -r: use 'raw' input. By default, the 'processed' history is used,
1221 so that magics are loaded in their transformed version to valid
1221 so that magics are loaded in their transformed version to valid
1222 Python. If this option is given, the raw input as typed at the
1222 Python. If this option is given, the raw input as typed at the
1223 command line is used instead.
1223 command line is used instead.
1224
1224
1225 -q: quiet macro definition. By default, a tag line is printed
1225 -q: quiet macro definition. By default, a tag line is printed
1226 to indicate the macro has been created, and then the contents of
1226 to indicate the macro has been created, and then the contents of
1227 the macro are printed. If this option is given, then no printout
1227 the macro are printed. If this option is given, then no printout
1228 is produced once the macro is created.
1228 is produced once the macro is created.
1229
1229
1230 This will define a global variable called `name` which is a string
1230 This will define a global variable called `name` which is a string
1231 made of joining the slices and lines you specify (n1,n2,... numbers
1231 made of joining the slices and lines you specify (n1,n2,... numbers
1232 above) from your input history into a single string. This variable
1232 above) from your input history into a single string. This variable
1233 acts like an automatic function which re-executes those lines as if
1233 acts like an automatic function which re-executes those lines as if
1234 you had typed them. You just type 'name' at the prompt and the code
1234 you had typed them. You just type 'name' at the prompt and the code
1235 executes.
1235 executes.
1236
1236
1237 The syntax for indicating input ranges is described in %history.
1237 The syntax for indicating input ranges is described in %history.
1238
1238
1239 Note: as a 'hidden' feature, you can also use traditional python slice
1239 Note: as a 'hidden' feature, you can also use traditional python slice
1240 notation, where N:M means numbers N through M-1.
1240 notation, where N:M means numbers N through M-1.
1241
1241
1242 For example, if your history contains (print using %hist -n )::
1242 For example, if your history contains (print using %hist -n )::
1243
1243
1244 44: x=1
1244 44: x=1
1245 45: y=3
1245 45: y=3
1246 46: z=x+y
1246 46: z=x+y
1247 47: print x
1247 47: print x
1248 48: a=5
1248 48: a=5
1249 49: print 'x',x,'y',y
1249 49: print 'x',x,'y',y
1250
1250
1251 you can create a macro with lines 44 through 47 (included) and line 49
1251 you can create a macro with lines 44 through 47 (included) and line 49
1252 called my_macro with::
1252 called my_macro with::
1253
1253
1254 In [55]: %macro my_macro 44-47 49
1254 In [55]: %macro my_macro 44-47 49
1255
1255
1256 Now, typing `my_macro` (without quotes) will re-execute all this code
1256 Now, typing `my_macro` (without quotes) will re-execute all this code
1257 in one pass.
1257 in one pass.
1258
1258
1259 You don't need to give the line-numbers in order, and any given line
1259 You don't need to give the line-numbers in order, and any given line
1260 number can appear multiple times. You can assemble macros with any
1260 number can appear multiple times. You can assemble macros with any
1261 lines from your input history in any order.
1261 lines from your input history in any order.
1262
1262
1263 The macro is a simple object which holds its value in an attribute,
1263 The macro is a simple object which holds its value in an attribute,
1264 but IPython's display system checks for macros and executes them as
1264 but IPython's display system checks for macros and executes them as
1265 code instead of printing them when you type their name.
1265 code instead of printing them when you type their name.
1266
1266
1267 You can view a macro's contents by explicitly printing it with::
1267 You can view a macro's contents by explicitly printing it with::
1268
1268
1269 print macro_name
1269 print macro_name
1270
1270
1271 """
1271 """
1272 opts,args = self.parse_options(parameter_s,'rq',mode='list')
1272 opts,args = self.parse_options(parameter_s,'rq',mode='list')
1273 if not args: # List existing macros
1273 if not args: # List existing macros
1274 return sorted(k for k,v in iteritems(self.shell.user_ns) if\
1274 return sorted(k for k,v in self.shell.user_ns.items() if isinstance(v, Macro))
1275 isinstance(v, Macro))
1276 if len(args) == 1:
1275 if len(args) == 1:
1277 raise UsageError(
1276 raise UsageError(
1278 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
1277 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
1279 name, codefrom = args[0], " ".join(args[1:])
1278 name, codefrom = args[0], " ".join(args[1:])
1280
1279
1281 #print 'rng',ranges # dbg
1280 #print 'rng',ranges # dbg
1282 try:
1281 try:
1283 lines = self.shell.find_user_code(codefrom, 'r' in opts)
1282 lines = self.shell.find_user_code(codefrom, 'r' in opts)
1284 except (ValueError, TypeError) as e:
1283 except (ValueError, TypeError) as e:
1285 print(e.args[0])
1284 print(e.args[0])
1286 return
1285 return
1287 macro = Macro(lines)
1286 macro = Macro(lines)
1288 self.shell.define_macro(name, macro)
1287 self.shell.define_macro(name, macro)
1289 if not ( 'q' in opts) :
1288 if not ( 'q' in opts) :
1290 print('Macro `%s` created. To execute, type its name (without quotes).' % name)
1289 print('Macro `%s` created. To execute, type its name (without quotes).' % name)
1291 print('=== Macro contents: ===')
1290 print('=== Macro contents: ===')
1292 print(macro, end=' ')
1291 print(macro, end=' ')
1293
1292
1294 @magic_arguments.magic_arguments()
1293 @magic_arguments.magic_arguments()
1295 @magic_arguments.argument('output', type=str, default='', nargs='?',
1294 @magic_arguments.argument('output', type=str, default='', nargs='?',
1296 help="""The name of the variable in which to store output.
1295 help="""The name of the variable in which to store output.
1297 This is a utils.io.CapturedIO object with stdout/err attributes
1296 This is a utils.io.CapturedIO object with stdout/err attributes
1298 for the text of the captured output.
1297 for the text of the captured output.
1299
1298
1300 CapturedOutput also has a show() method for displaying the output,
1299 CapturedOutput also has a show() method for displaying the output,
1301 and __call__ as well, so you can use that to quickly display the
1300 and __call__ as well, so you can use that to quickly display the
1302 output.
1301 output.
1303
1302
1304 If unspecified, captured output is discarded.
1303 If unspecified, captured output is discarded.
1305 """
1304 """
1306 )
1305 )
1307 @magic_arguments.argument('--no-stderr', action="store_true",
1306 @magic_arguments.argument('--no-stderr', action="store_true",
1308 help="""Don't capture stderr."""
1307 help="""Don't capture stderr."""
1309 )
1308 )
1310 @magic_arguments.argument('--no-stdout', action="store_true",
1309 @magic_arguments.argument('--no-stdout', action="store_true",
1311 help="""Don't capture stdout."""
1310 help="""Don't capture stdout."""
1312 )
1311 )
1313 @magic_arguments.argument('--no-display', action="store_true",
1312 @magic_arguments.argument('--no-display', action="store_true",
1314 help="""Don't capture IPython's rich display."""
1313 help="""Don't capture IPython's rich display."""
1315 )
1314 )
1316 @cell_magic
1315 @cell_magic
1317 def capture(self, line, cell):
1316 def capture(self, line, cell):
1318 """run the cell, capturing stdout, stderr, and IPython's rich display() calls."""
1317 """run the cell, capturing stdout, stderr, and IPython's rich display() calls."""
1319 args = magic_arguments.parse_argstring(self.capture, line)
1318 args = magic_arguments.parse_argstring(self.capture, line)
1320 out = not args.no_stdout
1319 out = not args.no_stdout
1321 err = not args.no_stderr
1320 err = not args.no_stderr
1322 disp = not args.no_display
1321 disp = not args.no_display
1323 with capture_output(out, err, disp) as io:
1322 with capture_output(out, err, disp) as io:
1324 self.shell.run_cell(cell)
1323 self.shell.run_cell(cell)
1325 if args.output:
1324 if args.output:
1326 self.shell.user_ns[args.output] = io
1325 self.shell.user_ns[args.output] = io
1327
1326
1328 def parse_breakpoint(text, current_file):
1327 def parse_breakpoint(text, current_file):
1329 '''Returns (file, line) for file:line and (current_file, line) for line'''
1328 '''Returns (file, line) for file:line and (current_file, line) for line'''
1330 colon = text.find(':')
1329 colon = text.find(':')
1331 if colon == -1:
1330 if colon == -1:
1332 return current_file, int(text)
1331 return current_file, int(text)
1333 else:
1332 else:
1334 return text[:colon], int(text[colon+1:])
1333 return text[:colon], int(text[colon+1:])
1335
1334
1336 def _format_time(timespan, precision=3):
1335 def _format_time(timespan, precision=3):
1337 """Formats the timespan in a human readable form"""
1336 """Formats the timespan in a human readable form"""
1338
1337
1339 if timespan >= 60.0:
1338 if timespan >= 60.0:
1340 # we have more than a minute, format that in a human readable form
1339 # we have more than a minute, format that in a human readable form
1341 # Idea from http://snipplr.com/view/5713/
1340 # Idea from http://snipplr.com/view/5713/
1342 parts = [("d", 60*60*24),("h", 60*60),("min", 60), ("s", 1)]
1341 parts = [("d", 60*60*24),("h", 60*60),("min", 60), ("s", 1)]
1343 time = []
1342 time = []
1344 leftover = timespan
1343 leftover = timespan
1345 for suffix, length in parts:
1344 for suffix, length in parts:
1346 value = int(leftover / length)
1345 value = int(leftover / length)
1347 if value > 0:
1346 if value > 0:
1348 leftover = leftover % length
1347 leftover = leftover % length
1349 time.append(u'%s%s' % (str(value), suffix))
1348 time.append(u'%s%s' % (str(value), suffix))
1350 if leftover < 1:
1349 if leftover < 1:
1351 break
1350 break
1352 return " ".join(time)
1351 return " ".join(time)
1353
1352
1354
1353
1355 # Unfortunately the unicode 'micro' symbol can cause problems in
1354 # Unfortunately the unicode 'micro' symbol can cause problems in
1356 # certain terminals.
1355 # certain terminals.
1357 # See bug: https://bugs.launchpad.net/ipython/+bug/348466
1356 # See bug: https://bugs.launchpad.net/ipython/+bug/348466
1358 # Try to prevent crashes by being more secure than it needs to
1357 # Try to prevent crashes by being more secure than it needs to
1359 # E.g. eclipse is able to print a Β΅, but has no sys.stdout.encoding set.
1358 # E.g. eclipse is able to print a Β΅, but has no sys.stdout.encoding set.
1360 units = [u"s", u"ms",u'us',"ns"] # the save value
1359 units = [u"s", u"ms",u'us',"ns"] # the save value
1361 if hasattr(sys.stdout, 'encoding') and sys.stdout.encoding:
1360 if hasattr(sys.stdout, 'encoding') and sys.stdout.encoding:
1362 try:
1361 try:
1363 u'\xb5'.encode(sys.stdout.encoding)
1362 u'\xb5'.encode(sys.stdout.encoding)
1364 units = [u"s", u"ms",u'\xb5s',"ns"]
1363 units = [u"s", u"ms",u'\xb5s',"ns"]
1365 except:
1364 except:
1366 pass
1365 pass
1367 scaling = [1, 1e3, 1e6, 1e9]
1366 scaling = [1, 1e3, 1e6, 1e9]
1368
1367
1369 if timespan > 0.0:
1368 if timespan > 0.0:
1370 order = min(-int(math.floor(math.log10(timespan)) // 3), 3)
1369 order = min(-int(math.floor(math.log10(timespan)) // 3), 3)
1371 else:
1370 else:
1372 order = 3
1371 order = 3
1373 return u"%.*g %s" % (precision, timespan * scaling[order], units[order])
1372 return u"%.*g %s" % (precision, timespan * scaling[order], units[order])
@@ -1,867 +1,866 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """
2 """
3 Python advanced pretty printer. This pretty printer is intended to
3 Python advanced pretty printer. This pretty printer is intended to
4 replace the old `pprint` python module which does not allow developers
4 replace the old `pprint` python module which does not allow developers
5 to provide their own pretty print callbacks.
5 to provide their own pretty print callbacks.
6
6
7 This module is based on ruby's `prettyprint.rb` library by `Tanaka Akira`.
7 This module is based on ruby's `prettyprint.rb` library by `Tanaka Akira`.
8
8
9
9
10 Example Usage
10 Example Usage
11 -------------
11 -------------
12
12
13 To directly print the representation of an object use `pprint`::
13 To directly print the representation of an object use `pprint`::
14
14
15 from pretty import pprint
15 from pretty import pprint
16 pprint(complex_object)
16 pprint(complex_object)
17
17
18 To get a string of the output use `pretty`::
18 To get a string of the output use `pretty`::
19
19
20 from pretty import pretty
20 from pretty import pretty
21 string = pretty(complex_object)
21 string = pretty(complex_object)
22
22
23
23
24 Extending
24 Extending
25 ---------
25 ---------
26
26
27 The pretty library allows developers to add pretty printing rules for their
27 The pretty library allows developers to add pretty printing rules for their
28 own objects. This process is straightforward. All you have to do is to
28 own objects. This process is straightforward. All you have to do is to
29 add a `_repr_pretty_` method to your object and call the methods on the
29 add a `_repr_pretty_` method to your object and call the methods on the
30 pretty printer passed::
30 pretty printer passed::
31
31
32 class MyObject(object):
32 class MyObject(object):
33
33
34 def _repr_pretty_(self, p, cycle):
34 def _repr_pretty_(self, p, cycle):
35 ...
35 ...
36
36
37 Here is an example implementation of a `_repr_pretty_` method for a list
37 Here is an example implementation of a `_repr_pretty_` method for a list
38 subclass::
38 subclass::
39
39
40 class MyList(list):
40 class MyList(list):
41
41
42 def _repr_pretty_(self, p, cycle):
42 def _repr_pretty_(self, p, cycle):
43 if cycle:
43 if cycle:
44 p.text('MyList(...)')
44 p.text('MyList(...)')
45 else:
45 else:
46 with p.group(8, 'MyList([', '])'):
46 with p.group(8, 'MyList([', '])'):
47 for idx, item in enumerate(self):
47 for idx, item in enumerate(self):
48 if idx:
48 if idx:
49 p.text(',')
49 p.text(',')
50 p.breakable()
50 p.breakable()
51 p.pretty(item)
51 p.pretty(item)
52
52
53 The `cycle` parameter is `True` if pretty detected a cycle. You *have* to
53 The `cycle` parameter is `True` if pretty detected a cycle. You *have* to
54 react to that or the result is an infinite loop. `p.text()` just adds
54 react to that or the result is an infinite loop. `p.text()` just adds
55 non breaking text to the output, `p.breakable()` either adds a whitespace
55 non breaking text to the output, `p.breakable()` either adds a whitespace
56 or breaks here. If you pass it an argument it's used instead of the
56 or breaks here. If you pass it an argument it's used instead of the
57 default space. `p.pretty` prettyprints another object using the pretty print
57 default space. `p.pretty` prettyprints another object using the pretty print
58 method.
58 method.
59
59
60 The first parameter to the `group` function specifies the extra indentation
60 The first parameter to the `group` function specifies the extra indentation
61 of the next line. In this example the next item will either be on the same
61 of the next line. In this example the next item will either be on the same
62 line (if the items are short enough) or aligned with the right edge of the
62 line (if the items are short enough) or aligned with the right edge of the
63 opening bracket of `MyList`.
63 opening bracket of `MyList`.
64
64
65 If you just want to indent something you can use the group function
65 If you just want to indent something you can use the group function
66 without open / close parameters. You can also use this code::
66 without open / close parameters. You can also use this code::
67
67
68 with p.indent(2):
68 with p.indent(2):
69 ...
69 ...
70
70
71 Inheritance diagram:
71 Inheritance diagram:
72
72
73 .. inheritance-diagram:: IPython.lib.pretty
73 .. inheritance-diagram:: IPython.lib.pretty
74 :parts: 3
74 :parts: 3
75
75
76 :copyright: 2007 by Armin Ronacher.
76 :copyright: 2007 by Armin Ronacher.
77 Portions (c) 2009 by Robert Kern.
77 Portions (c) 2009 by Robert Kern.
78 :license: BSD License.
78 :license: BSD License.
79 """
79 """
80 from contextlib import contextmanager
80 from contextlib import contextmanager
81 import sys
81 import sys
82 import types
82 import types
83 import re
83 import re
84 import datetime
84 import datetime
85 from collections import deque
85 from collections import deque
86
86
87 from IPython.utils.py3compat import PY3, PYPY, cast_unicode, string_types
87 from IPython.utils.py3compat import PY3, PYPY, cast_unicode, string_types
88 from IPython.utils.encoding import get_stream_enc
88 from IPython.utils.encoding import get_stream_enc
89
89
90 from io import StringIO
90 from io import StringIO
91
91
92
92
93 __all__ = ['pretty', 'pprint', 'PrettyPrinter', 'RepresentationPrinter',
93 __all__ = ['pretty', 'pprint', 'PrettyPrinter', 'RepresentationPrinter',
94 'for_type', 'for_type_by_name']
94 'for_type', 'for_type_by_name']
95
95
96
96
97 MAX_SEQ_LENGTH = 1000
97 MAX_SEQ_LENGTH = 1000
98 _re_pattern_type = type(re.compile(''))
98 _re_pattern_type = type(re.compile(''))
99
99
100 def _safe_getattr(obj, attr, default=None):
100 def _safe_getattr(obj, attr, default=None):
101 """Safe version of getattr.
101 """Safe version of getattr.
102
102
103 Same as getattr, but will return ``default`` on any Exception,
103 Same as getattr, but will return ``default`` on any Exception,
104 rather than raising.
104 rather than raising.
105 """
105 """
106 try:
106 try:
107 return getattr(obj, attr, default)
107 return getattr(obj, attr, default)
108 except Exception:
108 except Exception:
109 return default
109 return default
110
110
111 if PY3:
111 if PY3:
112 CUnicodeIO = StringIO
112 CUnicodeIO = StringIO
113 else:
113 else:
114 class CUnicodeIO(StringIO):
114 class CUnicodeIO(StringIO):
115 """StringIO that casts str to unicode on Python 2"""
115 """StringIO that casts str to unicode on Python 2"""
116 def write(self, text):
116 def write(self, text):
117 return super(CUnicodeIO, self).write(
117 return super(CUnicodeIO, self).write(
118 cast_unicode(text, encoding=get_stream_enc(sys.stdout)))
118 cast_unicode(text, encoding=get_stream_enc(sys.stdout)))
119
119
120
120
121 def pretty(obj, verbose=False, max_width=79, newline='\n', max_seq_length=MAX_SEQ_LENGTH):
121 def pretty(obj, verbose=False, max_width=79, newline='\n', max_seq_length=MAX_SEQ_LENGTH):
122 """
122 """
123 Pretty print the object's representation.
123 Pretty print the object's representation.
124 """
124 """
125 stream = CUnicodeIO()
125 stream = CUnicodeIO()
126 printer = RepresentationPrinter(stream, verbose, max_width, newline, max_seq_length=max_seq_length)
126 printer = RepresentationPrinter(stream, verbose, max_width, newline, max_seq_length=max_seq_length)
127 printer.pretty(obj)
127 printer.pretty(obj)
128 printer.flush()
128 printer.flush()
129 return stream.getvalue()
129 return stream.getvalue()
130
130
131
131
132 def pprint(obj, verbose=False, max_width=79, newline='\n', max_seq_length=MAX_SEQ_LENGTH):
132 def pprint(obj, verbose=False, max_width=79, newline='\n', max_seq_length=MAX_SEQ_LENGTH):
133 """
133 """
134 Like `pretty` but print to stdout.
134 Like `pretty` but print to stdout.
135 """
135 """
136 printer = RepresentationPrinter(sys.stdout, verbose, max_width, newline, max_seq_length=max_seq_length)
136 printer = RepresentationPrinter(sys.stdout, verbose, max_width, newline, max_seq_length=max_seq_length)
137 printer.pretty(obj)
137 printer.pretty(obj)
138 printer.flush()
138 printer.flush()
139 sys.stdout.write(newline)
139 sys.stdout.write(newline)
140 sys.stdout.flush()
140 sys.stdout.flush()
141
141
142 class _PrettyPrinterBase(object):
142 class _PrettyPrinterBase(object):
143
143
144 @contextmanager
144 @contextmanager
145 def indent(self, indent):
145 def indent(self, indent):
146 """with statement support for indenting/dedenting."""
146 """with statement support for indenting/dedenting."""
147 self.indentation += indent
147 self.indentation += indent
148 try:
148 try:
149 yield
149 yield
150 finally:
150 finally:
151 self.indentation -= indent
151 self.indentation -= indent
152
152
153 @contextmanager
153 @contextmanager
154 def group(self, indent=0, open='', close=''):
154 def group(self, indent=0, open='', close=''):
155 """like begin_group / end_group but for the with statement."""
155 """like begin_group / end_group but for the with statement."""
156 self.begin_group(indent, open)
156 self.begin_group(indent, open)
157 try:
157 try:
158 yield
158 yield
159 finally:
159 finally:
160 self.end_group(indent, close)
160 self.end_group(indent, close)
161
161
162 class PrettyPrinter(_PrettyPrinterBase):
162 class PrettyPrinter(_PrettyPrinterBase):
163 """
163 """
164 Baseclass for the `RepresentationPrinter` prettyprinter that is used to
164 Baseclass for the `RepresentationPrinter` prettyprinter that is used to
165 generate pretty reprs of objects. Contrary to the `RepresentationPrinter`
165 generate pretty reprs of objects. Contrary to the `RepresentationPrinter`
166 this printer knows nothing about the default pprinters or the `_repr_pretty_`
166 this printer knows nothing about the default pprinters or the `_repr_pretty_`
167 callback method.
167 callback method.
168 """
168 """
169
169
170 def __init__(self, output, max_width=79, newline='\n', max_seq_length=MAX_SEQ_LENGTH):
170 def __init__(self, output, max_width=79, newline='\n', max_seq_length=MAX_SEQ_LENGTH):
171 self.output = output
171 self.output = output
172 self.max_width = max_width
172 self.max_width = max_width
173 self.newline = newline
173 self.newline = newline
174 self.max_seq_length = max_seq_length
174 self.max_seq_length = max_seq_length
175 self.output_width = 0
175 self.output_width = 0
176 self.buffer_width = 0
176 self.buffer_width = 0
177 self.buffer = deque()
177 self.buffer = deque()
178
178
179 root_group = Group(0)
179 root_group = Group(0)
180 self.group_stack = [root_group]
180 self.group_stack = [root_group]
181 self.group_queue = GroupQueue(root_group)
181 self.group_queue = GroupQueue(root_group)
182 self.indentation = 0
182 self.indentation = 0
183
183
184 def _break_outer_groups(self):
184 def _break_outer_groups(self):
185 while self.max_width < self.output_width + self.buffer_width:
185 while self.max_width < self.output_width + self.buffer_width:
186 group = self.group_queue.deq()
186 group = self.group_queue.deq()
187 if not group:
187 if not group:
188 return
188 return
189 while group.breakables:
189 while group.breakables:
190 x = self.buffer.popleft()
190 x = self.buffer.popleft()
191 self.output_width = x.output(self.output, self.output_width)
191 self.output_width = x.output(self.output, self.output_width)
192 self.buffer_width -= x.width
192 self.buffer_width -= x.width
193 while self.buffer and isinstance(self.buffer[0], Text):
193 while self.buffer and isinstance(self.buffer[0], Text):
194 x = self.buffer.popleft()
194 x = self.buffer.popleft()
195 self.output_width = x.output(self.output, self.output_width)
195 self.output_width = x.output(self.output, self.output_width)
196 self.buffer_width -= x.width
196 self.buffer_width -= x.width
197
197
198 def text(self, obj):
198 def text(self, obj):
199 """Add literal text to the output."""
199 """Add literal text to the output."""
200 width = len(obj)
200 width = len(obj)
201 if self.buffer:
201 if self.buffer:
202 text = self.buffer[-1]
202 text = self.buffer[-1]
203 if not isinstance(text, Text):
203 if not isinstance(text, Text):
204 text = Text()
204 text = Text()
205 self.buffer.append(text)
205 self.buffer.append(text)
206 text.add(obj, width)
206 text.add(obj, width)
207 self.buffer_width += width
207 self.buffer_width += width
208 self._break_outer_groups()
208 self._break_outer_groups()
209 else:
209 else:
210 self.output.write(obj)
210 self.output.write(obj)
211 self.output_width += width
211 self.output_width += width
212
212
213 def breakable(self, sep=' '):
213 def breakable(self, sep=' '):
214 """
214 """
215 Add a breakable separator to the output. This does not mean that it
215 Add a breakable separator to the output. This does not mean that it
216 will automatically break here. If no breaking on this position takes
216 will automatically break here. If no breaking on this position takes
217 place the `sep` is inserted which default to one space.
217 place the `sep` is inserted which default to one space.
218 """
218 """
219 width = len(sep)
219 width = len(sep)
220 group = self.group_stack[-1]
220 group = self.group_stack[-1]
221 if group.want_break:
221 if group.want_break:
222 self.flush()
222 self.flush()
223 self.output.write(self.newline)
223 self.output.write(self.newline)
224 self.output.write(' ' * self.indentation)
224 self.output.write(' ' * self.indentation)
225 self.output_width = self.indentation
225 self.output_width = self.indentation
226 self.buffer_width = 0
226 self.buffer_width = 0
227 else:
227 else:
228 self.buffer.append(Breakable(sep, width, self))
228 self.buffer.append(Breakable(sep, width, self))
229 self.buffer_width += width
229 self.buffer_width += width
230 self._break_outer_groups()
230 self._break_outer_groups()
231
231
232 def break_(self):
232 def break_(self):
233 """
233 """
234 Explicitly insert a newline into the output, maintaining correct indentation.
234 Explicitly insert a newline into the output, maintaining correct indentation.
235 """
235 """
236 self.flush()
236 self.flush()
237 self.output.write(self.newline)
237 self.output.write(self.newline)
238 self.output.write(' ' * self.indentation)
238 self.output.write(' ' * self.indentation)
239 self.output_width = self.indentation
239 self.output_width = self.indentation
240 self.buffer_width = 0
240 self.buffer_width = 0
241
241
242
242
243 def begin_group(self, indent=0, open=''):
243 def begin_group(self, indent=0, open=''):
244 """
244 """
245 Begin a group. If you want support for python < 2.5 which doesn't has
245 Begin a group. If you want support for python < 2.5 which doesn't has
246 the with statement this is the preferred way:
246 the with statement this is the preferred way:
247
247
248 p.begin_group(1, '{')
248 p.begin_group(1, '{')
249 ...
249 ...
250 p.end_group(1, '}')
250 p.end_group(1, '}')
251
251
252 The python 2.5 expression would be this:
252 The python 2.5 expression would be this:
253
253
254 with p.group(1, '{', '}'):
254 with p.group(1, '{', '}'):
255 ...
255 ...
256
256
257 The first parameter specifies the indentation for the next line (usually
257 The first parameter specifies the indentation for the next line (usually
258 the width of the opening text), the second the opening text. All
258 the width of the opening text), the second the opening text. All
259 parameters are optional.
259 parameters are optional.
260 """
260 """
261 if open:
261 if open:
262 self.text(open)
262 self.text(open)
263 group = Group(self.group_stack[-1].depth + 1)
263 group = Group(self.group_stack[-1].depth + 1)
264 self.group_stack.append(group)
264 self.group_stack.append(group)
265 self.group_queue.enq(group)
265 self.group_queue.enq(group)
266 self.indentation += indent
266 self.indentation += indent
267
267
268 def _enumerate(self, seq):
268 def _enumerate(self, seq):
269 """like enumerate, but with an upper limit on the number of items"""
269 """like enumerate, but with an upper limit on the number of items"""
270 for idx, x in enumerate(seq):
270 for idx, x in enumerate(seq):
271 if self.max_seq_length and idx >= self.max_seq_length:
271 if self.max_seq_length and idx >= self.max_seq_length:
272 self.text(',')
272 self.text(',')
273 self.breakable()
273 self.breakable()
274 self.text('...')
274 self.text('...')
275 return
275 return
276 yield idx, x
276 yield idx, x
277
277
278 def end_group(self, dedent=0, close=''):
278 def end_group(self, dedent=0, close=''):
279 """End a group. See `begin_group` for more details."""
279 """End a group. See `begin_group` for more details."""
280 self.indentation -= dedent
280 self.indentation -= dedent
281 group = self.group_stack.pop()
281 group = self.group_stack.pop()
282 if not group.breakables:
282 if not group.breakables:
283 self.group_queue.remove(group)
283 self.group_queue.remove(group)
284 if close:
284 if close:
285 self.text(close)
285 self.text(close)
286
286
287 def flush(self):
287 def flush(self):
288 """Flush data that is left in the buffer."""
288 """Flush data that is left in the buffer."""
289 for data in self.buffer:
289 for data in self.buffer:
290 self.output_width += data.output(self.output, self.output_width)
290 self.output_width += data.output(self.output, self.output_width)
291 self.buffer.clear()
291 self.buffer.clear()
292 self.buffer_width = 0
292 self.buffer_width = 0
293
293
294
294
295 def _get_mro(obj_class):
295 def _get_mro(obj_class):
296 """ Get a reasonable method resolution order of a class and its superclasses
296 """ Get a reasonable method resolution order of a class and its superclasses
297 for both old-style and new-style classes.
297 for both old-style and new-style classes.
298 """
298 """
299 if not hasattr(obj_class, '__mro__'):
299 if not hasattr(obj_class, '__mro__'):
300 # Old-style class. Mix in object to make a fake new-style class.
300 # Old-style class. Mix in object to make a fake new-style class.
301 try:
301 try:
302 obj_class = type(obj_class.__name__, (obj_class, object), {})
302 obj_class = type(obj_class.__name__, (obj_class, object), {})
303 except TypeError:
303 except TypeError:
304 # Old-style extension type that does not descend from object.
304 # Old-style extension type that does not descend from object.
305 # FIXME: try to construct a more thorough MRO.
305 # FIXME: try to construct a more thorough MRO.
306 mro = [obj_class]
306 mro = [obj_class]
307 else:
307 else:
308 mro = obj_class.__mro__[1:-1]
308 mro = obj_class.__mro__[1:-1]
309 else:
309 else:
310 mro = obj_class.__mro__
310 mro = obj_class.__mro__
311 return mro
311 return mro
312
312
313
313
314 class RepresentationPrinter(PrettyPrinter):
314 class RepresentationPrinter(PrettyPrinter):
315 """
315 """
316 Special pretty printer that has a `pretty` method that calls the pretty
316 Special pretty printer that has a `pretty` method that calls the pretty
317 printer for a python object.
317 printer for a python object.
318
318
319 This class stores processing data on `self` so you must *never* use
319 This class stores processing data on `self` so you must *never* use
320 this class in a threaded environment. Always lock it or reinstanciate
320 this class in a threaded environment. Always lock it or reinstanciate
321 it.
321 it.
322
322
323 Instances also have a verbose flag callbacks can access to control their
323 Instances also have a verbose flag callbacks can access to control their
324 output. For example the default instance repr prints all attributes and
324 output. For example the default instance repr prints all attributes and
325 methods that are not prefixed by an underscore if the printer is in
325 methods that are not prefixed by an underscore if the printer is in
326 verbose mode.
326 verbose mode.
327 """
327 """
328
328
329 def __init__(self, output, verbose=False, max_width=79, newline='\n',
329 def __init__(self, output, verbose=False, max_width=79, newline='\n',
330 singleton_pprinters=None, type_pprinters=None, deferred_pprinters=None,
330 singleton_pprinters=None, type_pprinters=None, deferred_pprinters=None,
331 max_seq_length=MAX_SEQ_LENGTH):
331 max_seq_length=MAX_SEQ_LENGTH):
332
332
333 PrettyPrinter.__init__(self, output, max_width, newline, max_seq_length=max_seq_length)
333 PrettyPrinter.__init__(self, output, max_width, newline, max_seq_length=max_seq_length)
334 self.verbose = verbose
334 self.verbose = verbose
335 self.stack = []
335 self.stack = []
336 if singleton_pprinters is None:
336 if singleton_pprinters is None:
337 singleton_pprinters = _singleton_pprinters.copy()
337 singleton_pprinters = _singleton_pprinters.copy()
338 self.singleton_pprinters = singleton_pprinters
338 self.singleton_pprinters = singleton_pprinters
339 if type_pprinters is None:
339 if type_pprinters is None:
340 type_pprinters = _type_pprinters.copy()
340 type_pprinters = _type_pprinters.copy()
341 self.type_pprinters = type_pprinters
341 self.type_pprinters = type_pprinters
342 if deferred_pprinters is None:
342 if deferred_pprinters is None:
343 deferred_pprinters = _deferred_type_pprinters.copy()
343 deferred_pprinters = _deferred_type_pprinters.copy()
344 self.deferred_pprinters = deferred_pprinters
344 self.deferred_pprinters = deferred_pprinters
345
345
346 def pretty(self, obj):
346 def pretty(self, obj):
347 """Pretty print the given object."""
347 """Pretty print the given object."""
348 obj_id = id(obj)
348 obj_id = id(obj)
349 cycle = obj_id in self.stack
349 cycle = obj_id in self.stack
350 self.stack.append(obj_id)
350 self.stack.append(obj_id)
351 self.begin_group()
351 self.begin_group()
352 try:
352 try:
353 obj_class = _safe_getattr(obj, '__class__', None) or type(obj)
353 obj_class = _safe_getattr(obj, '__class__', None) or type(obj)
354 # First try to find registered singleton printers for the type.
354 # First try to find registered singleton printers for the type.
355 try:
355 try:
356 printer = self.singleton_pprinters[obj_id]
356 printer = self.singleton_pprinters[obj_id]
357 except (TypeError, KeyError):
357 except (TypeError, KeyError):
358 pass
358 pass
359 else:
359 else:
360 return printer(obj, self, cycle)
360 return printer(obj, self, cycle)
361 # Next walk the mro and check for either:
361 # Next walk the mro and check for either:
362 # 1) a registered printer
362 # 1) a registered printer
363 # 2) a _repr_pretty_ method
363 # 2) a _repr_pretty_ method
364 for cls in _get_mro(obj_class):
364 for cls in _get_mro(obj_class):
365 if cls in self.type_pprinters:
365 if cls in self.type_pprinters:
366 # printer registered in self.type_pprinters
366 # printer registered in self.type_pprinters
367 return self.type_pprinters[cls](obj, self, cycle)
367 return self.type_pprinters[cls](obj, self, cycle)
368 else:
368 else:
369 # deferred printer
369 # deferred printer
370 printer = self._in_deferred_types(cls)
370 printer = self._in_deferred_types(cls)
371 if printer is not None:
371 if printer is not None:
372 return printer(obj, self, cycle)
372 return printer(obj, self, cycle)
373 else:
373 else:
374 # Finally look for special method names.
374 # Finally look for special method names.
375 # Some objects automatically create any requested
375 # Some objects automatically create any requested
376 # attribute. Try to ignore most of them by checking for
376 # attribute. Try to ignore most of them by checking for
377 # callability.
377 # callability.
378 if '_repr_pretty_' in cls.__dict__:
378 if '_repr_pretty_' in cls.__dict__:
379 meth = cls._repr_pretty_
379 meth = cls._repr_pretty_
380 if callable(meth):
380 if callable(meth):
381 return meth(obj, self, cycle)
381 return meth(obj, self, cycle)
382 return _default_pprint(obj, self, cycle)
382 return _default_pprint(obj, self, cycle)
383 finally:
383 finally:
384 self.end_group()
384 self.end_group()
385 self.stack.pop()
385 self.stack.pop()
386
386
387 def _in_deferred_types(self, cls):
387 def _in_deferred_types(self, cls):
388 """
388 """
389 Check if the given class is specified in the deferred type registry.
389 Check if the given class is specified in the deferred type registry.
390
390
391 Returns the printer from the registry if it exists, and None if the
391 Returns the printer from the registry if it exists, and None if the
392 class is not in the registry. Successful matches will be moved to the
392 class is not in the registry. Successful matches will be moved to the
393 regular type registry for future use.
393 regular type registry for future use.
394 """
394 """
395 mod = _safe_getattr(cls, '__module__', None)
395 mod = _safe_getattr(cls, '__module__', None)
396 name = _safe_getattr(cls, '__name__', None)
396 name = _safe_getattr(cls, '__name__', None)
397 key = (mod, name)
397 key = (mod, name)
398 printer = None
398 printer = None
399 if key in self.deferred_pprinters:
399 if key in self.deferred_pprinters:
400 # Move the printer over to the regular registry.
400 # Move the printer over to the regular registry.
401 printer = self.deferred_pprinters.pop(key)
401 printer = self.deferred_pprinters.pop(key)
402 self.type_pprinters[cls] = printer
402 self.type_pprinters[cls] = printer
403 return printer
403 return printer
404
404
405
405
406 class Printable(object):
406 class Printable(object):
407
407
408 def output(self, stream, output_width):
408 def output(self, stream, output_width):
409 return output_width
409 return output_width
410
410
411
411
412 class Text(Printable):
412 class Text(Printable):
413
413
414 def __init__(self):
414 def __init__(self):
415 self.objs = []
415 self.objs = []
416 self.width = 0
416 self.width = 0
417
417
418 def output(self, stream, output_width):
418 def output(self, stream, output_width):
419 for obj in self.objs:
419 for obj in self.objs:
420 stream.write(obj)
420 stream.write(obj)
421 return output_width + self.width
421 return output_width + self.width
422
422
423 def add(self, obj, width):
423 def add(self, obj, width):
424 self.objs.append(obj)
424 self.objs.append(obj)
425 self.width += width
425 self.width += width
426
426
427
427
428 class Breakable(Printable):
428 class Breakable(Printable):
429
429
430 def __init__(self, seq, width, pretty):
430 def __init__(self, seq, width, pretty):
431 self.obj = seq
431 self.obj = seq
432 self.width = width
432 self.width = width
433 self.pretty = pretty
433 self.pretty = pretty
434 self.indentation = pretty.indentation
434 self.indentation = pretty.indentation
435 self.group = pretty.group_stack[-1]
435 self.group = pretty.group_stack[-1]
436 self.group.breakables.append(self)
436 self.group.breakables.append(self)
437
437
438 def output(self, stream, output_width):
438 def output(self, stream, output_width):
439 self.group.breakables.popleft()
439 self.group.breakables.popleft()
440 if self.group.want_break:
440 if self.group.want_break:
441 stream.write(self.pretty.newline)
441 stream.write(self.pretty.newline)
442 stream.write(' ' * self.indentation)
442 stream.write(' ' * self.indentation)
443 return self.indentation
443 return self.indentation
444 if not self.group.breakables:
444 if not self.group.breakables:
445 self.pretty.group_queue.remove(self.group)
445 self.pretty.group_queue.remove(self.group)
446 stream.write(self.obj)
446 stream.write(self.obj)
447 return output_width + self.width
447 return output_width + self.width
448
448
449
449
450 class Group(Printable):
450 class Group(Printable):
451
451
452 def __init__(self, depth):
452 def __init__(self, depth):
453 self.depth = depth
453 self.depth = depth
454 self.breakables = deque()
454 self.breakables = deque()
455 self.want_break = False
455 self.want_break = False
456
456
457
457
458 class GroupQueue(object):
458 class GroupQueue(object):
459
459
460 def __init__(self, *groups):
460 def __init__(self, *groups):
461 self.queue = []
461 self.queue = []
462 for group in groups:
462 for group in groups:
463 self.enq(group)
463 self.enq(group)
464
464
465 def enq(self, group):
465 def enq(self, group):
466 depth = group.depth
466 depth = group.depth
467 while depth > len(self.queue) - 1:
467 while depth > len(self.queue) - 1:
468 self.queue.append([])
468 self.queue.append([])
469 self.queue[depth].append(group)
469 self.queue[depth].append(group)
470
470
471 def deq(self):
471 def deq(self):
472 for stack in self.queue:
472 for stack in self.queue:
473 for idx, group in enumerate(reversed(stack)):
473 for idx, group in enumerate(reversed(stack)):
474 if group.breakables:
474 if group.breakables:
475 del stack[idx]
475 del stack[idx]
476 group.want_break = True
476 group.want_break = True
477 return group
477 return group
478 for group in stack:
478 for group in stack:
479 group.want_break = True
479 group.want_break = True
480 del stack[:]
480 del stack[:]
481
481
482 def remove(self, group):
482 def remove(self, group):
483 try:
483 try:
484 self.queue[group.depth].remove(group)
484 self.queue[group.depth].remove(group)
485 except ValueError:
485 except ValueError:
486 pass
486 pass
487
487
488 try:
488 try:
489 _baseclass_reprs = (object.__repr__, types.InstanceType.__repr__)
489 _baseclass_reprs = (object.__repr__, types.InstanceType.__repr__)
490 except AttributeError: # Python 3
490 except AttributeError: # Python 3
491 _baseclass_reprs = (object.__repr__,)
491 _baseclass_reprs = (object.__repr__,)
492
492
493
493
494 def _default_pprint(obj, p, cycle):
494 def _default_pprint(obj, p, cycle):
495 """
495 """
496 The default print function. Used if an object does not provide one and
496 The default print function. Used if an object does not provide one and
497 it's none of the builtin objects.
497 it's none of the builtin objects.
498 """
498 """
499 klass = _safe_getattr(obj, '__class__', None) or type(obj)
499 klass = _safe_getattr(obj, '__class__', None) or type(obj)
500 if _safe_getattr(klass, '__repr__', None) not in _baseclass_reprs:
500 if _safe_getattr(klass, '__repr__', None) not in _baseclass_reprs:
501 # A user-provided repr. Find newlines and replace them with p.break_()
501 # A user-provided repr. Find newlines and replace them with p.break_()
502 _repr_pprint(obj, p, cycle)
502 _repr_pprint(obj, p, cycle)
503 return
503 return
504 p.begin_group(1, '<')
504 p.begin_group(1, '<')
505 p.pretty(klass)
505 p.pretty(klass)
506 p.text(' at 0x%x' % id(obj))
506 p.text(' at 0x%x' % id(obj))
507 if cycle:
507 if cycle:
508 p.text(' ...')
508 p.text(' ...')
509 elif p.verbose:
509 elif p.verbose:
510 first = True
510 first = True
511 for key in dir(obj):
511 for key in dir(obj):
512 if not key.startswith('_'):
512 if not key.startswith('_'):
513 try:
513 try:
514 value = getattr(obj, key)
514 value = getattr(obj, key)
515 except AttributeError:
515 except AttributeError:
516 continue
516 continue
517 if isinstance(value, types.MethodType):
517 if isinstance(value, types.MethodType):
518 continue
518 continue
519 if not first:
519 if not first:
520 p.text(',')
520 p.text(',')
521 p.breakable()
521 p.breakable()
522 p.text(key)
522 p.text(key)
523 p.text('=')
523 p.text('=')
524 step = len(key) + 1
524 step = len(key) + 1
525 p.indentation += step
525 p.indentation += step
526 p.pretty(value)
526 p.pretty(value)
527 p.indentation -= step
527 p.indentation -= step
528 first = False
528 first = False
529 p.end_group(1, '>')
529 p.end_group(1, '>')
530
530
531
531
532 def _seq_pprinter_factory(start, end, basetype):
532 def _seq_pprinter_factory(start, end, basetype):
533 """
533 """
534 Factory that returns a pprint function useful for sequences. Used by
534 Factory that returns a pprint function useful for sequences. Used by
535 the default pprint for tuples, dicts, and lists.
535 the default pprint for tuples, dicts, and lists.
536 """
536 """
537 def inner(obj, p, cycle):
537 def inner(obj, p, cycle):
538 typ = type(obj)
538 typ = type(obj)
539 if basetype is not None and typ is not basetype and typ.__repr__ != basetype.__repr__:
539 if basetype is not None and typ is not basetype and typ.__repr__ != basetype.__repr__:
540 # If the subclass provides its own repr, use it instead.
540 # If the subclass provides its own repr, use it instead.
541 return p.text(typ.__repr__(obj))
541 return p.text(typ.__repr__(obj))
542
542
543 if cycle:
543 if cycle:
544 return p.text(start + '...' + end)
544 return p.text(start + '...' + end)
545 step = len(start)
545 step = len(start)
546 p.begin_group(step, start)
546 p.begin_group(step, start)
547 for idx, x in p._enumerate(obj):
547 for idx, x in p._enumerate(obj):
548 if idx:
548 if idx:
549 p.text(',')
549 p.text(',')
550 p.breakable()
550 p.breakable()
551 p.pretty(x)
551 p.pretty(x)
552 if len(obj) == 1 and type(obj) is tuple:
552 if len(obj) == 1 and type(obj) is tuple:
553 # Special case for 1-item tuples.
553 # Special case for 1-item tuples.
554 p.text(',')
554 p.text(',')
555 p.end_group(step, end)
555 p.end_group(step, end)
556 return inner
556 return inner
557
557
558
558
559 def _set_pprinter_factory(start, end, basetype):
559 def _set_pprinter_factory(start, end, basetype):
560 """
560 """
561 Factory that returns a pprint function useful for sets and frozensets.
561 Factory that returns a pprint function useful for sets and frozensets.
562 """
562 """
563 def inner(obj, p, cycle):
563 def inner(obj, p, cycle):
564 typ = type(obj)
564 typ = type(obj)
565 if basetype is not None and typ is not basetype and typ.__repr__ != basetype.__repr__:
565 if basetype is not None and typ is not basetype and typ.__repr__ != basetype.__repr__:
566 # If the subclass provides its own repr, use it instead.
566 # If the subclass provides its own repr, use it instead.
567 return p.text(typ.__repr__(obj))
567 return p.text(typ.__repr__(obj))
568
568
569 if cycle:
569 if cycle:
570 return p.text(start + '...' + end)
570 return p.text(start + '...' + end)
571 if len(obj) == 0:
571 if len(obj) == 0:
572 # Special case.
572 # Special case.
573 p.text(basetype.__name__ + '()')
573 p.text(basetype.__name__ + '()')
574 else:
574 else:
575 step = len(start)
575 step = len(start)
576 p.begin_group(step, start)
576 p.begin_group(step, start)
577 # Like dictionary keys, we will try to sort the items if there aren't too many
577 # Like dictionary keys, we will try to sort the items if there aren't too many
578 items = obj
578 items = obj
579 if not (p.max_seq_length and len(obj) >= p.max_seq_length):
579 if not (p.max_seq_length and len(obj) >= p.max_seq_length):
580 try:
580 try:
581 items = sorted(obj)
581 items = sorted(obj)
582 except Exception:
582 except Exception:
583 # Sometimes the items don't sort.
583 # Sometimes the items don't sort.
584 pass
584 pass
585 for idx, x in p._enumerate(items):
585 for idx, x in p._enumerate(items):
586 if idx:
586 if idx:
587 p.text(',')
587 p.text(',')
588 p.breakable()
588 p.breakable()
589 p.pretty(x)
589 p.pretty(x)
590 p.end_group(step, end)
590 p.end_group(step, end)
591 return inner
591 return inner
592
592
593
593
594 def _dict_pprinter_factory(start, end, basetype=None):
594 def _dict_pprinter_factory(start, end, basetype=None):
595 """
595 """
596 Factory that returns a pprint function used by the default pprint of
596 Factory that returns a pprint function used by the default pprint of
597 dicts and dict proxies.
597 dicts and dict proxies.
598 """
598 """
599 def inner(obj, p, cycle):
599 def inner(obj, p, cycle):
600 typ = type(obj)
600 typ = type(obj)
601 if basetype is not None and typ is not basetype and typ.__repr__ != basetype.__repr__:
601 if basetype is not None and typ is not basetype and typ.__repr__ != basetype.__repr__:
602 # If the subclass provides its own repr, use it instead.
602 # If the subclass provides its own repr, use it instead.
603 return p.text(typ.__repr__(obj))
603 return p.text(typ.__repr__(obj))
604
604
605 if cycle:
605 if cycle:
606 return p.text('{...}')
606 return p.text('{...}')
607 step = len(start)
607 step = len(start)
608 p.begin_group(step, start)
608 p.begin_group(step, start)
609 keys = obj.keys()
609 keys = obj.keys()
610 # if dict isn't large enough to be truncated, sort keys before displaying
610 # if dict isn't large enough to be truncated, sort keys before displaying
611 if not (p.max_seq_length and len(obj) >= p.max_seq_length):
611 if not (p.max_seq_length and len(obj) >= p.max_seq_length):
612 try:
612 try:
613 keys = sorted(keys)
613 keys = sorted(keys)
614 except Exception:
614 except Exception:
615 # Sometimes the keys don't sort.
615 # Sometimes the keys don't sort.
616 pass
616 pass
617 for idx, key in p._enumerate(keys):
617 for idx, key in p._enumerate(keys):
618 if idx:
618 if idx:
619 p.text(',')
619 p.text(',')
620 p.breakable()
620 p.breakable()
621 p.pretty(key)
621 p.pretty(key)
622 p.text(': ')
622 p.text(': ')
623 p.pretty(obj[key])
623 p.pretty(obj[key])
624 p.end_group(step, end)
624 p.end_group(step, end)
625 return inner
625 return inner
626
626
627
627
628 def _super_pprint(obj, p, cycle):
628 def _super_pprint(obj, p, cycle):
629 """The pprint for the super type."""
629 """The pprint for the super type."""
630 p.begin_group(8, '<super: ')
630 p.begin_group(8, '<super: ')
631 p.pretty(obj.__thisclass__)
631 p.pretty(obj.__thisclass__)
632 p.text(',')
632 p.text(',')
633 p.breakable()
633 p.breakable()
634 if PYPY: # In PyPy, super() objects don't have __self__ attributes
634 if PYPY: # In PyPy, super() objects don't have __self__ attributes
635 dself = obj.__repr__.__self__
635 dself = obj.__repr__.__self__
636 p.pretty(None if dself is obj else dself)
636 p.pretty(None if dself is obj else dself)
637 else:
637 else:
638 p.pretty(obj.__self__)
638 p.pretty(obj.__self__)
639 p.end_group(8, '>')
639 p.end_group(8, '>')
640
640
641
641
642 def _re_pattern_pprint(obj, p, cycle):
642 def _re_pattern_pprint(obj, p, cycle):
643 """The pprint function for regular expression patterns."""
643 """The pprint function for regular expression patterns."""
644 p.text('re.compile(')
644 p.text('re.compile(')
645 pattern = repr(obj.pattern)
645 pattern = repr(obj.pattern)
646 if pattern[:1] in 'uU':
646 if pattern[:1] in 'uU':
647 pattern = pattern[1:]
647 pattern = pattern[1:]
648 prefix = 'ur'
648 prefix = 'ur'
649 else:
649 else:
650 prefix = 'r'
650 prefix = 'r'
651 pattern = prefix + pattern.replace('\\\\', '\\')
651 pattern = prefix + pattern.replace('\\\\', '\\')
652 p.text(pattern)
652 p.text(pattern)
653 if obj.flags:
653 if obj.flags:
654 p.text(',')
654 p.text(',')
655 p.breakable()
655 p.breakable()
656 done_one = False
656 done_one = False
657 for flag in ('TEMPLATE', 'IGNORECASE', 'LOCALE', 'MULTILINE', 'DOTALL',
657 for flag in ('TEMPLATE', 'IGNORECASE', 'LOCALE', 'MULTILINE', 'DOTALL',
658 'UNICODE', 'VERBOSE', 'DEBUG'):
658 'UNICODE', 'VERBOSE', 'DEBUG'):
659 if obj.flags & getattr(re, flag):
659 if obj.flags & getattr(re, flag):
660 if done_one:
660 if done_one:
661 p.text('|')
661 p.text('|')
662 p.text('re.' + flag)
662 p.text('re.' + flag)
663 done_one = True
663 done_one = True
664 p.text(')')
664 p.text(')')
665
665
666
666
667 def _type_pprint(obj, p, cycle):
667 def _type_pprint(obj, p, cycle):
668 """The pprint for classes and types."""
668 """The pprint for classes and types."""
669 # Heap allocated types might not have the module attribute,
669 # Heap allocated types might not have the module attribute,
670 # and others may set it to None.
670 # and others may set it to None.
671
671
672 # Checks for a __repr__ override in the metaclass. Can't compare the
672 # Checks for a __repr__ override in the metaclass. Can't compare the
673 # type(obj).__repr__ directly because in PyPy the representation function
673 # type(obj).__repr__ directly because in PyPy the representation function
674 # inherited from type isn't the same type.__repr__
674 # inherited from type isn't the same type.__repr__
675 if [m for m in _get_mro(type(obj)) if "__repr__" in vars(m)][:1] != [type]:
675 if [m for m in _get_mro(type(obj)) if "__repr__" in vars(m)][:1] != [type]:
676 _repr_pprint(obj, p, cycle)
676 _repr_pprint(obj, p, cycle)
677 return
677 return
678
678
679 mod = _safe_getattr(obj, '__module__', None)
679 mod = _safe_getattr(obj, '__module__', None)
680 try:
680 try:
681 name = obj.__qualname__
681 name = obj.__qualname__
682 if not isinstance(name, string_types):
682 if not isinstance(name, string_types):
683 # This can happen if the type implements __qualname__ as a property
683 # This can happen if the type implements __qualname__ as a property
684 # or other descriptor in Python 2.
684 # or other descriptor in Python 2.
685 raise Exception("Try __name__")
685 raise Exception("Try __name__")
686 except Exception:
686 except Exception:
687 name = obj.__name__
687 name = obj.__name__
688 if not isinstance(name, string_types):
688 if not isinstance(name, string_types):
689 name = '<unknown type>'
689 name = '<unknown type>'
690
690
691 if mod in (None, '__builtin__', 'builtins', 'exceptions'):
691 if mod in (None, '__builtin__', 'builtins', 'exceptions'):
692 p.text(name)
692 p.text(name)
693 else:
693 else:
694 p.text(mod + '.' + name)
694 p.text(mod + '.' + name)
695
695
696
696
697 def _repr_pprint(obj, p, cycle):
697 def _repr_pprint(obj, p, cycle):
698 """A pprint that just redirects to the normal repr function."""
698 """A pprint that just redirects to the normal repr function."""
699 # Find newlines and replace them with p.break_()
699 # Find newlines and replace them with p.break_()
700 output = repr(obj)
700 output = repr(obj)
701 for idx,output_line in enumerate(output.splitlines()):
701 for idx,output_line in enumerate(output.splitlines()):
702 if idx:
702 if idx:
703 p.break_()
703 p.break_()
704 p.text(output_line)
704 p.text(output_line)
705
705
706
706
707 def _function_pprint(obj, p, cycle):
707 def _function_pprint(obj, p, cycle):
708 """Base pprint for all functions and builtin functions."""
708 """Base pprint for all functions and builtin functions."""
709 name = _safe_getattr(obj, '__qualname__', obj.__name__)
709 name = _safe_getattr(obj, '__qualname__', obj.__name__)
710 mod = obj.__module__
710 mod = obj.__module__
711 if mod and mod not in ('__builtin__', 'builtins', 'exceptions'):
711 if mod and mod not in ('__builtin__', 'builtins', 'exceptions'):
712 name = mod + '.' + name
712 name = mod + '.' + name
713 p.text('<function %s>' % name)
713 p.text('<function %s>' % name)
714
714
715
715
716 def _exception_pprint(obj, p, cycle):
716 def _exception_pprint(obj, p, cycle):
717 """Base pprint for all exceptions."""
717 """Base pprint for all exceptions."""
718 name = getattr(obj.__class__, '__qualname__', obj.__class__.__name__)
718 name = getattr(obj.__class__, '__qualname__', obj.__class__.__name__)
719 if obj.__class__.__module__ not in ('exceptions', 'builtins'):
719 if obj.__class__.__module__ not in ('exceptions', 'builtins'):
720 name = '%s.%s' % (obj.__class__.__module__, name)
720 name = '%s.%s' % (obj.__class__.__module__, name)
721 step = len(name) + 1
721 step = len(name) + 1
722 p.begin_group(step, name + '(')
722 p.begin_group(step, name + '(')
723 for idx, arg in enumerate(getattr(obj, 'args', ())):
723 for idx, arg in enumerate(getattr(obj, 'args', ())):
724 if idx:
724 if idx:
725 p.text(',')
725 p.text(',')
726 p.breakable()
726 p.breakable()
727 p.pretty(arg)
727 p.pretty(arg)
728 p.end_group(step, ')')
728 p.end_group(step, ')')
729
729
730
730
731 #: the exception base
731 #: the exception base
732 try:
732 try:
733 _exception_base = BaseException
733 _exception_base = BaseException
734 except NameError:
734 except NameError:
735 _exception_base = Exception
735 _exception_base = Exception
736
736
737
737
738 #: printers for builtin types
738 #: printers for builtin types
739 _type_pprinters = {
739 _type_pprinters = {
740 int: _repr_pprint,
740 int: _repr_pprint,
741 float: _repr_pprint,
741 float: _repr_pprint,
742 str: _repr_pprint,
742 str: _repr_pprint,
743 tuple: _seq_pprinter_factory('(', ')', tuple),
743 tuple: _seq_pprinter_factory('(', ')', tuple),
744 list: _seq_pprinter_factory('[', ']', list),
744 list: _seq_pprinter_factory('[', ']', list),
745 dict: _dict_pprinter_factory('{', '}', dict),
745 dict: _dict_pprinter_factory('{', '}', dict),
746
746
747 set: _set_pprinter_factory('{', '}', set),
747 set: _set_pprinter_factory('{', '}', set),
748 frozenset: _set_pprinter_factory('frozenset({', '})', frozenset),
748 frozenset: _set_pprinter_factory('frozenset({', '})', frozenset),
749 super: _super_pprint,
749 super: _super_pprint,
750 _re_pattern_type: _re_pattern_pprint,
750 _re_pattern_type: _re_pattern_pprint,
751 type: _type_pprint,
751 type: _type_pprint,
752 types.FunctionType: _function_pprint,
752 types.FunctionType: _function_pprint,
753 types.BuiltinFunctionType: _function_pprint,
753 types.BuiltinFunctionType: _function_pprint,
754 types.MethodType: _repr_pprint,
754 types.MethodType: _repr_pprint,
755
755
756 datetime.datetime: _repr_pprint,
756 datetime.datetime: _repr_pprint,
757 datetime.timedelta: _repr_pprint,
757 datetime.timedelta: _repr_pprint,
758 _exception_base: _exception_pprint
758 _exception_base: _exception_pprint
759 }
759 }
760
760
761 try:
761 try:
762 # In PyPy, types.DictProxyType is dict, setting the dictproxy printer
762 # In PyPy, types.DictProxyType is dict, setting the dictproxy printer
763 # using dict.setdefault avoids overwritting the dict printer
763 # using dict.setdefault avoids overwritting the dict printer
764 _type_pprinters.setdefault(types.DictProxyType,
764 _type_pprinters.setdefault(types.DictProxyType,
765 _dict_pprinter_factory('dict_proxy({', '})'))
765 _dict_pprinter_factory('dict_proxy({', '})'))
766 _type_pprinters[types.ClassType] = _type_pprint
766 _type_pprinters[types.ClassType] = _type_pprint
767 _type_pprinters[types.SliceType] = _repr_pprint
767 _type_pprinters[types.SliceType] = _repr_pprint
768 except AttributeError: # Python 3
768 except AttributeError: # Python 3
769 _type_pprinters[types.MappingProxyType] = \
769 _type_pprinters[types.MappingProxyType] = \
770 _dict_pprinter_factory('mappingproxy({', '})')
770 _dict_pprinter_factory('mappingproxy({', '})')
771 _type_pprinters[slice] = _repr_pprint
771 _type_pprinters[slice] = _repr_pprint
772
772
773 try:
773 try:
774 _type_pprinters[xrange] = _repr_pprint
775 _type_pprinters[long] = _repr_pprint
774 _type_pprinters[long] = _repr_pprint
776 _type_pprinters[unicode] = _repr_pprint
775 _type_pprinters[unicode] = _repr_pprint
777 except NameError:
776 except NameError:
778 _type_pprinters[range] = _repr_pprint
777 _type_pprinters[range] = _repr_pprint
779 _type_pprinters[bytes] = _repr_pprint
778 _type_pprinters[bytes] = _repr_pprint
780
779
781 #: printers for types specified by name
780 #: printers for types specified by name
782 _deferred_type_pprinters = {
781 _deferred_type_pprinters = {
783 }
782 }
784
783
785 def for_type(typ, func):
784 def for_type(typ, func):
786 """
785 """
787 Add a pretty printer for a given type.
786 Add a pretty printer for a given type.
788 """
787 """
789 oldfunc = _type_pprinters.get(typ, None)
788 oldfunc = _type_pprinters.get(typ, None)
790 if func is not None:
789 if func is not None:
791 # To support easy restoration of old pprinters, we need to ignore Nones.
790 # To support easy restoration of old pprinters, we need to ignore Nones.
792 _type_pprinters[typ] = func
791 _type_pprinters[typ] = func
793 return oldfunc
792 return oldfunc
794
793
795 def for_type_by_name(type_module, type_name, func):
794 def for_type_by_name(type_module, type_name, func):
796 """
795 """
797 Add a pretty printer for a type specified by the module and name of a type
796 Add a pretty printer for a type specified by the module and name of a type
798 rather than the type object itself.
797 rather than the type object itself.
799 """
798 """
800 key = (type_module, type_name)
799 key = (type_module, type_name)
801 oldfunc = _deferred_type_pprinters.get(key, None)
800 oldfunc = _deferred_type_pprinters.get(key, None)
802 if func is not None:
801 if func is not None:
803 # To support easy restoration of old pprinters, we need to ignore Nones.
802 # To support easy restoration of old pprinters, we need to ignore Nones.
804 _deferred_type_pprinters[key] = func
803 _deferred_type_pprinters[key] = func
805 return oldfunc
804 return oldfunc
806
805
807
806
808 #: printers for the default singletons
807 #: printers for the default singletons
809 _singleton_pprinters = dict.fromkeys(map(id, [None, True, False, Ellipsis,
808 _singleton_pprinters = dict.fromkeys(map(id, [None, True, False, Ellipsis,
810 NotImplemented]), _repr_pprint)
809 NotImplemented]), _repr_pprint)
811
810
812
811
813 def _defaultdict_pprint(obj, p, cycle):
812 def _defaultdict_pprint(obj, p, cycle):
814 name = obj.__class__.__name__
813 name = obj.__class__.__name__
815 with p.group(len(name) + 1, name + '(', ')'):
814 with p.group(len(name) + 1, name + '(', ')'):
816 if cycle:
815 if cycle:
817 p.text('...')
816 p.text('...')
818 else:
817 else:
819 p.pretty(obj.default_factory)
818 p.pretty(obj.default_factory)
820 p.text(',')
819 p.text(',')
821 p.breakable()
820 p.breakable()
822 p.pretty(dict(obj))
821 p.pretty(dict(obj))
823
822
824 def _ordereddict_pprint(obj, p, cycle):
823 def _ordereddict_pprint(obj, p, cycle):
825 name = obj.__class__.__name__
824 name = obj.__class__.__name__
826 with p.group(len(name) + 1, name + '(', ')'):
825 with p.group(len(name) + 1, name + '(', ')'):
827 if cycle:
826 if cycle:
828 p.text('...')
827 p.text('...')
829 elif len(obj):
828 elif len(obj):
830 p.pretty(list(obj.items()))
829 p.pretty(list(obj.items()))
831
830
832 def _deque_pprint(obj, p, cycle):
831 def _deque_pprint(obj, p, cycle):
833 name = obj.__class__.__name__
832 name = obj.__class__.__name__
834 with p.group(len(name) + 1, name + '(', ')'):
833 with p.group(len(name) + 1, name + '(', ')'):
835 if cycle:
834 if cycle:
836 p.text('...')
835 p.text('...')
837 else:
836 else:
838 p.pretty(list(obj))
837 p.pretty(list(obj))
839
838
840
839
841 def _counter_pprint(obj, p, cycle):
840 def _counter_pprint(obj, p, cycle):
842 name = obj.__class__.__name__
841 name = obj.__class__.__name__
843 with p.group(len(name) + 1, name + '(', ')'):
842 with p.group(len(name) + 1, name + '(', ')'):
844 if cycle:
843 if cycle:
845 p.text('...')
844 p.text('...')
846 elif len(obj):
845 elif len(obj):
847 p.pretty(dict(obj))
846 p.pretty(dict(obj))
848
847
849 for_type_by_name('collections', 'defaultdict', _defaultdict_pprint)
848 for_type_by_name('collections', 'defaultdict', _defaultdict_pprint)
850 for_type_by_name('collections', 'OrderedDict', _ordereddict_pprint)
849 for_type_by_name('collections', 'OrderedDict', _ordereddict_pprint)
851 for_type_by_name('collections', 'deque', _deque_pprint)
850 for_type_by_name('collections', 'deque', _deque_pprint)
852 for_type_by_name('collections', 'Counter', _counter_pprint)
851 for_type_by_name('collections', 'Counter', _counter_pprint)
853
852
854 if __name__ == '__main__':
853 if __name__ == '__main__':
855 from random import randrange
854 from random import randrange
856 class Foo(object):
855 class Foo(object):
857 def __init__(self):
856 def __init__(self):
858 self.foo = 1
857 self.foo = 1
859 self.bar = re.compile(r'\s+')
858 self.bar = re.compile(r'\s+')
860 self.blub = dict.fromkeys(range(30), randrange(1, 40))
859 self.blub = dict.fromkeys(range(30), randrange(1, 40))
861 self.hehe = 23424.234234
860 self.hehe = 23424.234234
862 self.list = ["blub", "blah", self]
861 self.list = ["blub", "blah", self]
863
862
864 def get_foo(self):
863 def get_foo(self):
865 print("foo")
864 print("foo")
866
865
867 pprint(Foo(), verbose=True)
866 pprint(Foo(), verbose=True)
@@ -1,37 +1,36 b''
1 # encoding: utf-8
1 # encoding: utf-8
2 """Utilities for working with data structures like lists, dicts and tuples.
2 """Utilities for working with data structures like lists, dicts and tuples.
3 """
3 """
4
4
5 #-----------------------------------------------------------------------------
5 #-----------------------------------------------------------------------------
6 # Copyright (C) 2008-2011 The IPython Development Team
6 # Copyright (C) 2008-2011 The IPython Development Team
7 #
7 #
8 # Distributed under the terms of the BSD License. The full license is in
8 # Distributed under the terms of the BSD License. The full license is in
9 # the file COPYING, distributed as part of this software.
9 # the file COPYING, distributed as part of this software.
10 #-----------------------------------------------------------------------------
10 #-----------------------------------------------------------------------------
11
11
12 from .py3compat import xrange
13
12
14 def uniq_stable(elems):
13 def uniq_stable(elems):
15 """uniq_stable(elems) -> list
14 """uniq_stable(elems) -> list
16
15
17 Return from an iterable, a list of all the unique elements in the input,
16 Return from an iterable, a list of all the unique elements in the input,
18 but maintaining the order in which they first appear.
17 but maintaining the order in which they first appear.
19
18
20 Note: All elements in the input must be hashable for this routine
19 Note: All elements in the input must be hashable for this routine
21 to work, as it internally uses a set for efficiency reasons.
20 to work, as it internally uses a set for efficiency reasons.
22 """
21 """
23 seen = set()
22 seen = set()
24 return [x for x in elems if x not in seen and not seen.add(x)]
23 return [x for x in elems if x not in seen and not seen.add(x)]
25
24
26
25
27 def flatten(seq):
26 def flatten(seq):
28 """Flatten a list of lists (NOT recursive, only works for 2d lists)."""
27 """Flatten a list of lists (NOT recursive, only works for 2d lists)."""
29
28
30 return [x for subseq in seq for x in subseq]
29 return [x for subseq in seq for x in subseq]
31
30
32
31
33 def chop(seq, size):
32 def chop(seq, size):
34 """Chop a sequence into chunks of the given size."""
33 """Chop a sequence into chunks of the given size."""
35 return [seq[i:i+size] for i in xrange(0,len(seq),size)]
34 return [seq[i:i+size] for i in range(0,len(seq),size)]
36
35
37
36
@@ -1,774 +1,774 b''
1 # encoding: utf-8
1 # encoding: utf-8
2 """
2 """
3 Utilities for working with strings and text.
3 Utilities for working with strings and text.
4
4
5 Inheritance diagram:
5 Inheritance diagram:
6
6
7 .. inheritance-diagram:: IPython.utils.text
7 .. inheritance-diagram:: IPython.utils.text
8 :parts: 3
8 :parts: 3
9 """
9 """
10
10
11 import os
11 import os
12 import re
12 import re
13 import sys
13 import sys
14 import textwrap
14 import textwrap
15 from string import Formatter
15 from string import Formatter
16 try:
16 try:
17 from pathlib import Path
17 from pathlib import Path
18 except ImportError:
18 except ImportError:
19 # Python 2 backport
19 # Python 2 backport
20 from pathlib2 import Path
20 from pathlib2 import Path
21
21
22 from IPython.utils import py3compat
22 from IPython.utils import py3compat
23
23
24 # datetime.strftime date format for ipython
24 # datetime.strftime date format for ipython
25 if sys.platform == 'win32':
25 if sys.platform == 'win32':
26 date_format = "%B %d, %Y"
26 date_format = "%B %d, %Y"
27 else:
27 else:
28 date_format = "%B %-d, %Y"
28 date_format = "%B %-d, %Y"
29
29
30 class LSString(str):
30 class LSString(str):
31 """String derivative with a special access attributes.
31 """String derivative with a special access attributes.
32
32
33 These are normal strings, but with the special attributes:
33 These are normal strings, but with the special attributes:
34
34
35 .l (or .list) : value as list (split on newlines).
35 .l (or .list) : value as list (split on newlines).
36 .n (or .nlstr): original value (the string itself).
36 .n (or .nlstr): original value (the string itself).
37 .s (or .spstr): value as whitespace-separated string.
37 .s (or .spstr): value as whitespace-separated string.
38 .p (or .paths): list of path objects (requires path.py package)
38 .p (or .paths): list of path objects (requires path.py package)
39
39
40 Any values which require transformations are computed only once and
40 Any values which require transformations are computed only once and
41 cached.
41 cached.
42
42
43 Such strings are very useful to efficiently interact with the shell, which
43 Such strings are very useful to efficiently interact with the shell, which
44 typically only understands whitespace-separated options for commands."""
44 typically only understands whitespace-separated options for commands."""
45
45
46 def get_list(self):
46 def get_list(self):
47 try:
47 try:
48 return self.__list
48 return self.__list
49 except AttributeError:
49 except AttributeError:
50 self.__list = self.split('\n')
50 self.__list = self.split('\n')
51 return self.__list
51 return self.__list
52
52
53 l = list = property(get_list)
53 l = list = property(get_list)
54
54
55 def get_spstr(self):
55 def get_spstr(self):
56 try:
56 try:
57 return self.__spstr
57 return self.__spstr
58 except AttributeError:
58 except AttributeError:
59 self.__spstr = self.replace('\n',' ')
59 self.__spstr = self.replace('\n',' ')
60 return self.__spstr
60 return self.__spstr
61
61
62 s = spstr = property(get_spstr)
62 s = spstr = property(get_spstr)
63
63
64 def get_nlstr(self):
64 def get_nlstr(self):
65 return self
65 return self
66
66
67 n = nlstr = property(get_nlstr)
67 n = nlstr = property(get_nlstr)
68
68
69 def get_paths(self):
69 def get_paths(self):
70 try:
70 try:
71 return self.__paths
71 return self.__paths
72 except AttributeError:
72 except AttributeError:
73 self.__paths = [Path(p) for p in self.split('\n') if os.path.exists(p)]
73 self.__paths = [Path(p) for p in self.split('\n') if os.path.exists(p)]
74 return self.__paths
74 return self.__paths
75
75
76 p = paths = property(get_paths)
76 p = paths = property(get_paths)
77
77
78 # FIXME: We need to reimplement type specific displayhook and then add this
78 # FIXME: We need to reimplement type specific displayhook and then add this
79 # back as a custom printer. This should also be moved outside utils into the
79 # back as a custom printer. This should also be moved outside utils into the
80 # core.
80 # core.
81
81
82 # def print_lsstring(arg):
82 # def print_lsstring(arg):
83 # """ Prettier (non-repr-like) and more informative printer for LSString """
83 # """ Prettier (non-repr-like) and more informative printer for LSString """
84 # print "LSString (.p, .n, .l, .s available). Value:"
84 # print "LSString (.p, .n, .l, .s available). Value:"
85 # print arg
85 # print arg
86 #
86 #
87 #
87 #
88 # print_lsstring = result_display.when_type(LSString)(print_lsstring)
88 # print_lsstring = result_display.when_type(LSString)(print_lsstring)
89
89
90
90
91 class SList(list):
91 class SList(list):
92 """List derivative with a special access attributes.
92 """List derivative with a special access attributes.
93
93
94 These are normal lists, but with the special attributes:
94 These are normal lists, but with the special attributes:
95
95
96 * .l (or .list) : value as list (the list itself).
96 * .l (or .list) : value as list (the list itself).
97 * .n (or .nlstr): value as a string, joined on newlines.
97 * .n (or .nlstr): value as a string, joined on newlines.
98 * .s (or .spstr): value as a string, joined on spaces.
98 * .s (or .spstr): value as a string, joined on spaces.
99 * .p (or .paths): list of path objects (requires path.py package)
99 * .p (or .paths): list of path objects (requires path.py package)
100
100
101 Any values which require transformations are computed only once and
101 Any values which require transformations are computed only once and
102 cached."""
102 cached."""
103
103
104 def get_list(self):
104 def get_list(self):
105 return self
105 return self
106
106
107 l = list = property(get_list)
107 l = list = property(get_list)
108
108
109 def get_spstr(self):
109 def get_spstr(self):
110 try:
110 try:
111 return self.__spstr
111 return self.__spstr
112 except AttributeError:
112 except AttributeError:
113 self.__spstr = ' '.join(self)
113 self.__spstr = ' '.join(self)
114 return self.__spstr
114 return self.__spstr
115
115
116 s = spstr = property(get_spstr)
116 s = spstr = property(get_spstr)
117
117
118 def get_nlstr(self):
118 def get_nlstr(self):
119 try:
119 try:
120 return self.__nlstr
120 return self.__nlstr
121 except AttributeError:
121 except AttributeError:
122 self.__nlstr = '\n'.join(self)
122 self.__nlstr = '\n'.join(self)
123 return self.__nlstr
123 return self.__nlstr
124
124
125 n = nlstr = property(get_nlstr)
125 n = nlstr = property(get_nlstr)
126
126
127 def get_paths(self):
127 def get_paths(self):
128 try:
128 try:
129 return self.__paths
129 return self.__paths
130 except AttributeError:
130 except AttributeError:
131 self.__paths = [Path(p) for p in self if os.path.exists(p)]
131 self.__paths = [Path(p) for p in self if os.path.exists(p)]
132 return self.__paths
132 return self.__paths
133
133
134 p = paths = property(get_paths)
134 p = paths = property(get_paths)
135
135
136 def grep(self, pattern, prune = False, field = None):
136 def grep(self, pattern, prune = False, field = None):
137 """ Return all strings matching 'pattern' (a regex or callable)
137 """ Return all strings matching 'pattern' (a regex or callable)
138
138
139 This is case-insensitive. If prune is true, return all items
139 This is case-insensitive. If prune is true, return all items
140 NOT matching the pattern.
140 NOT matching the pattern.
141
141
142 If field is specified, the match must occur in the specified
142 If field is specified, the match must occur in the specified
143 whitespace-separated field.
143 whitespace-separated field.
144
144
145 Examples::
145 Examples::
146
146
147 a.grep( lambda x: x.startswith('C') )
147 a.grep( lambda x: x.startswith('C') )
148 a.grep('Cha.*log', prune=1)
148 a.grep('Cha.*log', prune=1)
149 a.grep('chm', field=-1)
149 a.grep('chm', field=-1)
150 """
150 """
151
151
152 def match_target(s):
152 def match_target(s):
153 if field is None:
153 if field is None:
154 return s
154 return s
155 parts = s.split()
155 parts = s.split()
156 try:
156 try:
157 tgt = parts[field]
157 tgt = parts[field]
158 return tgt
158 return tgt
159 except IndexError:
159 except IndexError:
160 return ""
160 return ""
161
161
162 if isinstance(pattern, py3compat.string_types):
162 if isinstance(pattern, py3compat.string_types):
163 pred = lambda x : re.search(pattern, x, re.IGNORECASE)
163 pred = lambda x : re.search(pattern, x, re.IGNORECASE)
164 else:
164 else:
165 pred = pattern
165 pred = pattern
166 if not prune:
166 if not prune:
167 return SList([el for el in self if pred(match_target(el))])
167 return SList([el for el in self if pred(match_target(el))])
168 else:
168 else:
169 return SList([el for el in self if not pred(match_target(el))])
169 return SList([el for el in self if not pred(match_target(el))])
170
170
171 def fields(self, *fields):
171 def fields(self, *fields):
172 """ Collect whitespace-separated fields from string list
172 """ Collect whitespace-separated fields from string list
173
173
174 Allows quick awk-like usage of string lists.
174 Allows quick awk-like usage of string lists.
175
175
176 Example data (in var a, created by 'a = !ls -l')::
176 Example data (in var a, created by 'a = !ls -l')::
177
177
178 -rwxrwxrwx 1 ville None 18 Dec 14 2006 ChangeLog
178 -rwxrwxrwx 1 ville None 18 Dec 14 2006 ChangeLog
179 drwxrwxrwx+ 6 ville None 0 Oct 24 18:05 IPython
179 drwxrwxrwx+ 6 ville None 0 Oct 24 18:05 IPython
180
180
181 * ``a.fields(0)`` is ``['-rwxrwxrwx', 'drwxrwxrwx+']``
181 * ``a.fields(0)`` is ``['-rwxrwxrwx', 'drwxrwxrwx+']``
182 * ``a.fields(1,0)`` is ``['1 -rwxrwxrwx', '6 drwxrwxrwx+']``
182 * ``a.fields(1,0)`` is ``['1 -rwxrwxrwx', '6 drwxrwxrwx+']``
183 (note the joining by space).
183 (note the joining by space).
184 * ``a.fields(-1)`` is ``['ChangeLog', 'IPython']``
184 * ``a.fields(-1)`` is ``['ChangeLog', 'IPython']``
185
185
186 IndexErrors are ignored.
186 IndexErrors are ignored.
187
187
188 Without args, fields() just split()'s the strings.
188 Without args, fields() just split()'s the strings.
189 """
189 """
190 if len(fields) == 0:
190 if len(fields) == 0:
191 return [el.split() for el in self]
191 return [el.split() for el in self]
192
192
193 res = SList()
193 res = SList()
194 for el in [f.split() for f in self]:
194 for el in [f.split() for f in self]:
195 lineparts = []
195 lineparts = []
196
196
197 for fd in fields:
197 for fd in fields:
198 try:
198 try:
199 lineparts.append(el[fd])
199 lineparts.append(el[fd])
200 except IndexError:
200 except IndexError:
201 pass
201 pass
202 if lineparts:
202 if lineparts:
203 res.append(" ".join(lineparts))
203 res.append(" ".join(lineparts))
204
204
205 return res
205 return res
206
206
207 def sort(self,field= None, nums = False):
207 def sort(self,field= None, nums = False):
208 """ sort by specified fields (see fields())
208 """ sort by specified fields (see fields())
209
209
210 Example::
210 Example::
211
211
212 a.sort(1, nums = True)
212 a.sort(1, nums = True)
213
213
214 Sorts a by second field, in numerical order (so that 21 > 3)
214 Sorts a by second field, in numerical order (so that 21 > 3)
215
215
216 """
216 """
217
217
218 #decorate, sort, undecorate
218 #decorate, sort, undecorate
219 if field is not None:
219 if field is not None:
220 dsu = [[SList([line]).fields(field), line] for line in self]
220 dsu = [[SList([line]).fields(field), line] for line in self]
221 else:
221 else:
222 dsu = [[line, line] for line in self]
222 dsu = [[line, line] for line in self]
223 if nums:
223 if nums:
224 for i in range(len(dsu)):
224 for i in range(len(dsu)):
225 numstr = "".join([ch for ch in dsu[i][0] if ch.isdigit()])
225 numstr = "".join([ch for ch in dsu[i][0] if ch.isdigit()])
226 try:
226 try:
227 n = int(numstr)
227 n = int(numstr)
228 except ValueError:
228 except ValueError:
229 n = 0
229 n = 0
230 dsu[i][0] = n
230 dsu[i][0] = n
231
231
232
232
233 dsu.sort()
233 dsu.sort()
234 return SList([t[1] for t in dsu])
234 return SList([t[1] for t in dsu])
235
235
236
236
237 # FIXME: We need to reimplement type specific displayhook and then add this
237 # FIXME: We need to reimplement type specific displayhook and then add this
238 # back as a custom printer. This should also be moved outside utils into the
238 # back as a custom printer. This should also be moved outside utils into the
239 # core.
239 # core.
240
240
241 # def print_slist(arg):
241 # def print_slist(arg):
242 # """ Prettier (non-repr-like) and more informative printer for SList """
242 # """ Prettier (non-repr-like) and more informative printer for SList """
243 # print "SList (.p, .n, .l, .s, .grep(), .fields(), sort() available):"
243 # print "SList (.p, .n, .l, .s, .grep(), .fields(), sort() available):"
244 # if hasattr(arg, 'hideonce') and arg.hideonce:
244 # if hasattr(arg, 'hideonce') and arg.hideonce:
245 # arg.hideonce = False
245 # arg.hideonce = False
246 # return
246 # return
247 #
247 #
248 # nlprint(arg) # This was a nested list printer, now removed.
248 # nlprint(arg) # This was a nested list printer, now removed.
249 #
249 #
250 # print_slist = result_display.when_type(SList)(print_slist)
250 # print_slist = result_display.when_type(SList)(print_slist)
251
251
252
252
253 def indent(instr,nspaces=4, ntabs=0, flatten=False):
253 def indent(instr,nspaces=4, ntabs=0, flatten=False):
254 """Indent a string a given number of spaces or tabstops.
254 """Indent a string a given number of spaces or tabstops.
255
255
256 indent(str,nspaces=4,ntabs=0) -> indent str by ntabs+nspaces.
256 indent(str,nspaces=4,ntabs=0) -> indent str by ntabs+nspaces.
257
257
258 Parameters
258 Parameters
259 ----------
259 ----------
260
260
261 instr : basestring
261 instr : basestring
262 The string to be indented.
262 The string to be indented.
263 nspaces : int (default: 4)
263 nspaces : int (default: 4)
264 The number of spaces to be indented.
264 The number of spaces to be indented.
265 ntabs : int (default: 0)
265 ntabs : int (default: 0)
266 The number of tabs to be indented.
266 The number of tabs to be indented.
267 flatten : bool (default: False)
267 flatten : bool (default: False)
268 Whether to scrub existing indentation. If True, all lines will be
268 Whether to scrub existing indentation. If True, all lines will be
269 aligned to the same indentation. If False, existing indentation will
269 aligned to the same indentation. If False, existing indentation will
270 be strictly increased.
270 be strictly increased.
271
271
272 Returns
272 Returns
273 -------
273 -------
274
274
275 str|unicode : string indented by ntabs and nspaces.
275 str|unicode : string indented by ntabs and nspaces.
276
276
277 """
277 """
278 if instr is None:
278 if instr is None:
279 return
279 return
280 ind = '\t'*ntabs+' '*nspaces
280 ind = '\t'*ntabs+' '*nspaces
281 if flatten:
281 if flatten:
282 pat = re.compile(r'^\s*', re.MULTILINE)
282 pat = re.compile(r'^\s*', re.MULTILINE)
283 else:
283 else:
284 pat = re.compile(r'^', re.MULTILINE)
284 pat = re.compile(r'^', re.MULTILINE)
285 outstr = re.sub(pat, ind, instr)
285 outstr = re.sub(pat, ind, instr)
286 if outstr.endswith(os.linesep+ind):
286 if outstr.endswith(os.linesep+ind):
287 return outstr[:-len(ind)]
287 return outstr[:-len(ind)]
288 else:
288 else:
289 return outstr
289 return outstr
290
290
291
291
292 def list_strings(arg):
292 def list_strings(arg):
293 """Always return a list of strings, given a string or list of strings
293 """Always return a list of strings, given a string or list of strings
294 as input.
294 as input.
295
295
296 Examples
296 Examples
297 --------
297 --------
298 ::
298 ::
299
299
300 In [7]: list_strings('A single string')
300 In [7]: list_strings('A single string')
301 Out[7]: ['A single string']
301 Out[7]: ['A single string']
302
302
303 In [8]: list_strings(['A single string in a list'])
303 In [8]: list_strings(['A single string in a list'])
304 Out[8]: ['A single string in a list']
304 Out[8]: ['A single string in a list']
305
305
306 In [9]: list_strings(['A','list','of','strings'])
306 In [9]: list_strings(['A','list','of','strings'])
307 Out[9]: ['A', 'list', 'of', 'strings']
307 Out[9]: ['A', 'list', 'of', 'strings']
308 """
308 """
309
309
310 if isinstance(arg, py3compat.string_types): return [arg]
310 if isinstance(arg, py3compat.string_types): return [arg]
311 else: return arg
311 else: return arg
312
312
313
313
314 def marquee(txt='',width=78,mark='*'):
314 def marquee(txt='',width=78,mark='*'):
315 """Return the input string centered in a 'marquee'.
315 """Return the input string centered in a 'marquee'.
316
316
317 Examples
317 Examples
318 --------
318 --------
319 ::
319 ::
320
320
321 In [16]: marquee('A test',40)
321 In [16]: marquee('A test',40)
322 Out[16]: '**************** A test ****************'
322 Out[16]: '**************** A test ****************'
323
323
324 In [17]: marquee('A test',40,'-')
324 In [17]: marquee('A test',40,'-')
325 Out[17]: '---------------- A test ----------------'
325 Out[17]: '---------------- A test ----------------'
326
326
327 In [18]: marquee('A test',40,' ')
327 In [18]: marquee('A test',40,' ')
328 Out[18]: ' A test '
328 Out[18]: ' A test '
329
329
330 """
330 """
331 if not txt:
331 if not txt:
332 return (mark*width)[:width]
332 return (mark*width)[:width]
333 nmark = (width-len(txt)-2)//len(mark)//2
333 nmark = (width-len(txt)-2)//len(mark)//2
334 if nmark < 0: nmark =0
334 if nmark < 0: nmark =0
335 marks = mark*nmark
335 marks = mark*nmark
336 return '%s %s %s' % (marks,txt,marks)
336 return '%s %s %s' % (marks,txt,marks)
337
337
338
338
339 ini_spaces_re = re.compile(r'^(\s+)')
339 ini_spaces_re = re.compile(r'^(\s+)')
340
340
341 def num_ini_spaces(strng):
341 def num_ini_spaces(strng):
342 """Return the number of initial spaces in a string"""
342 """Return the number of initial spaces in a string"""
343
343
344 ini_spaces = ini_spaces_re.match(strng)
344 ini_spaces = ini_spaces_re.match(strng)
345 if ini_spaces:
345 if ini_spaces:
346 return ini_spaces.end()
346 return ini_spaces.end()
347 else:
347 else:
348 return 0
348 return 0
349
349
350
350
351 def format_screen(strng):
351 def format_screen(strng):
352 """Format a string for screen printing.
352 """Format a string for screen printing.
353
353
354 This removes some latex-type format codes."""
354 This removes some latex-type format codes."""
355 # Paragraph continue
355 # Paragraph continue
356 par_re = re.compile(r'\\$',re.MULTILINE)
356 par_re = re.compile(r'\\$',re.MULTILINE)
357 strng = par_re.sub('',strng)
357 strng = par_re.sub('',strng)
358 return strng
358 return strng
359
359
360
360
361 def dedent(text):
361 def dedent(text):
362 """Equivalent of textwrap.dedent that ignores unindented first line.
362 """Equivalent of textwrap.dedent that ignores unindented first line.
363
363
364 This means it will still dedent strings like:
364 This means it will still dedent strings like:
365 '''foo
365 '''foo
366 is a bar
366 is a bar
367 '''
367 '''
368
368
369 For use in wrap_paragraphs.
369 For use in wrap_paragraphs.
370 """
370 """
371
371
372 if text.startswith('\n'):
372 if text.startswith('\n'):
373 # text starts with blank line, don't ignore the first line
373 # text starts with blank line, don't ignore the first line
374 return textwrap.dedent(text)
374 return textwrap.dedent(text)
375
375
376 # split first line
376 # split first line
377 splits = text.split('\n',1)
377 splits = text.split('\n',1)
378 if len(splits) == 1:
378 if len(splits) == 1:
379 # only one line
379 # only one line
380 return textwrap.dedent(text)
380 return textwrap.dedent(text)
381
381
382 first, rest = splits
382 first, rest = splits
383 # dedent everything but the first line
383 # dedent everything but the first line
384 rest = textwrap.dedent(rest)
384 rest = textwrap.dedent(rest)
385 return '\n'.join([first, rest])
385 return '\n'.join([first, rest])
386
386
387
387
388 def wrap_paragraphs(text, ncols=80):
388 def wrap_paragraphs(text, ncols=80):
389 """Wrap multiple paragraphs to fit a specified width.
389 """Wrap multiple paragraphs to fit a specified width.
390
390
391 This is equivalent to textwrap.wrap, but with support for multiple
391 This is equivalent to textwrap.wrap, but with support for multiple
392 paragraphs, as separated by empty lines.
392 paragraphs, as separated by empty lines.
393
393
394 Returns
394 Returns
395 -------
395 -------
396
396
397 list of complete paragraphs, wrapped to fill `ncols` columns.
397 list of complete paragraphs, wrapped to fill `ncols` columns.
398 """
398 """
399 paragraph_re = re.compile(r'\n(\s*\n)+', re.MULTILINE)
399 paragraph_re = re.compile(r'\n(\s*\n)+', re.MULTILINE)
400 text = dedent(text).strip()
400 text = dedent(text).strip()
401 paragraphs = paragraph_re.split(text)[::2] # every other entry is space
401 paragraphs = paragraph_re.split(text)[::2] # every other entry is space
402 out_ps = []
402 out_ps = []
403 indent_re = re.compile(r'\n\s+', re.MULTILINE)
403 indent_re = re.compile(r'\n\s+', re.MULTILINE)
404 for p in paragraphs:
404 for p in paragraphs:
405 # presume indentation that survives dedent is meaningful formatting,
405 # presume indentation that survives dedent is meaningful formatting,
406 # so don't fill unless text is flush.
406 # so don't fill unless text is flush.
407 if indent_re.search(p) is None:
407 if indent_re.search(p) is None:
408 # wrap paragraph
408 # wrap paragraph
409 p = textwrap.fill(p, ncols)
409 p = textwrap.fill(p, ncols)
410 out_ps.append(p)
410 out_ps.append(p)
411 return out_ps
411 return out_ps
412
412
413
413
414 def long_substr(data):
414 def long_substr(data):
415 """Return the longest common substring in a list of strings.
415 """Return the longest common substring in a list of strings.
416
416
417 Credit: http://stackoverflow.com/questions/2892931/longest-common-substring-from-more-than-two-strings-python
417 Credit: http://stackoverflow.com/questions/2892931/longest-common-substring-from-more-than-two-strings-python
418 """
418 """
419 substr = ''
419 substr = ''
420 if len(data) > 1 and len(data[0]) > 0:
420 if len(data) > 1 and len(data[0]) > 0:
421 for i in range(len(data[0])):
421 for i in range(len(data[0])):
422 for j in range(len(data[0])-i+1):
422 for j in range(len(data[0])-i+1):
423 if j > len(substr) and all(data[0][i:i+j] in x for x in data):
423 if j > len(substr) and all(data[0][i:i+j] in x for x in data):
424 substr = data[0][i:i+j]
424 substr = data[0][i:i+j]
425 elif len(data) == 1:
425 elif len(data) == 1:
426 substr = data[0]
426 substr = data[0]
427 return substr
427 return substr
428
428
429
429
430 def strip_email_quotes(text):
430 def strip_email_quotes(text):
431 """Strip leading email quotation characters ('>').
431 """Strip leading email quotation characters ('>').
432
432
433 Removes any combination of leading '>' interspersed with whitespace that
433 Removes any combination of leading '>' interspersed with whitespace that
434 appears *identically* in all lines of the input text.
434 appears *identically* in all lines of the input text.
435
435
436 Parameters
436 Parameters
437 ----------
437 ----------
438 text : str
438 text : str
439
439
440 Examples
440 Examples
441 --------
441 --------
442
442
443 Simple uses::
443 Simple uses::
444
444
445 In [2]: strip_email_quotes('> > text')
445 In [2]: strip_email_quotes('> > text')
446 Out[2]: 'text'
446 Out[2]: 'text'
447
447
448 In [3]: strip_email_quotes('> > text\\n> > more')
448 In [3]: strip_email_quotes('> > text\\n> > more')
449 Out[3]: 'text\\nmore'
449 Out[3]: 'text\\nmore'
450
450
451 Note how only the common prefix that appears in all lines is stripped::
451 Note how only the common prefix that appears in all lines is stripped::
452
452
453 In [4]: strip_email_quotes('> > text\\n> > more\\n> more...')
453 In [4]: strip_email_quotes('> > text\\n> > more\\n> more...')
454 Out[4]: '> text\\n> more\\nmore...'
454 Out[4]: '> text\\n> more\\nmore...'
455
455
456 So if any line has no quote marks ('>') , then none are stripped from any
456 So if any line has no quote marks ('>') , then none are stripped from any
457 of them ::
457 of them ::
458
458
459 In [5]: strip_email_quotes('> > text\\n> > more\\nlast different')
459 In [5]: strip_email_quotes('> > text\\n> > more\\nlast different')
460 Out[5]: '> > text\\n> > more\\nlast different'
460 Out[5]: '> > text\\n> > more\\nlast different'
461 """
461 """
462 lines = text.splitlines()
462 lines = text.splitlines()
463 matches = set()
463 matches = set()
464 for line in lines:
464 for line in lines:
465 prefix = re.match(r'^(\s*>[ >]*)', line)
465 prefix = re.match(r'^(\s*>[ >]*)', line)
466 if prefix:
466 if prefix:
467 matches.add(prefix.group(1))
467 matches.add(prefix.group(1))
468 else:
468 else:
469 break
469 break
470 else:
470 else:
471 prefix = long_substr(list(matches))
471 prefix = long_substr(list(matches))
472 if prefix:
472 if prefix:
473 strip = len(prefix)
473 strip = len(prefix)
474 text = '\n'.join([ ln[strip:] for ln in lines])
474 text = '\n'.join([ ln[strip:] for ln in lines])
475 return text
475 return text
476
476
477 def strip_ansi(source):
477 def strip_ansi(source):
478 """
478 """
479 Remove ansi escape codes from text.
479 Remove ansi escape codes from text.
480
480
481 Parameters
481 Parameters
482 ----------
482 ----------
483 source : str
483 source : str
484 Source to remove the ansi from
484 Source to remove the ansi from
485 """
485 """
486 return re.sub(r'\033\[(\d|;)+?m', '', source)
486 return re.sub(r'\033\[(\d|;)+?m', '', source)
487
487
488
488
489 class EvalFormatter(Formatter):
489 class EvalFormatter(Formatter):
490 """A String Formatter that allows evaluation of simple expressions.
490 """A String Formatter that allows evaluation of simple expressions.
491
491
492 Note that this version interprets a : as specifying a format string (as per
492 Note that this version interprets a : as specifying a format string (as per
493 standard string formatting), so if slicing is required, you must explicitly
493 standard string formatting), so if slicing is required, you must explicitly
494 create a slice.
494 create a slice.
495
495
496 This is to be used in templating cases, such as the parallel batch
496 This is to be used in templating cases, such as the parallel batch
497 script templates, where simple arithmetic on arguments is useful.
497 script templates, where simple arithmetic on arguments is useful.
498
498
499 Examples
499 Examples
500 --------
500 --------
501 ::
501 ::
502
502
503 In [1]: f = EvalFormatter()
503 In [1]: f = EvalFormatter()
504 In [2]: f.format('{n//4}', n=8)
504 In [2]: f.format('{n//4}', n=8)
505 Out[2]: '2'
505 Out[2]: '2'
506
506
507 In [3]: f.format("{greeting[slice(2,4)]}", greeting="Hello")
507 In [3]: f.format("{greeting[slice(2,4)]}", greeting="Hello")
508 Out[3]: 'll'
508 Out[3]: 'll'
509 """
509 """
510 def get_field(self, name, args, kwargs):
510 def get_field(self, name, args, kwargs):
511 v = eval(name, kwargs)
511 v = eval(name, kwargs)
512 return v, name
512 return v, name
513
513
514 #XXX: As of Python 3.4, the format string parsing no longer splits on a colon
514 #XXX: As of Python 3.4, the format string parsing no longer splits on a colon
515 # inside [], so EvalFormatter can handle slicing. Once we only support 3.4 and
515 # inside [], so EvalFormatter can handle slicing. Once we only support 3.4 and
516 # above, it should be possible to remove FullEvalFormatter.
516 # above, it should be possible to remove FullEvalFormatter.
517
517
518 class FullEvalFormatter(Formatter):
518 class FullEvalFormatter(Formatter):
519 """A String Formatter that allows evaluation of simple expressions.
519 """A String Formatter that allows evaluation of simple expressions.
520
520
521 Any time a format key is not found in the kwargs,
521 Any time a format key is not found in the kwargs,
522 it will be tried as an expression in the kwargs namespace.
522 it will be tried as an expression in the kwargs namespace.
523
523
524 Note that this version allows slicing using [1:2], so you cannot specify
524 Note that this version allows slicing using [1:2], so you cannot specify
525 a format string. Use :class:`EvalFormatter` to permit format strings.
525 a format string. Use :class:`EvalFormatter` to permit format strings.
526
526
527 Examples
527 Examples
528 --------
528 --------
529 ::
529 ::
530
530
531 In [1]: f = FullEvalFormatter()
531 In [1]: f = FullEvalFormatter()
532 In [2]: f.format('{n//4}', n=8)
532 In [2]: f.format('{n//4}', n=8)
533 Out[2]: '2'
533 Out[2]: '2'
534
534
535 In [3]: f.format('{list(range(5))[2:4]}')
535 In [3]: f.format('{list(range(5))[2:4]}')
536 Out[3]: '[2, 3]'
536 Out[3]: '[2, 3]'
537
537
538 In [4]: f.format('{3*2}')
538 In [4]: f.format('{3*2}')
539 Out[4]: '6'
539 Out[4]: '6'
540 """
540 """
541 # copied from Formatter._vformat with minor changes to allow eval
541 # copied from Formatter._vformat with minor changes to allow eval
542 # and replace the format_spec code with slicing
542 # and replace the format_spec code with slicing
543 def vformat(self, format_string, args, kwargs):
543 def vformat(self, format_string, args, kwargs):
544 result = []
544 result = []
545 for literal_text, field_name, format_spec, conversion in \
545 for literal_text, field_name, format_spec, conversion in \
546 self.parse(format_string):
546 self.parse(format_string):
547
547
548 # output the literal text
548 # output the literal text
549 if literal_text:
549 if literal_text:
550 result.append(literal_text)
550 result.append(literal_text)
551
551
552 # if there's a field, output it
552 # if there's a field, output it
553 if field_name is not None:
553 if field_name is not None:
554 # this is some markup, find the object and do
554 # this is some markup, find the object and do
555 # the formatting
555 # the formatting
556
556
557 if format_spec:
557 if format_spec:
558 # override format spec, to allow slicing:
558 # override format spec, to allow slicing:
559 field_name = ':'.join([field_name, format_spec])
559 field_name = ':'.join([field_name, format_spec])
560
560
561 # eval the contents of the field for the object
561 # eval the contents of the field for the object
562 # to be formatted
562 # to be formatted
563 obj = eval(field_name, kwargs)
563 obj = eval(field_name, kwargs)
564
564
565 # do any conversion on the resulting object
565 # do any conversion on the resulting object
566 obj = self.convert_field(obj, conversion)
566 obj = self.convert_field(obj, conversion)
567
567
568 # format the object and append to the result
568 # format the object and append to the result
569 result.append(self.format_field(obj, ''))
569 result.append(self.format_field(obj, ''))
570
570
571 return u''.join(py3compat.cast_unicode(s) for s in result)
571 return u''.join(py3compat.cast_unicode(s) for s in result)
572
572
573
573
574 class DollarFormatter(FullEvalFormatter):
574 class DollarFormatter(FullEvalFormatter):
575 """Formatter allowing Itpl style $foo replacement, for names and attribute
575 """Formatter allowing Itpl style $foo replacement, for names and attribute
576 access only. Standard {foo} replacement also works, and allows full
576 access only. Standard {foo} replacement also works, and allows full
577 evaluation of its arguments.
577 evaluation of its arguments.
578
578
579 Examples
579 Examples
580 --------
580 --------
581 ::
581 ::
582
582
583 In [1]: f = DollarFormatter()
583 In [1]: f = DollarFormatter()
584 In [2]: f.format('{n//4}', n=8)
584 In [2]: f.format('{n//4}', n=8)
585 Out[2]: '2'
585 Out[2]: '2'
586
586
587 In [3]: f.format('23 * 76 is $result', result=23*76)
587 In [3]: f.format('23 * 76 is $result', result=23*76)
588 Out[3]: '23 * 76 is 1748'
588 Out[3]: '23 * 76 is 1748'
589
589
590 In [4]: f.format('$a or {b}', a=1, b=2)
590 In [4]: f.format('$a or {b}', a=1, b=2)
591 Out[4]: '1 or 2'
591 Out[4]: '1 or 2'
592 """
592 """
593 _dollar_pattern = re.compile("(.*?)\$(\$?[\w\.]+)")
593 _dollar_pattern = re.compile("(.*?)\$(\$?[\w\.]+)")
594 def parse(self, fmt_string):
594 def parse(self, fmt_string):
595 for literal_txt, field_name, format_spec, conversion \
595 for literal_txt, field_name, format_spec, conversion \
596 in Formatter.parse(self, fmt_string):
596 in Formatter.parse(self, fmt_string):
597
597
598 # Find $foo patterns in the literal text.
598 # Find $foo patterns in the literal text.
599 continue_from = 0
599 continue_from = 0
600 txt = ""
600 txt = ""
601 for m in self._dollar_pattern.finditer(literal_txt):
601 for m in self._dollar_pattern.finditer(literal_txt):
602 new_txt, new_field = m.group(1,2)
602 new_txt, new_field = m.group(1,2)
603 # $$foo --> $foo
603 # $$foo --> $foo
604 if new_field.startswith("$"):
604 if new_field.startswith("$"):
605 txt += new_txt + new_field
605 txt += new_txt + new_field
606 else:
606 else:
607 yield (txt + new_txt, new_field, "", None)
607 yield (txt + new_txt, new_field, "", None)
608 txt = ""
608 txt = ""
609 continue_from = m.end()
609 continue_from = m.end()
610
610
611 # Re-yield the {foo} style pattern
611 # Re-yield the {foo} style pattern
612 yield (txt + literal_txt[continue_from:], field_name, format_spec, conversion)
612 yield (txt + literal_txt[continue_from:], field_name, format_spec, conversion)
613
613
614 #-----------------------------------------------------------------------------
614 #-----------------------------------------------------------------------------
615 # Utils to columnize a list of string
615 # Utils to columnize a list of string
616 #-----------------------------------------------------------------------------
616 #-----------------------------------------------------------------------------
617
617
618 def _col_chunks(l, max_rows, row_first=False):
618 def _col_chunks(l, max_rows, row_first=False):
619 """Yield successive max_rows-sized column chunks from l."""
619 """Yield successive max_rows-sized column chunks from l."""
620 if row_first:
620 if row_first:
621 ncols = (len(l) // max_rows) + (len(l) % max_rows > 0)
621 ncols = (len(l) // max_rows) + (len(l) % max_rows > 0)
622 for i in py3compat.xrange(ncols):
622 for i in range(ncols):
623 yield [l[j] for j in py3compat.xrange(i, len(l), ncols)]
623 yield [l[j] for j in range(i, len(l), ncols)]
624 else:
624 else:
625 for i in py3compat.xrange(0, len(l), max_rows):
625 for i in range(0, len(l), max_rows):
626 yield l[i:(i + max_rows)]
626 yield l[i:(i + max_rows)]
627
627
628
628
629 def _find_optimal(rlist, row_first=False, separator_size=2, displaywidth=80):
629 def _find_optimal(rlist, row_first=False, separator_size=2, displaywidth=80):
630 """Calculate optimal info to columnize a list of string"""
630 """Calculate optimal info to columnize a list of string"""
631 for max_rows in range(1, len(rlist) + 1):
631 for max_rows in range(1, len(rlist) + 1):
632 col_widths = list(map(max, _col_chunks(rlist, max_rows, row_first)))
632 col_widths = list(map(max, _col_chunks(rlist, max_rows, row_first)))
633 sumlength = sum(col_widths)
633 sumlength = sum(col_widths)
634 ncols = len(col_widths)
634 ncols = len(col_widths)
635 if sumlength + separator_size * (ncols - 1) <= displaywidth:
635 if sumlength + separator_size * (ncols - 1) <= displaywidth:
636 break
636 break
637 return {'num_columns': ncols,
637 return {'num_columns': ncols,
638 'optimal_separator_width': (displaywidth - sumlength) // (ncols - 1) if (ncols - 1) else 0,
638 'optimal_separator_width': (displaywidth - sumlength) // (ncols - 1) if (ncols - 1) else 0,
639 'max_rows': max_rows,
639 'max_rows': max_rows,
640 'column_widths': col_widths
640 'column_widths': col_widths
641 }
641 }
642
642
643
643
644 def _get_or_default(mylist, i, default=None):
644 def _get_or_default(mylist, i, default=None):
645 """return list item number, or default if don't exist"""
645 """return list item number, or default if don't exist"""
646 if i >= len(mylist):
646 if i >= len(mylist):
647 return default
647 return default
648 else :
648 else :
649 return mylist[i]
649 return mylist[i]
650
650
651
651
652 def compute_item_matrix(items, row_first=False, empty=None, *args, **kwargs) :
652 def compute_item_matrix(items, row_first=False, empty=None, *args, **kwargs) :
653 """Returns a nested list, and info to columnize items
653 """Returns a nested list, and info to columnize items
654
654
655 Parameters
655 Parameters
656 ----------
656 ----------
657
657
658 items
658 items
659 list of strings to columize
659 list of strings to columize
660 row_first : (default False)
660 row_first : (default False)
661 Whether to compute columns for a row-first matrix instead of
661 Whether to compute columns for a row-first matrix instead of
662 column-first (default).
662 column-first (default).
663 empty : (default None)
663 empty : (default None)
664 default value to fill list if needed
664 default value to fill list if needed
665 separator_size : int (default=2)
665 separator_size : int (default=2)
666 How much caracters will be used as a separation between each columns.
666 How much caracters will be used as a separation between each columns.
667 displaywidth : int (default=80)
667 displaywidth : int (default=80)
668 The width of the area onto wich the columns should enter
668 The width of the area onto wich the columns should enter
669
669
670 Returns
670 Returns
671 -------
671 -------
672
672
673 strings_matrix
673 strings_matrix
674
674
675 nested list of string, the outer most list contains as many list as
675 nested list of string, the outer most list contains as many list as
676 rows, the innermost lists have each as many element as colums. If the
676 rows, the innermost lists have each as many element as colums. If the
677 total number of elements in `items` does not equal the product of
677 total number of elements in `items` does not equal the product of
678 rows*columns, the last element of some lists are filled with `None`.
678 rows*columns, the last element of some lists are filled with `None`.
679
679
680 dict_info
680 dict_info
681 some info to make columnize easier:
681 some info to make columnize easier:
682
682
683 num_columns
683 num_columns
684 number of columns
684 number of columns
685 max_rows
685 max_rows
686 maximum number of rows (final number may be less)
686 maximum number of rows (final number may be less)
687 column_widths
687 column_widths
688 list of with of each columns
688 list of with of each columns
689 optimal_separator_width
689 optimal_separator_width
690 best separator width between columns
690 best separator width between columns
691
691
692 Examples
692 Examples
693 --------
693 --------
694 ::
694 ::
695
695
696 In [1]: l = ['aaa','b','cc','d','eeeee','f','g','h','i','j','k','l']
696 In [1]: l = ['aaa','b','cc','d','eeeee','f','g','h','i','j','k','l']
697 In [2]: list, info = compute_item_matrix(l, displaywidth=12)
697 In [2]: list, info = compute_item_matrix(l, displaywidth=12)
698 In [3]: list
698 In [3]: list
699 Out[3]: [['aaa', 'f', 'k'], ['b', 'g', 'l'], ['cc', 'h', None], ['d', 'i', None], ['eeeee', 'j', None]]
699 Out[3]: [['aaa', 'f', 'k'], ['b', 'g', 'l'], ['cc', 'h', None], ['d', 'i', None], ['eeeee', 'j', None]]
700 In [4]: ideal = {'num_columns': 3, 'column_widths': [5, 1, 1], 'optimal_separator_width': 2, 'max_rows': 5}
700 In [4]: ideal = {'num_columns': 3, 'column_widths': [5, 1, 1], 'optimal_separator_width': 2, 'max_rows': 5}
701 In [5]: all((info[k] == ideal[k] for k in ideal.keys()))
701 In [5]: all((info[k] == ideal[k] for k in ideal.keys()))
702 Out[5]: True
702 Out[5]: True
703 """
703 """
704 info = _find_optimal(list(map(len, items)), row_first, *args, **kwargs)
704 info = _find_optimal(list(map(len, items)), row_first, *args, **kwargs)
705 nrow, ncol = info['max_rows'], info['num_columns']
705 nrow, ncol = info['max_rows'], info['num_columns']
706 if row_first:
706 if row_first:
707 return ([[_get_or_default(items, r * ncol + c, default=empty) for c in range(ncol)] for r in range(nrow)], info)
707 return ([[_get_or_default(items, r * ncol + c, default=empty) for c in range(ncol)] for r in range(nrow)], info)
708 else:
708 else:
709 return ([[_get_or_default(items, c * nrow + r, default=empty) for c in range(ncol)] for r in range(nrow)], info)
709 return ([[_get_or_default(items, c * nrow + r, default=empty) for c in range(ncol)] for r in range(nrow)], info)
710
710
711
711
712 def columnize(items, row_first=False, separator=' ', displaywidth=80, spread=False):
712 def columnize(items, row_first=False, separator=' ', displaywidth=80, spread=False):
713 """ Transform a list of strings into a single string with columns.
713 """ Transform a list of strings into a single string with columns.
714
714
715 Parameters
715 Parameters
716 ----------
716 ----------
717 items : sequence of strings
717 items : sequence of strings
718 The strings to process.
718 The strings to process.
719
719
720 row_first : (default False)
720 row_first : (default False)
721 Whether to compute columns for a row-first matrix instead of
721 Whether to compute columns for a row-first matrix instead of
722 column-first (default).
722 column-first (default).
723
723
724 separator : str, optional [default is two spaces]
724 separator : str, optional [default is two spaces]
725 The string that separates columns.
725 The string that separates columns.
726
726
727 displaywidth : int, optional [default is 80]
727 displaywidth : int, optional [default is 80]
728 Width of the display in number of characters.
728 Width of the display in number of characters.
729
729
730 Returns
730 Returns
731 -------
731 -------
732 The formatted string.
732 The formatted string.
733 """
733 """
734 if not items:
734 if not items:
735 return '\n'
735 return '\n'
736 matrix, info = compute_item_matrix(items, row_first=row_first, separator_size=len(separator), displaywidth=displaywidth)
736 matrix, info = compute_item_matrix(items, row_first=row_first, separator_size=len(separator), displaywidth=displaywidth)
737 if spread:
737 if spread:
738 separator = separator.ljust(int(info['optimal_separator_width']))
738 separator = separator.ljust(int(info['optimal_separator_width']))
739 fmatrix = [filter(None, x) for x in matrix]
739 fmatrix = [filter(None, x) for x in matrix]
740 sjoin = lambda x : separator.join([ y.ljust(w, ' ') for y, w in zip(x, info['column_widths'])])
740 sjoin = lambda x : separator.join([ y.ljust(w, ' ') for y, w in zip(x, info['column_widths'])])
741 return '\n'.join(map(sjoin, fmatrix))+'\n'
741 return '\n'.join(map(sjoin, fmatrix))+'\n'
742
742
743
743
744 def get_text_list(list_, last_sep=' and ', sep=", ", wrap_item_with=""):
744 def get_text_list(list_, last_sep=' and ', sep=", ", wrap_item_with=""):
745 """
745 """
746 Return a string with a natural enumeration of items
746 Return a string with a natural enumeration of items
747
747
748 >>> get_text_list(['a', 'b', 'c', 'd'])
748 >>> get_text_list(['a', 'b', 'c', 'd'])
749 'a, b, c and d'
749 'a, b, c and d'
750 >>> get_text_list(['a', 'b', 'c'], ' or ')
750 >>> get_text_list(['a', 'b', 'c'], ' or ')
751 'a, b or c'
751 'a, b or c'
752 >>> get_text_list(['a', 'b', 'c'], ', ')
752 >>> get_text_list(['a', 'b', 'c'], ', ')
753 'a, b, c'
753 'a, b, c'
754 >>> get_text_list(['a', 'b'], ' or ')
754 >>> get_text_list(['a', 'b'], ' or ')
755 'a or b'
755 'a or b'
756 >>> get_text_list(['a'])
756 >>> get_text_list(['a'])
757 'a'
757 'a'
758 >>> get_text_list([])
758 >>> get_text_list([])
759 ''
759 ''
760 >>> get_text_list(['a', 'b'], wrap_item_with="`")
760 >>> get_text_list(['a', 'b'], wrap_item_with="`")
761 '`a` and `b`'
761 '`a` and `b`'
762 >>> get_text_list(['a', 'b', 'c', 'd'], " = ", sep=" + ")
762 >>> get_text_list(['a', 'b', 'c', 'd'], " = ", sep=" + ")
763 'a + b + c = d'
763 'a + b + c = d'
764 """
764 """
765 if len(list_) == 0:
765 if len(list_) == 0:
766 return ''
766 return ''
767 if wrap_item_with:
767 if wrap_item_with:
768 list_ = ['%s%s%s' % (wrap_item_with, item, wrap_item_with) for
768 list_ = ['%s%s%s' % (wrap_item_with, item, wrap_item_with) for
769 item in list_]
769 item in list_]
770 if len(list_) == 1:
770 if len(list_) == 1:
771 return list_[0]
771 return list_[0]
772 return '%s%s%s' % (
772 return '%s%s%s' % (
773 sep.join(i for i in list_[:-1]),
773 sep.join(i for i in list_[:-1]),
774 last_sep, list_[-1])
774 last_sep, list_[-1])
@@ -1,118 +1,116 b''
1 # encoding: utf-8
1 # encoding: utf-8
2 """
2 """
3 Utilities for timing code execution.
3 Utilities for timing code execution.
4 """
4 """
5
5
6 #-----------------------------------------------------------------------------
6 #-----------------------------------------------------------------------------
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 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14 # Imports
14 # Imports
15 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
16
16
17 import time
17 import time
18
18
19 from .py3compat import xrange
20
21 #-----------------------------------------------------------------------------
19 #-----------------------------------------------------------------------------
22 # Code
20 # Code
23 #-----------------------------------------------------------------------------
21 #-----------------------------------------------------------------------------
24
22
25 # If possible (Unix), use the resource module instead of time.clock()
23 # If possible (Unix), use the resource module instead of time.clock()
26 try:
24 try:
27 import resource
25 import resource
28 def clocku():
26 def clocku():
29 """clocku() -> floating point number
27 """clocku() -> floating point number
30
28
31 Return the *USER* CPU time in seconds since the start of the process.
29 Return the *USER* CPU time in seconds since the start of the process.
32 This is done via a call to resource.getrusage, so it avoids the
30 This is done via a call to resource.getrusage, so it avoids the
33 wraparound problems in time.clock()."""
31 wraparound problems in time.clock()."""
34
32
35 return resource.getrusage(resource.RUSAGE_SELF)[0]
33 return resource.getrusage(resource.RUSAGE_SELF)[0]
36
34
37 def clocks():
35 def clocks():
38 """clocks() -> floating point number
36 """clocks() -> floating point number
39
37
40 Return the *SYSTEM* CPU time in seconds since the start of the process.
38 Return the *SYSTEM* CPU time in seconds since the start of the process.
41 This is done via a call to resource.getrusage, so it avoids the
39 This is done via a call to resource.getrusage, so it avoids the
42 wraparound problems in time.clock()."""
40 wraparound problems in time.clock()."""
43
41
44 return resource.getrusage(resource.RUSAGE_SELF)[1]
42 return resource.getrusage(resource.RUSAGE_SELF)[1]
45
43
46 def clock():
44 def clock():
47 """clock() -> floating point number
45 """clock() -> floating point number
48
46
49 Return the *TOTAL USER+SYSTEM* CPU time in seconds since the start of
47 Return the *TOTAL USER+SYSTEM* CPU time in seconds since the start of
50 the process. This is done via a call to resource.getrusage, so it
48 the process. This is done via a call to resource.getrusage, so it
51 avoids the wraparound problems in time.clock()."""
49 avoids the wraparound problems in time.clock()."""
52
50
53 u,s = resource.getrusage(resource.RUSAGE_SELF)[:2]
51 u,s = resource.getrusage(resource.RUSAGE_SELF)[:2]
54 return u+s
52 return u+s
55
53
56 def clock2():
54 def clock2():
57 """clock2() -> (t_user,t_system)
55 """clock2() -> (t_user,t_system)
58
56
59 Similar to clock(), but return a tuple of user/system times."""
57 Similar to clock(), but return a tuple of user/system times."""
60 return resource.getrusage(resource.RUSAGE_SELF)[:2]
58 return resource.getrusage(resource.RUSAGE_SELF)[:2]
61 except ImportError:
59 except ImportError:
62 # There is no distinction of user/system time under windows, so we just use
60 # There is no distinction of user/system time under windows, so we just use
63 # time.clock() for everything...
61 # time.clock() for everything...
64 clocku = clocks = clock = time.clock
62 clocku = clocks = clock = time.clock
65 def clock2():
63 def clock2():
66 """Under windows, system CPU time can't be measured.
64 """Under windows, system CPU time can't be measured.
67
65
68 This just returns clock() and zero."""
66 This just returns clock() and zero."""
69 return time.clock(),0.0
67 return time.clock(),0.0
70
68
71
69
72 def timings_out(reps,func,*args,**kw):
70 def timings_out(reps,func,*args,**kw):
73 """timings_out(reps,func,*args,**kw) -> (t_total,t_per_call,output)
71 """timings_out(reps,func,*args,**kw) -> (t_total,t_per_call,output)
74
72
75 Execute a function reps times, return a tuple with the elapsed total
73 Execute a function reps times, return a tuple with the elapsed total
76 CPU time in seconds, the time per call and the function's output.
74 CPU time in seconds, the time per call and the function's output.
77
75
78 Under Unix, the return value is the sum of user+system time consumed by
76 Under Unix, the return value is the sum of user+system time consumed by
79 the process, computed via the resource module. This prevents problems
77 the process, computed via the resource module. This prevents problems
80 related to the wraparound effect which the time.clock() function has.
78 related to the wraparound effect which the time.clock() function has.
81
79
82 Under Windows the return value is in wall clock seconds. See the
80 Under Windows the return value is in wall clock seconds. See the
83 documentation for the time module for more details."""
81 documentation for the time module for more details."""
84
82
85 reps = int(reps)
83 reps = int(reps)
86 assert reps >=1, 'reps must be >= 1'
84 assert reps >=1, 'reps must be >= 1'
87 if reps==1:
85 if reps==1:
88 start = clock()
86 start = clock()
89 out = func(*args,**kw)
87 out = func(*args,**kw)
90 tot_time = clock()-start
88 tot_time = clock()-start
91 else:
89 else:
92 rng = xrange(reps-1) # the last time is executed separately to store output
90 rng = range(reps-1) # the last time is executed separately to store output
93 start = clock()
91 start = clock()
94 for dummy in rng: func(*args,**kw)
92 for dummy in rng: func(*args,**kw)
95 out = func(*args,**kw) # one last time
93 out = func(*args,**kw) # one last time
96 tot_time = clock()-start
94 tot_time = clock()-start
97 av_time = tot_time / reps
95 av_time = tot_time / reps
98 return tot_time,av_time,out
96 return tot_time,av_time,out
99
97
100
98
101 def timings(reps,func,*args,**kw):
99 def timings(reps,func,*args,**kw):
102 """timings(reps,func,*args,**kw) -> (t_total,t_per_call)
100 """timings(reps,func,*args,**kw) -> (t_total,t_per_call)
103
101
104 Execute a function reps times, return a tuple with the elapsed total CPU
102 Execute a function reps times, return a tuple with the elapsed total CPU
105 time in seconds and the time per call. These are just the first two values
103 time in seconds and the time per call. These are just the first two values
106 in timings_out()."""
104 in timings_out()."""
107
105
108 return timings_out(reps,func,*args,**kw)[0:2]
106 return timings_out(reps,func,*args,**kw)[0:2]
109
107
110
108
111 def timing(func,*args,**kw):
109 def timing(func,*args,**kw):
112 """timing(func,*args,**kw) -> t_total
110 """timing(func,*args,**kw) -> t_total
113
111
114 Execute a function once, return the elapsed total CPU time in
112 Execute a function once, return the elapsed total CPU time in
115 seconds. This is just the first value in timings_out()."""
113 seconds. This is just the first value in timings_out()."""
116
114
117 return timings_out(1,func,*args,**kw)[0]
115 return timings_out(1,func,*args,**kw)[0]
118
116
@@ -1,112 +1,111 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Support for wildcard pattern matching in object inspection.
2 """Support for wildcard pattern matching in object inspection.
3
3
4 Authors
4 Authors
5 -------
5 -------
6 - JΓΆrgen Stenarson <jorgen.stenarson@bostream.nu>
6 - JΓΆrgen Stenarson <jorgen.stenarson@bostream.nu>
7 - Thomas Kluyver
7 - Thomas Kluyver
8 """
8 """
9
9
10 #*****************************************************************************
10 #*****************************************************************************
11 # Copyright (C) 2005 JΓΆrgen Stenarson <jorgen.stenarson@bostream.nu>
11 # Copyright (C) 2005 JΓΆrgen Stenarson <jorgen.stenarson@bostream.nu>
12 #
12 #
13 # Distributed under the terms of the BSD License. The full license is in
13 # Distributed under the terms of the BSD License. The full license is in
14 # the file COPYING, distributed as part of this software.
14 # the file COPYING, distributed as part of this software.
15 #*****************************************************************************
15 #*****************************************************************************
16
16
17 import re
17 import re
18 import types
18 import types
19
19
20 from IPython.utils.dir2 import dir2
20 from IPython.utils.dir2 import dir2
21 from .py3compat import iteritems
22
21
23 def create_typestr2type_dicts(dont_include_in_type2typestr=["lambda"]):
22 def create_typestr2type_dicts(dont_include_in_type2typestr=["lambda"]):
24 """Return dictionaries mapping lower case typename (e.g. 'tuple') to type
23 """Return dictionaries mapping lower case typename (e.g. 'tuple') to type
25 objects from the types package, and vice versa."""
24 objects from the types package, and vice versa."""
26 typenamelist = [tname for tname in dir(types) if tname.endswith("Type")]
25 typenamelist = [tname for tname in dir(types) if tname.endswith("Type")]
27 typestr2type, type2typestr = {}, {}
26 typestr2type, type2typestr = {}, {}
28
27
29 for tname in typenamelist:
28 for tname in typenamelist:
30 name = tname[:-4].lower() # Cut 'Type' off the end of the name
29 name = tname[:-4].lower() # Cut 'Type' off the end of the name
31 obj = getattr(types, tname)
30 obj = getattr(types, tname)
32 typestr2type[name] = obj
31 typestr2type[name] = obj
33 if name not in dont_include_in_type2typestr:
32 if name not in dont_include_in_type2typestr:
34 type2typestr[obj] = name
33 type2typestr[obj] = name
35 return typestr2type, type2typestr
34 return typestr2type, type2typestr
36
35
37 typestr2type, type2typestr = create_typestr2type_dicts()
36 typestr2type, type2typestr = create_typestr2type_dicts()
38
37
39 def is_type(obj, typestr_or_type):
38 def is_type(obj, typestr_or_type):
40 """is_type(obj, typestr_or_type) verifies if obj is of a certain type. It
39 """is_type(obj, typestr_or_type) verifies if obj is of a certain type. It
41 can take strings or actual python types for the second argument, i.e.
40 can take strings or actual python types for the second argument, i.e.
42 'tuple'<->TupleType. 'all' matches all types.
41 'tuple'<->TupleType. 'all' matches all types.
43
42
44 TODO: Should be extended for choosing more than one type."""
43 TODO: Should be extended for choosing more than one type."""
45 if typestr_or_type == "all":
44 if typestr_or_type == "all":
46 return True
45 return True
47 if type(typestr_or_type) == type:
46 if type(typestr_or_type) == type:
48 test_type = typestr_or_type
47 test_type = typestr_or_type
49 else:
48 else:
50 test_type = typestr2type.get(typestr_or_type, False)
49 test_type = typestr2type.get(typestr_or_type, False)
51 if test_type:
50 if test_type:
52 return isinstance(obj, test_type)
51 return isinstance(obj, test_type)
53 return False
52 return False
54
53
55 def show_hidden(str, show_all=False):
54 def show_hidden(str, show_all=False):
56 """Return true for strings starting with single _ if show_all is true."""
55 """Return true for strings starting with single _ if show_all is true."""
57 return show_all or str.startswith("__") or not str.startswith("_")
56 return show_all or str.startswith("__") or not str.startswith("_")
58
57
59 def dict_dir(obj):
58 def dict_dir(obj):
60 """Produce a dictionary of an object's attributes. Builds on dir2 by
59 """Produce a dictionary of an object's attributes. Builds on dir2 by
61 checking that a getattr() call actually succeeds."""
60 checking that a getattr() call actually succeeds."""
62 ns = {}
61 ns = {}
63 for key in dir2(obj):
62 for key in dir2(obj):
64 # This seemingly unnecessary try/except is actually needed
63 # This seemingly unnecessary try/except is actually needed
65 # because there is code out there with metaclasses that
64 # because there is code out there with metaclasses that
66 # create 'write only' attributes, where a getattr() call
65 # create 'write only' attributes, where a getattr() call
67 # will fail even if the attribute appears listed in the
66 # will fail even if the attribute appears listed in the
68 # object's dictionary. Properties can actually do the same
67 # object's dictionary. Properties can actually do the same
69 # thing. In particular, Traits use this pattern
68 # thing. In particular, Traits use this pattern
70 try:
69 try:
71 ns[key] = getattr(obj, key)
70 ns[key] = getattr(obj, key)
72 except AttributeError:
71 except AttributeError:
73 pass
72 pass
74 return ns
73 return ns
75
74
76 def filter_ns(ns, name_pattern="*", type_pattern="all", ignore_case=True,
75 def filter_ns(ns, name_pattern="*", type_pattern="all", ignore_case=True,
77 show_all=True):
76 show_all=True):
78 """Filter a namespace dictionary by name pattern and item type."""
77 """Filter a namespace dictionary by name pattern and item type."""
79 pattern = name_pattern.replace("*",".*").replace("?",".")
78 pattern = name_pattern.replace("*",".*").replace("?",".")
80 if ignore_case:
79 if ignore_case:
81 reg = re.compile(pattern+"$", re.I)
80 reg = re.compile(pattern+"$", re.I)
82 else:
81 else:
83 reg = re.compile(pattern+"$")
82 reg = re.compile(pattern+"$")
84
83
85 # Check each one matches regex; shouldn't be hidden; of correct type.
84 # Check each one matches regex; shouldn't be hidden; of correct type.
86 return dict((key,obj) for key, obj in iteritems(ns) if reg.match(key) \
85 return dict((key,obj) for key, obj in ns.items() if reg.match(key) \
87 and show_hidden(key, show_all) \
86 and show_hidden(key, show_all) \
88 and is_type(obj, type_pattern) )
87 and is_type(obj, type_pattern) )
89
88
90 def list_namespace(namespace, type_pattern, filter, ignore_case=False, show_all=False):
89 def list_namespace(namespace, type_pattern, filter, ignore_case=False, show_all=False):
91 """Return dictionary of all objects in a namespace dictionary that match
90 """Return dictionary of all objects in a namespace dictionary that match
92 type_pattern and filter."""
91 type_pattern and filter."""
93 pattern_list=filter.split(".")
92 pattern_list=filter.split(".")
94 if len(pattern_list) == 1:
93 if len(pattern_list) == 1:
95 return filter_ns(namespace, name_pattern=pattern_list[0],
94 return filter_ns(namespace, name_pattern=pattern_list[0],
96 type_pattern=type_pattern,
95 type_pattern=type_pattern,
97 ignore_case=ignore_case, show_all=show_all)
96 ignore_case=ignore_case, show_all=show_all)
98 else:
97 else:
99 # This is where we can change if all objects should be searched or
98 # This is where we can change if all objects should be searched or
100 # only modules. Just change the type_pattern to module to search only
99 # only modules. Just change the type_pattern to module to search only
101 # modules
100 # modules
102 filtered = filter_ns(namespace, name_pattern=pattern_list[0],
101 filtered = filter_ns(namespace, name_pattern=pattern_list[0],
103 type_pattern="all",
102 type_pattern="all",
104 ignore_case=ignore_case, show_all=show_all)
103 ignore_case=ignore_case, show_all=show_all)
105 results = {}
104 results = {}
106 for name, obj in iteritems(filtered):
105 for name, obj in filtered.items():
107 ns = list_namespace(dict_dir(obj), type_pattern,
106 ns = list_namespace(dict_dir(obj), type_pattern,
108 ".".join(pattern_list[1:]),
107 ".".join(pattern_list[1:]),
109 ignore_case=ignore_case, show_all=show_all)
108 ignore_case=ignore_case, show_all=show_all)
110 for inner_name, inner_obj in iteritems(ns):
109 for inner_name, inner_obj in ns.items():
111 results["%s.%s"%(name,inner_name)] = inner_obj
110 results["%s.%s"%(name,inner_name)] = inner_obj
112 return results
111 return results
General Comments 0
You need to be logged in to leave comments. Login now