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