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