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