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