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