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