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