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