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