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