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