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