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