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