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