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