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