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