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