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