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