##// END OF EJS Templates
Made InteractiveShell a SingletonConfigurable....
Brian Granger -
Show More
@@ -1,234 +1,240 b''
1 1 #!/usr/bin/env python
2 2 # encoding: utf-8
3 3 """
4 4 A base class for objects that are configurable.
5 5
6 6 Authors:
7 7
8 8 * Brian Granger
9 9 * Fernando Perez
10 10 """
11 11
12 12 #-----------------------------------------------------------------------------
13 13 # Copyright (C) 2008-2010 The IPython Development Team
14 14 #
15 15 # Distributed under the terms of the BSD License. The full license is in
16 16 # the file COPYING, distributed as part of this software.
17 17 #-----------------------------------------------------------------------------
18 18
19 19 #-----------------------------------------------------------------------------
20 20 # Imports
21 21 #-----------------------------------------------------------------------------
22 22
23 23 from copy import deepcopy
24 24 import datetime
25 25
26 26 from loader import Config
27 27 from IPython.utils.traitlets import HasTraits, Instance
28 28 from IPython.utils.text import indent
29 29
30 30
31 31 #-----------------------------------------------------------------------------
32 32 # Helper classes for Configurables
33 33 #-----------------------------------------------------------------------------
34 34
35 35
36 36 class ConfigurableError(Exception):
37 37 pass
38 38
39 39
40 40 class MultipleInstanceError(ConfigurableError):
41 41 pass
42 42
43 43 #-----------------------------------------------------------------------------
44 44 # Configurable implementation
45 45 #-----------------------------------------------------------------------------
46 46
47 47
48 48 class Configurable(HasTraits):
49 49
50 50 config = Instance(Config,(),{})
51 51 created = None
52 52
53 53 def __init__(self, **kwargs):
54 54 """Create a conigurable given a config config.
55 55
56 56 Parameters
57 57 ----------
58 58 config : Config
59 59 If this is empty, default values are used. If config is a
60 60 :class:`Config` instance, it will be used to configure the
61 61 instance.
62 62
63 63 Notes
64 64 -----
65 65 Subclasses of Configurable must call the :meth:`__init__` method of
66 66 :class:`Configurable` *before* doing anything else and using
67 67 :func:`super`::
68 68
69 69 class MyConfigurable(Configurable):
70 70 def __init__(self, config=None):
71 71 super(MyConfigurable, self).__init__(config)
72 72 # Then any other code you need to finish initialization.
73 73
74 74 This ensures that instances will be configured properly.
75 75 """
76 76 config = kwargs.pop('config', None)
77 77 if config is not None:
78 78 # We used to deepcopy, but for now we are trying to just save
79 79 # by reference. This *could* have side effects as all components
80 80 # will share config. In fact, I did find such a side effect in
81 81 # _config_changed below. If a config attribute value was a mutable type
82 82 # all instances of a component were getting the same copy, effectively
83 83 # making that a class attribute.
84 84 # self.config = deepcopy(config)
85 85 self.config = config
86 86 # This should go second so individual keyword arguments override
87 87 # the values in config.
88 88 super(Configurable, self).__init__(**kwargs)
89 89 self.created = datetime.datetime.now()
90 90
91 91 #-------------------------------------------------------------------------
92 92 # Static trait notifiations
93 93 #-------------------------------------------------------------------------
94 94
95 95 def _config_changed(self, name, old, new):
96 96 """Update all the class traits having ``config=True`` as metadata.
97 97
98 98 For any class trait with a ``config`` metadata attribute that is
99 99 ``True``, we update the trait with the value of the corresponding
100 100 config entry.
101 101 """
102 102 # Get all traits with a config metadata entry that is True
103 103 traits = self.traits(config=True)
104 104
105 105 # We auto-load config section for this class as well as any parent
106 106 # classes that are Configurable subclasses. This starts with Configurable
107 107 # and works down the mro loading the config for each section.
108 108 section_names = [cls.__name__ for cls in \
109 109 reversed(self.__class__.__mro__) if
110 110 issubclass(cls, Configurable) and issubclass(self.__class__, cls)]
111 111
112 112 for sname in section_names:
113 113 # Don't do a blind getattr as that would cause the config to
114 114 # dynamically create the section with name self.__class__.__name__.
115 115 if new._has_section(sname):
116 116 my_config = new[sname]
117 117 for k, v in traits.iteritems():
118 118 # Don't allow traitlets with config=True to start with
119 119 # uppercase. Otherwise, they are confused with Config
120 120 # subsections. But, developers shouldn't have uppercase
121 121 # attributes anyways! (PEP 6)
122 122 if k[0].upper()==k[0] and not k.startswith('_'):
123 123 raise ConfigurableError('Configurable traitlets with '
124 124 'config=True must start with a lowercase so they are '
125 125 'not confused with Config subsections: %s.%s' % \
126 126 (self.__class__.__name__, k))
127 127 try:
128 128 # Here we grab the value from the config
129 129 # If k has the naming convention of a config
130 130 # section, it will be auto created.
131 131 config_value = my_config[k]
132 132 except KeyError:
133 133 pass
134 134 else:
135 135 # print "Setting %s.%s from %s.%s=%r" % \
136 136 # (self.__class__.__name__,k,sname,k,config_value)
137 137 # We have to do a deepcopy here if we don't deepcopy the entire
138 138 # config object. If we don't, a mutable config_value will be
139 139 # shared by all instances, effectively making it a class attribute.
140 140 setattr(self, k, deepcopy(config_value))
141 141
142 142 @classmethod
143 143 def class_get_shortnames(cls):
144 144 """Return the shortname to fullname dict for config=True traits."""
145 145 cls_traits = cls.class_traits(config=True)
146 146 shortnames = {}
147 147 for k, v in cls_traits.items():
148 148 shortname = v.get_metadata('shortname')
149 149 if shortname is not None:
150 150 longname = cls.__name__ + '.' + k
151 151 shortnames[shortname] = longname
152 152 return shortnames
153 153
154 154 @classmethod
155 155 def class_get_help(cls):
156 156 """Get the help string for this class in ReST format."""
157 157 cls_traits = cls.class_traits(config=True)
158 158 final_help = []
159 159 final_help.append(u'%s options' % cls.__name__)
160 160 final_help.append(len(final_help[0])*u'-')
161 161 for k, v in cls_traits.items():
162 162 help = v.get_metadata('help')
163 163 shortname = v.get_metadata('shortname')
164 164 header = "%s.%s : %s" % (cls.__name__, k, v.__class__.__name__)
165 165 if shortname is not None:
166 166 header += " (shortname=" + shortname + ")"
167 167 final_help.append(header)
168 168 if help is not None:
169 169 final_help.append(indent(help))
170 170 return '\n'.join(final_help)
171 171
172 172 @classmethod
173 173 def class_print_help(cls):
174 174 print cls.class_get_help()
175 175
176 176
177 177 class SingletonConfigurable(Configurable):
178 178 """A configurable that only allows one instance.
179 179
180 180 This class is for classes that should only have one instance of itself
181 181 or *any* subclass. To create and retrieve such a class use the
182 182 :meth:`SingletonConfigurable.instance` method.
183 183 """
184 184
185 185 _instance = None
186 186
187 187 @classmethod
188 188 def instance(cls, *args, **kwargs):
189 189 """Returns a global instance of this class.
190 190
191 191 This method create a new instance if none have previously been created
192 192 and returns a previously created instance is one already exists.
193 193
194 194 The arguments and keyword arguments passed to this method are passed
195 195 on to the :meth:`__init__` method of the class upon instantiation.
196 196
197 197 Examples
198 198 --------
199 199
200 200 Create a singleton class using instance, and retrieve it::
201 201
202 202 >>> from IPython.config.configurable import SingletonConfigurable
203 203 >>> class Foo(SingletonConfigurable): pass
204 204 >>> foo = Foo.instance()
205 205 >>> foo == Foo.instance()
206 206 True
207 207
208 208 Create a subclass that is retrived using the base class instance::
209 209
210 210 >>> class Bar(SingletonConfigurable): pass
211 211 >>> class Bam(Bar): pass
212 212 >>> bam = Bam.instance()
213 213 >>> bam == Bar.instance()
214 214 True
215 215 """
216 216 # Create and save the instance
217 217 if cls._instance is None:
218 218 inst = cls(*args, **kwargs)
219 219 # Now make sure that the instance will also be returned by
220 220 # the subclasses instance attribute.
221 221 for subclass in cls.mro():
222 222 if issubclass(cls, subclass) and \
223 223 issubclass(subclass, SingletonConfigurable) and \
224 224 subclass != SingletonConfigurable:
225 225 subclass._instance = inst
226 226 else:
227 227 break
228 228 if isinstance(cls._instance, cls):
229 229 return cls._instance
230 230 else:
231 231 raise MultipleInstanceError(
232 232 'Multiple incompatible subclass instances of '
233 233 '%s are being created.' % cls.__name__
234 234 )
235
236 @classmethod
237 def initialized(cls):
238 """Has an instance been created?"""
239 return hasattr(cls, "_instance") and cls._instance is not None
240
@@ -1,168 +1,172 b''
1 1 #!/usr/bin/env python
2 2 # encoding: utf-8
3 3 """
4 4 Tests for IPython.config.configurable
5 5
6 6 Authors:
7 7
8 8 * Brian Granger
9 9 * Fernando Perez (design help)
10 10 """
11 11
12 12 #-----------------------------------------------------------------------------
13 13 # Copyright (C) 2008-2010 The IPython Development Team
14 14 #
15 15 # Distributed under the terms of the BSD License. The full license is in
16 16 # the file COPYING, distributed as part of this software.
17 17 #-----------------------------------------------------------------------------
18 18
19 19 #-----------------------------------------------------------------------------
20 20 # Imports
21 21 #-----------------------------------------------------------------------------
22 22
23 23 from unittest import TestCase
24 24
25 25 from IPython.config.configurable import (
26 26 Configurable,
27 27 SingletonConfigurable
28 28 )
29 29
30 30 from IPython.utils.traitlets import (
31 31 Int, Float, Str
32 32 )
33 33
34 34 from IPython.config.loader import Config
35 35
36 36
37 37 #-----------------------------------------------------------------------------
38 38 # Test cases
39 39 #-----------------------------------------------------------------------------
40 40
41 41
42 42 class MyConfigurable(Configurable):
43 43 a = Int(1, config=True, shortname="a", help="The integer a.")
44 44 b = Float(1.0, config=True, shortname="b", help="The integer b.")
45 45 c = Str('no config')
46 46
47 47
48 48 mc_help=u"""MyConfigurable options
49 49 ----------------------
50 50 MyConfigurable.a : Int (shortname=a)
51 51 The integer a.
52 52 MyConfigurable.b : Float (shortname=b)
53 53 The integer b."""
54 54
55 55 class Foo(Configurable):
56 56 a = Int(0, config=True, shortname="a", help="The integer a.")
57 57 b = Str('nope', config=True)
58 58
59 59
60 60 class Bar(Foo):
61 61 b = Str('gotit', config=False, shortname="b", help="The string b.")
62 62 c = Float(config=True, shortname="c", help="The string c.")
63 63
64 64
65 65 class TestConfigurable(TestCase):
66 66
67 67 def test_default(self):
68 68 c1 = Configurable()
69 69 c2 = Configurable(config=c1.config)
70 70 c3 = Configurable(config=c2.config)
71 71 self.assertEquals(c1.config, c2.config)
72 72 self.assertEquals(c2.config, c3.config)
73 73
74 74 def test_custom(self):
75 75 config = Config()
76 76 config.foo = 'foo'
77 77 config.bar = 'bar'
78 78 c1 = Configurable(config=config)
79 79 c2 = Configurable(config=c1.config)
80 80 c3 = Configurable(config=c2.config)
81 81 self.assertEquals(c1.config, config)
82 82 self.assertEquals(c2.config, config)
83 83 self.assertEquals(c3.config, config)
84 84 # Test that copies are not made
85 85 self.assert_(c1.config is config)
86 86 self.assert_(c2.config is config)
87 87 self.assert_(c3.config is config)
88 88 self.assert_(c1.config is c2.config)
89 89 self.assert_(c2.config is c3.config)
90 90
91 91 def test_inheritance(self):
92 92 config = Config()
93 93 config.MyConfigurable.a = 2
94 94 config.MyConfigurable.b = 2.0
95 95 c1 = MyConfigurable(config=config)
96 96 c2 = MyConfigurable(config=c1.config)
97 97 self.assertEquals(c1.a, config.MyConfigurable.a)
98 98 self.assertEquals(c1.b, config.MyConfigurable.b)
99 99 self.assertEquals(c2.a, config.MyConfigurable.a)
100 100 self.assertEquals(c2.b, config.MyConfigurable.b)
101 101
102 102 def test_parent(self):
103 103 config = Config()
104 104 config.Foo.a = 10
105 105 config.Foo.b = "wow"
106 106 config.Bar.b = 'later'
107 107 config.Bar.c = 100.0
108 108 f = Foo(config=config)
109 109 b = Bar(config=f.config)
110 110 self.assertEquals(f.a, 10)
111 111 self.assertEquals(f.b, 'wow')
112 112 self.assertEquals(b.b, 'gotit')
113 113 self.assertEquals(b.c, 100.0)
114 114
115 115 def test_override1(self):
116 116 config = Config()
117 117 config.MyConfigurable.a = 2
118 118 config.MyConfigurable.b = 2.0
119 119 c = MyConfigurable(a=3, config=config)
120 120 self.assertEquals(c.a, 3)
121 121 self.assertEquals(c.b, config.MyConfigurable.b)
122 122 self.assertEquals(c.c, 'no config')
123 123
124 124 def test_override2(self):
125 125 config = Config()
126 126 config.Foo.a = 1
127 127 config.Bar.b = 'or' # Up above b is config=False, so this won't do it.
128 128 config.Bar.c = 10.0
129 129 c = Bar(config=config)
130 130 self.assertEquals(c.a, config.Foo.a)
131 131 self.assertEquals(c.b, 'gotit')
132 132 self.assertEquals(c.c, config.Bar.c)
133 133 c = Bar(a=2, b='and', c=20.0, config=config)
134 134 self.assertEquals(c.a, 2)
135 135 self.assertEquals(c.b, 'and')
136 136 self.assertEquals(c.c, 20.0)
137 137
138 138 def test_shortnames(self):
139 139 sn = MyConfigurable.class_get_shortnames()
140 140 self.assertEquals(sn, {'a': 'MyConfigurable.a', 'b': 'MyConfigurable.b'})
141 141 sn = Foo.class_get_shortnames()
142 142 self.assertEquals(sn, {'a': 'Foo.a'})
143 143 sn = Bar.class_get_shortnames()
144 144 self.assertEquals(sn, {'a': 'Bar.a', 'c': 'Bar.c'})
145 145
146 146 def test_help(self):
147 147 self.assertEquals(MyConfigurable.class_get_help(), mc_help)
148 148
149 149
150 150 class TestSingletonConfigurable(TestCase):
151 151
152 152 def test_instance(self):
153 153 from IPython.config.configurable import SingletonConfigurable
154 154 class Foo(SingletonConfigurable): pass
155 self.assertEquals(Foo.initialized(), False)
155 156 foo = Foo.instance()
157 self.assertEquals(Foo.initialized(), True)
156 158 self.assertEquals(foo, Foo.instance())
157 159 self.assertEquals(SingletonConfigurable._instance, None)
158 160
159 161 def test_inheritance(self):
160
161 162 class Bar(SingletonConfigurable): pass
162 163 class Bam(Bar): pass
164 self.assertEquals(Bar.initialized(), False)
165 self.assertEquals(Bam.initialized(), False)
163 166 bam = Bam.instance()
164 167 bam == Bar.instance()
168 self.assertEquals(Bar.initialized(), True)
169 self.assertEquals(Bam.initialized(), True)
165 170 self.assertEquals(bam, Bam._instance)
166 171 self.assertEquals(bam, Bar._instance)
167 172 self.assertEquals(SingletonConfigurable._instance, None)
168 No newline at end of file
@@ -1,2493 +1,2466 b''
1 1 # -*- coding: utf-8 -*-
2 2 """Main IPython class."""
3 3
4 4 #-----------------------------------------------------------------------------
5 5 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
6 6 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
7 7 # Copyright (C) 2008-2011 The IPython Development Team
8 8 #
9 9 # Distributed under the terms of the BSD License. The full license is in
10 10 # the file COPYING, distributed as part of this software.
11 11 #-----------------------------------------------------------------------------
12 12
13 13 #-----------------------------------------------------------------------------
14 14 # Imports
15 15 #-----------------------------------------------------------------------------
16 16
17 17 from __future__ import with_statement
18 18 from __future__ import absolute_import
19 19
20 20 import __builtin__
21 21 import __future__
22 22 import abc
23 23 import ast
24 24 import atexit
25 25 import codeop
26 26 import inspect
27 27 import os
28 28 import re
29 29 import sys
30 30 import tempfile
31 31 import types
32 32 from contextlib import nested
33 33
34 from IPython.config.configurable import Configurable
34 from IPython.config.configurable import SingletonConfigurable
35 35 from IPython.core import debugger, oinspect
36 36 from IPython.core import history as ipcorehist
37 37 from IPython.core import page
38 38 from IPython.core import prefilter
39 39 from IPython.core import shadowns
40 40 from IPython.core import ultratb
41 41 from IPython.core.alias import AliasManager
42 42 from IPython.core.autocall import ExitAutocall
43 43 from IPython.core.builtin_trap import BuiltinTrap
44 44 from IPython.core.compilerop import CachingCompiler
45 45 from IPython.core.display_trap import DisplayTrap
46 46 from IPython.core.displayhook import DisplayHook
47 47 from IPython.core.displaypub import DisplayPublisher
48 48 from IPython.core.error import TryNext, UsageError
49 49 from IPython.core.extensions import ExtensionManager
50 50 from IPython.core.fakemodule import FakeModule, init_fakemod_dict
51 51 from IPython.core.formatters import DisplayFormatter
52 52 from IPython.core.history import HistoryManager
53 53 from IPython.core.inputsplitter import IPythonInputSplitter
54 54 from IPython.core.logger import Logger
55 55 from IPython.core.macro import Macro
56 56 from IPython.core.magic import Magic
57 57 from IPython.core.payload import PayloadManager
58 58 from IPython.core.plugin import PluginManager
59 59 from IPython.core.prefilter import PrefilterManager, ESC_MAGIC
60 60 from IPython.external.Itpl import ItplNS
61 61 from IPython.utils import PyColorize
62 62 from IPython.utils import io
63 63 from IPython.utils.doctestreload import doctest_reload
64 64 from IPython.utils.io import ask_yes_no, rprint
65 65 from IPython.utils.ipstruct import Struct
66 66 from IPython.utils.path import get_home_dir, get_ipython_dir, HomeDirError
67 67 from IPython.utils.pickleshare import PickleShareDB
68 68 from IPython.utils.process import system, getoutput
69 69 from IPython.utils.strdispatch import StrDispatch
70 70 from IPython.utils.syspathcontext import prepended_to_syspath
71 71 from IPython.utils.text import num_ini_spaces, format_screen, LSString, SList
72 72 from IPython.utils.traitlets import (Int, Str, CBool, CaselessStrEnum, Enum,
73 73 List, Unicode, Instance, Type)
74 74 from IPython.utils.warn import warn, error, fatal
75 75 import IPython.core.hooks
76 76
77 77 #-----------------------------------------------------------------------------
78 78 # Globals
79 79 #-----------------------------------------------------------------------------
80 80
81 81 # compiled regexps for autoindent management
82 82 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
83 83
84 84 #-----------------------------------------------------------------------------
85 85 # Utilities
86 86 #-----------------------------------------------------------------------------
87 87
88 88 # store the builtin raw_input globally, and use this always, in case user code
89 89 # overwrites it (like wx.py.PyShell does)
90 90 raw_input_original = raw_input
91 91
92 92 def softspace(file, newvalue):
93 93 """Copied from code.py, to remove the dependency"""
94 94
95 95 oldvalue = 0
96 96 try:
97 97 oldvalue = file.softspace
98 98 except AttributeError:
99 99 pass
100 100 try:
101 101 file.softspace = newvalue
102 102 except (AttributeError, TypeError):
103 103 # "attribute-less object" or "read-only attributes"
104 104 pass
105 105 return oldvalue
106 106
107 107
108 108 def no_op(*a, **kw): pass
109 109
110 110 class SpaceInInput(Exception): pass
111 111
112 112 class Bunch: pass
113 113
114 114
115 115 def get_default_colors():
116 116 if sys.platform=='darwin':
117 117 return "LightBG"
118 118 elif os.name=='nt':
119 119 return 'Linux'
120 120 else:
121 121 return 'Linux'
122 122
123 123
124 124 class SeparateStr(Str):
125 125 """A Str subclass to validate separate_in, separate_out, etc.
126 126
127 127 This is a Str based trait that converts '0'->'' and '\\n'->'\n'.
128 128 """
129 129
130 130 def validate(self, obj, value):
131 131 if value == '0': value = ''
132 132 value = value.replace('\\n','\n')
133 133 return super(SeparateStr, self).validate(obj, value)
134 134
135 class MultipleInstanceError(Exception):
136 pass
137
135
138 136 class ReadlineNoRecord(object):
139 137 """Context manager to execute some code, then reload readline history
140 138 so that interactive input to the code doesn't appear when pressing up."""
141 139 def __init__(self, shell):
142 140 self.shell = shell
143 141 self._nested_level = 0
144 142
145 143 def __enter__(self):
146 144 if self._nested_level == 0:
147 145 try:
148 146 self.orig_length = self.current_length()
149 147 self.readline_tail = self.get_readline_tail()
150 148 except (AttributeError, IndexError): # Can fail with pyreadline
151 149 self.orig_length, self.readline_tail = 999999, []
152 150 self._nested_level += 1
153 151
154 152 def __exit__(self, type, value, traceback):
155 153 self._nested_level -= 1
156 154 if self._nested_level == 0:
157 155 # Try clipping the end if it's got longer
158 156 try:
159 157 e = self.current_length() - self.orig_length
160 158 if e > 0:
161 159 for _ in range(e):
162 160 self.shell.readline.remove_history_item(self.orig_length)
163 161
164 162 # If it still doesn't match, just reload readline history.
165 163 if self.current_length() != self.orig_length \
166 164 or self.get_readline_tail() != self.readline_tail:
167 165 self.shell.refill_readline_hist()
168 166 except (AttributeError, IndexError):
169 167 pass
170 168 # Returning False will cause exceptions to propagate
171 169 return False
172 170
173 171 def current_length(self):
174 172 return self.shell.readline.get_current_history_length()
175 173
176 174 def get_readline_tail(self, n=10):
177 175 """Get the last n items in readline history."""
178 176 end = self.shell.readline.get_current_history_length() + 1
179 177 start = max(end-n, 1)
180 178 ghi = self.shell.readline.get_history_item
181 179 return [ghi(x) for x in range(start, end)]
182 180
183 181
184 182 _autocall_help = """
185 183 Make IPython automatically call any callable object even if
186 184 you didn't type explicit parentheses. For example, 'str 43' becomes 'str(43)'
187 185 automatically. The value can be '0' to disable the feature, '1' for 'smart'
188 186 autocall, where it is not applied if there are no more arguments on the line,
189 187 and '2' for 'full' autocall, where all callable objects are automatically
190 188 called (even if no arguments are present). The default is '1'.
191 189 """
192 190
193 191 #-----------------------------------------------------------------------------
194 192 # Main IPython class
195 193 #-----------------------------------------------------------------------------
196 194
197 class InteractiveShell(Configurable, Magic):
195 class InteractiveShell(SingletonConfigurable, Magic):
198 196 """An enhanced, interactive shell for Python."""
199 197
200 198 _instance = None
201 199
202 200 autocall = Enum((0,1,2), default_value=1, config=True, help=
203 201 """
204 202 Make IPython automatically call any callable object even if you didn't
205 203 type explicit parentheses. For example, 'str 43' becomes 'str(43)'
206 204 automatically. The value can be '0' to disable the feature, '1' for
207 205 'smart' autocall, where it is not applied if there are no more
208 206 arguments on the line, and '2' for 'full' autocall, where all callable
209 207 objects are automatically called (even if no arguments are present).
210 208 The default is '1'.
211 209 """
212 210 )
213 211 # TODO: remove all autoindent logic and put into frontends.
214 212 # We can't do this yet because even runlines uses the autoindent.
215 213 autoindent = CBool(True, config=True, help=
216 214 """
217 215 Autoindent IPython code entered interactively.
218 216 """
219 217 )
220 218 automagic = CBool(True, config=True, help=
221 219 """
222 220 Enable magic commands to be called without the leading %.
223 221 """
224 222 )
225 223 cache_size = Int(1000, config=True, help=
226 224 """
227 225 Set the size of the output cache. The default is 1000, you can
228 226 change it permanently in your config file. Setting it to 0 completely
229 227 disables the caching system, and the minimum value accepted is 20 (if
230 228 you provide a value less than 20, it is reset to 0 and a warning is
231 229 issued). This limit is defined because otherwise you'll spend more
232 230 time re-flushing a too small cache than working
233 231 """
234 232 )
235 233 color_info = CBool(True, config=True, help=
236 234 """
237 235 Use colors for displaying information about objects. Because this
238 236 information is passed through a pager (like 'less'), and some pagers
239 237 get confused with color codes, this capability can be turned off.
240 238 """
241 239 )
242 240 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
243 241 default_value=get_default_colors(), config=True)
244 242 debug = CBool(False, config=True)
245 243 deep_reload = CBool(False, config=True, help=
246 244 """
247 245 Enable deep (recursive) reloading by default. IPython can use the
248 246 deep_reload module which reloads changes in modules recursively (it
249 247 replaces the reload() function, so you don't need to change anything to
250 248 use it). deep_reload() forces a full reload of modules whose code may
251 249 have changed, which the default reload() function does not. When
252 250 deep_reload is off, IPython will use the normal reload(), but
253 251 deep_reload will still be available as dreload().
254 252 """
255 253 )
256 254 display_formatter = Instance(DisplayFormatter)
257 255 displayhook_class = Type(DisplayHook)
258 256 display_pub_class = Type(DisplayPublisher)
259 257
260 258 exit_now = CBool(False)
261 259 exiter = Instance(ExitAutocall)
262 260 def _exiter_default(self):
263 261 return ExitAutocall(self)
264 262 # Monotonically increasing execution counter
265 263 execution_count = Int(1)
266 264 filename = Unicode("<ipython console>")
267 265 ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__
268 266
269 267 # Input splitter, to split entire cells of input into either individual
270 268 # interactive statements or whole blocks.
271 269 input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
272 270 (), {})
273 271 logstart = CBool(False, config=True, help=
274 272 """
275 273 Start logging to the default log file.
276 274 """
277 275 )
278 276 logfile = Unicode('', config=True, help=
279 277 """
280 278 The name of the logfile to use.
281 279 """
282 280 )
283 281 logappend = Unicode('', config=True, help=
284 282 """
285 283 Start logging to the given file in append mode.
286 284 """
287 285 )
288 286 object_info_string_level = Enum((0,1,2), default_value=0,
289 287 config=True)
290 288 pdb = CBool(False, config=True, help=
291 289 """
292 290 Automatically call the pdb debugger after every exception.
293 291 """
294 292 )
295 293
296 294 profile = Unicode('', config=True)
297 295 prompt_in1 = Str('In [\\#]: ', config=True)
298 296 prompt_in2 = Str(' .\\D.: ', config=True)
299 297 prompt_out = Str('Out[\\#]: ', config=True)
300 298 prompts_pad_left = CBool(True, config=True)
301 299 quiet = CBool(False, config=True)
302 300
303 301 history_length = Int(10000, config=True)
304 302
305 303 # The readline stuff will eventually be moved to the terminal subclass
306 304 # but for now, we can't do that as readline is welded in everywhere.
307 305 readline_use = CBool(True, config=True)
308 306 readline_merge_completions = CBool(True, config=True)
309 307 readline_omit__names = Enum((0,1,2), default_value=2, config=True)
310 308 readline_remove_delims = Str('-/~', config=True)
311 309 readline_parse_and_bind = List([
312 310 'tab: complete',
313 311 '"\C-l": clear-screen',
314 312 'set show-all-if-ambiguous on',
315 313 '"\C-o": tab-insert',
316 314 # See bug gh-58 - with \M-i enabled, chars 0x9000-0x9fff
317 315 # crash IPython.
318 316 '"\M-o": "\d\d\d\d"',
319 317 '"\M-I": "\d\d\d\d"',
320 318 '"\C-r": reverse-search-history',
321 319 '"\C-s": forward-search-history',
322 320 '"\C-p": history-search-backward',
323 321 '"\C-n": history-search-forward',
324 322 '"\e[A": history-search-backward',
325 323 '"\e[B": history-search-forward',
326 324 '"\C-k": kill-line',
327 325 '"\C-u": unix-line-discard',
328 326 ], allow_none=False, config=True)
329 327
330 328 # TODO: this part of prompt management should be moved to the frontends.
331 329 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
332 330 separate_in = SeparateStr('\n', config=True)
333 331 separate_out = SeparateStr('', config=True)
334 332 separate_out2 = SeparateStr('', config=True)
335 333 wildcards_case_sensitive = CBool(True, config=True)
336 334 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
337 335 default_value='Context', config=True)
338 336
339 337 # Subcomponents of InteractiveShell
340 338 alias_manager = Instance('IPython.core.alias.AliasManager')
341 339 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
342 340 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap')
343 341 display_trap = Instance('IPython.core.display_trap.DisplayTrap')
344 342 extension_manager = Instance('IPython.core.extensions.ExtensionManager')
345 343 plugin_manager = Instance('IPython.core.plugin.PluginManager')
346 344 payload_manager = Instance('IPython.core.payload.PayloadManager')
347 345 history_manager = Instance('IPython.core.history.HistoryManager')
348 346
349 347 # Private interface
350 348 _post_execute = Instance(dict)
351 349
352 350 def __init__(self, config=None, ipython_dir=None,
353 351 user_ns=None, user_global_ns=None,
354 352 custom_exceptions=((), None)):
355 353
356 354 # This is where traits with a config_key argument are updated
357 355 # from the values on config.
358 356 super(InteractiveShell, self).__init__(config=config)
359 357
360 358 # These are relatively independent and stateless
361 359 self.init_ipython_dir(ipython_dir)
362 360 self.init_instance_attrs()
363 361 self.init_environment()
364 362
365 363 # Create namespaces (user_ns, user_global_ns, etc.)
366 364 self.init_create_namespaces(user_ns, user_global_ns)
367 365 # This has to be done after init_create_namespaces because it uses
368 366 # something in self.user_ns, but before init_sys_modules, which
369 367 # is the first thing to modify sys.
370 368 # TODO: When we override sys.stdout and sys.stderr before this class
371 369 # is created, we are saving the overridden ones here. Not sure if this
372 370 # is what we want to do.
373 371 self.save_sys_module_state()
374 372 self.init_sys_modules()
375 373
376 374 # While we're trying to have each part of the code directly access what
377 375 # it needs without keeping redundant references to objects, we have too
378 376 # much legacy code that expects ip.db to exist.
379 377 self.db = PickleShareDB(os.path.join(self.ipython_dir, 'db'))
380 378
381 379 self.init_history()
382 380 self.init_encoding()
383 381 self.init_prefilter()
384 382
385 383 Magic.__init__(self, self)
386 384
387 385 self.init_syntax_highlighting()
388 386 self.init_hooks()
389 387 self.init_pushd_popd_magic()
390 388 # self.init_traceback_handlers use to be here, but we moved it below
391 389 # because it and init_io have to come after init_readline.
392 390 self.init_user_ns()
393 391 self.init_logger()
394 392 self.init_alias()
395 393 self.init_builtins()
396 394
397 395 # pre_config_initialization
398 396
399 397 # The next section should contain everything that was in ipmaker.
400 398 self.init_logstart()
401 399
402 400 # The following was in post_config_initialization
403 401 self.init_inspector()
404 402 # init_readline() must come before init_io(), because init_io uses
405 403 # readline related things.
406 404 self.init_readline()
407 405 # init_completer must come after init_readline, because it needs to
408 406 # know whether readline is present or not system-wide to configure the
409 407 # completers, since the completion machinery can now operate
410 408 # independently of readline (e.g. over the network)
411 409 self.init_completer()
412 410 # TODO: init_io() needs to happen before init_traceback handlers
413 411 # because the traceback handlers hardcode the stdout/stderr streams.
414 412 # This logic in in debugger.Pdb and should eventually be changed.
415 413 self.init_io()
416 414 self.init_traceback_handlers(custom_exceptions)
417 415 self.init_prompts()
418 416 self.init_display_formatter()
419 417 self.init_display_pub()
420 418 self.init_displayhook()
421 419 self.init_reload_doctest()
422 420 self.init_magics()
423 421 self.init_pdb()
424 422 self.init_extension_manager()
425 423 self.init_plugin_manager()
426 424 self.init_payload()
427 425 self.hooks.late_startup_hook()
428 426 atexit.register(self.atexit_operations)
429 427
430 @classmethod
431 def instance(cls, *args, **kwargs):
432 """Returns a global InteractiveShell instance."""
433 if cls._instance is None:
434 inst = cls(*args, **kwargs)
435 # Now make sure that the instance will also be returned by
436 # the subclasses instance attribute.
437 for subclass in cls.mro():
438 if issubclass(cls, subclass) and \
439 issubclass(subclass, InteractiveShell):
440 subclass._instance = inst
441 else:
442 break
443 if isinstance(cls._instance, cls):
444 return cls._instance
445 else:
446 raise MultipleInstanceError(
447 'Multiple incompatible subclass instances of '
448 'InteractiveShell are being created.'
449 )
450
451 @classmethod
452 def initialized(cls):
453 return hasattr(cls, "_instance")
454
455 428 def get_ipython(self):
456 429 """Return the currently running IPython instance."""
457 430 return self
458 431
459 432 #-------------------------------------------------------------------------
460 433 # Trait changed handlers
461 434 #-------------------------------------------------------------------------
462 435
463 436 def _ipython_dir_changed(self, name, new):
464 437 if not os.path.isdir(new):
465 438 os.makedirs(new, mode = 0777)
466 439
467 440 def set_autoindent(self,value=None):
468 441 """Set the autoindent flag, checking for readline support.
469 442
470 443 If called with no arguments, it acts as a toggle."""
471 444
472 445 if not self.has_readline:
473 446 if os.name == 'posix':
474 447 warn("The auto-indent feature requires the readline library")
475 448 self.autoindent = 0
476 449 return
477 450 if value is None:
478 451 self.autoindent = not self.autoindent
479 452 else:
480 453 self.autoindent = value
481 454
482 455 #-------------------------------------------------------------------------
483 456 # init_* methods called by __init__
484 457 #-------------------------------------------------------------------------
485 458
486 459 def init_ipython_dir(self, ipython_dir):
487 460 if ipython_dir is not None:
488 461 self.ipython_dir = ipython_dir
489 462 self.config.Global.ipython_dir = self.ipython_dir
490 463 return
491 464
492 465 if hasattr(self.config.Global, 'ipython_dir'):
493 466 self.ipython_dir = self.config.Global.ipython_dir
494 467 else:
495 468 self.ipython_dir = get_ipython_dir()
496 469
497 470 # All children can just read this
498 471 self.config.Global.ipython_dir = self.ipython_dir
499 472
500 473 def init_instance_attrs(self):
501 474 self.more = False
502 475
503 476 # command compiler
504 477 self.compile = CachingCompiler()
505 478
506 479 # Make an empty namespace, which extension writers can rely on both
507 480 # existing and NEVER being used by ipython itself. This gives them a
508 481 # convenient location for storing additional information and state
509 482 # their extensions may require, without fear of collisions with other
510 483 # ipython names that may develop later.
511 484 self.meta = Struct()
512 485
513 486 # Temporary files used for various purposes. Deleted at exit.
514 487 self.tempfiles = []
515 488
516 489 # Keep track of readline usage (later set by init_readline)
517 490 self.has_readline = False
518 491
519 492 # keep track of where we started running (mainly for crash post-mortem)
520 493 # This is not being used anywhere currently.
521 494 self.starting_dir = os.getcwd()
522 495
523 496 # Indentation management
524 497 self.indent_current_nsp = 0
525 498
526 499 # Dict to track post-execution functions that have been registered
527 500 self._post_execute = {}
528 501
529 502 def init_environment(self):
530 503 """Any changes we need to make to the user's environment."""
531 504 pass
532 505
533 506 def init_encoding(self):
534 507 # Get system encoding at startup time. Certain terminals (like Emacs
535 508 # under Win32 have it set to None, and we need to have a known valid
536 509 # encoding to use in the raw_input() method
537 510 try:
538 511 self.stdin_encoding = sys.stdin.encoding or 'ascii'
539 512 except AttributeError:
540 513 self.stdin_encoding = 'ascii'
541 514
542 515 def init_syntax_highlighting(self):
543 516 # Python source parser/formatter for syntax highlighting
544 517 pyformat = PyColorize.Parser().format
545 518 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
546 519
547 520 def init_pushd_popd_magic(self):
548 521 # for pushd/popd management
549 522 try:
550 523 self.home_dir = get_home_dir()
551 524 except HomeDirError, msg:
552 525 fatal(msg)
553 526
554 527 self.dir_stack = []
555 528
556 529 def init_logger(self):
557 530 self.logger = Logger(self.home_dir, logfname='ipython_log.py',
558 531 logmode='rotate')
559 532
560 533 def init_logstart(self):
561 534 """Initialize logging in case it was requested at the command line.
562 535 """
563 536 if self.logappend:
564 537 self.magic_logstart(self.logappend + ' append')
565 538 elif self.logfile:
566 539 self.magic_logstart(self.logfile)
567 540 elif self.logstart:
568 541 self.magic_logstart()
569 542
570 543 def init_builtins(self):
571 544 self.builtin_trap = BuiltinTrap(shell=self)
572 545
573 546 def init_inspector(self):
574 547 # Object inspector
575 548 self.inspector = oinspect.Inspector(oinspect.InspectColors,
576 549 PyColorize.ANSICodeColors,
577 550 'NoColor',
578 551 self.object_info_string_level)
579 552
580 553 def init_io(self):
581 554 # This will just use sys.stdout and sys.stderr. If you want to
582 555 # override sys.stdout and sys.stderr themselves, you need to do that
583 556 # *before* instantiating this class, because Term holds onto
584 557 # references to the underlying streams.
585 558 if sys.platform == 'win32' and self.has_readline:
586 559 Term = io.IOTerm(cout=self.readline._outputfile,
587 560 cerr=self.readline._outputfile)
588 561 else:
589 562 Term = io.IOTerm()
590 563 io.Term = Term
591 564
592 565 def init_prompts(self):
593 566 # TODO: This is a pass for now because the prompts are managed inside
594 567 # the DisplayHook. Once there is a separate prompt manager, this
595 568 # will initialize that object and all prompt related information.
596 569 pass
597 570
598 571 def init_display_formatter(self):
599 572 self.display_formatter = DisplayFormatter(config=self.config)
600 573
601 574 def init_display_pub(self):
602 575 self.display_pub = self.display_pub_class(config=self.config)
603 576
604 577 def init_displayhook(self):
605 578 # Initialize displayhook, set in/out prompts and printing system
606 579 self.displayhook = self.displayhook_class(
607 580 config=self.config,
608 581 shell=self,
609 582 cache_size=self.cache_size,
610 583 input_sep = self.separate_in,
611 584 output_sep = self.separate_out,
612 585 output_sep2 = self.separate_out2,
613 586 ps1 = self.prompt_in1,
614 587 ps2 = self.prompt_in2,
615 588 ps_out = self.prompt_out,
616 589 pad_left = self.prompts_pad_left
617 590 )
618 591 # This is a context manager that installs/revmoes the displayhook at
619 592 # the appropriate time.
620 593 self.display_trap = DisplayTrap(hook=self.displayhook)
621 594
622 595 def init_reload_doctest(self):
623 596 # Do a proper resetting of doctest, including the necessary displayhook
624 597 # monkeypatching
625 598 try:
626 599 doctest_reload()
627 600 except ImportError:
628 601 warn("doctest module does not exist.")
629 602
630 603 #-------------------------------------------------------------------------
631 604 # Things related to injections into the sys module
632 605 #-------------------------------------------------------------------------
633 606
634 607 def save_sys_module_state(self):
635 608 """Save the state of hooks in the sys module.
636 609
637 610 This has to be called after self.user_ns is created.
638 611 """
639 612 self._orig_sys_module_state = {}
640 613 self._orig_sys_module_state['stdin'] = sys.stdin
641 614 self._orig_sys_module_state['stdout'] = sys.stdout
642 615 self._orig_sys_module_state['stderr'] = sys.stderr
643 616 self._orig_sys_module_state['excepthook'] = sys.excepthook
644 617 try:
645 618 self._orig_sys_modules_main_name = self.user_ns['__name__']
646 619 except KeyError:
647 620 pass
648 621
649 622 def restore_sys_module_state(self):
650 623 """Restore the state of the sys module."""
651 624 try:
652 625 for k, v in self._orig_sys_module_state.iteritems():
653 626 setattr(sys, k, v)
654 627 except AttributeError:
655 628 pass
656 629 # Reset what what done in self.init_sys_modules
657 630 try:
658 631 sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name
659 632 except (AttributeError, KeyError):
660 633 pass
661 634
662 635 #-------------------------------------------------------------------------
663 636 # Things related to hooks
664 637 #-------------------------------------------------------------------------
665 638
666 639 def init_hooks(self):
667 640 # hooks holds pointers used for user-side customizations
668 641 self.hooks = Struct()
669 642
670 643 self.strdispatchers = {}
671 644
672 645 # Set all default hooks, defined in the IPython.hooks module.
673 646 hooks = IPython.core.hooks
674 647 for hook_name in hooks.__all__:
675 648 # default hooks have priority 100, i.e. low; user hooks should have
676 649 # 0-100 priority
677 650 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
678 651
679 652 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
680 653 """set_hook(name,hook) -> sets an internal IPython hook.
681 654
682 655 IPython exposes some of its internal API as user-modifiable hooks. By
683 656 adding your function to one of these hooks, you can modify IPython's
684 657 behavior to call at runtime your own routines."""
685 658
686 659 # At some point in the future, this should validate the hook before it
687 660 # accepts it. Probably at least check that the hook takes the number
688 661 # of args it's supposed to.
689 662
690 663 f = types.MethodType(hook,self)
691 664
692 665 # check if the hook is for strdispatcher first
693 666 if str_key is not None:
694 667 sdp = self.strdispatchers.get(name, StrDispatch())
695 668 sdp.add_s(str_key, f, priority )
696 669 self.strdispatchers[name] = sdp
697 670 return
698 671 if re_key is not None:
699 672 sdp = self.strdispatchers.get(name, StrDispatch())
700 673 sdp.add_re(re.compile(re_key), f, priority )
701 674 self.strdispatchers[name] = sdp
702 675 return
703 676
704 677 dp = getattr(self.hooks, name, None)
705 678 if name not in IPython.core.hooks.__all__:
706 679 print "Warning! Hook '%s' is not one of %s" % \
707 680 (name, IPython.core.hooks.__all__ )
708 681 if not dp:
709 682 dp = IPython.core.hooks.CommandChainDispatcher()
710 683
711 684 try:
712 685 dp.add(f,priority)
713 686 except AttributeError:
714 687 # it was not commandchain, plain old func - replace
715 688 dp = f
716 689
717 690 setattr(self.hooks,name, dp)
718 691
719 692 def register_post_execute(self, func):
720 693 """Register a function for calling after code execution.
721 694 """
722 695 if not callable(func):
723 696 raise ValueError('argument %s must be callable' % func)
724 697 self._post_execute[func] = True
725 698
726 699 #-------------------------------------------------------------------------
727 700 # Things related to the "main" module
728 701 #-------------------------------------------------------------------------
729 702
730 703 def new_main_mod(self,ns=None):
731 704 """Return a new 'main' module object for user code execution.
732 705 """
733 706 main_mod = self._user_main_module
734 707 init_fakemod_dict(main_mod,ns)
735 708 return main_mod
736 709
737 710 def cache_main_mod(self,ns,fname):
738 711 """Cache a main module's namespace.
739 712
740 713 When scripts are executed via %run, we must keep a reference to the
741 714 namespace of their __main__ module (a FakeModule instance) around so
742 715 that Python doesn't clear it, rendering objects defined therein
743 716 useless.
744 717
745 718 This method keeps said reference in a private dict, keyed by the
746 719 absolute path of the module object (which corresponds to the script
747 720 path). This way, for multiple executions of the same script we only
748 721 keep one copy of the namespace (the last one), thus preventing memory
749 722 leaks from old references while allowing the objects from the last
750 723 execution to be accessible.
751 724
752 725 Note: we can not allow the actual FakeModule instances to be deleted,
753 726 because of how Python tears down modules (it hard-sets all their
754 727 references to None without regard for reference counts). This method
755 728 must therefore make a *copy* of the given namespace, to allow the
756 729 original module's __dict__ to be cleared and reused.
757 730
758 731
759 732 Parameters
760 733 ----------
761 734 ns : a namespace (a dict, typically)
762 735
763 736 fname : str
764 737 Filename associated with the namespace.
765 738
766 739 Examples
767 740 --------
768 741
769 742 In [10]: import IPython
770 743
771 744 In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
772 745
773 746 In [12]: IPython.__file__ in _ip._main_ns_cache
774 747 Out[12]: True
775 748 """
776 749 self._main_ns_cache[os.path.abspath(fname)] = ns.copy()
777 750
778 751 def clear_main_mod_cache(self):
779 752 """Clear the cache of main modules.
780 753
781 754 Mainly for use by utilities like %reset.
782 755
783 756 Examples
784 757 --------
785 758
786 759 In [15]: import IPython
787 760
788 761 In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
789 762
790 763 In [17]: len(_ip._main_ns_cache) > 0
791 764 Out[17]: True
792 765
793 766 In [18]: _ip.clear_main_mod_cache()
794 767
795 768 In [19]: len(_ip._main_ns_cache) == 0
796 769 Out[19]: True
797 770 """
798 771 self._main_ns_cache.clear()
799 772
800 773 #-------------------------------------------------------------------------
801 774 # Things related to debugging
802 775 #-------------------------------------------------------------------------
803 776
804 777 def init_pdb(self):
805 778 # Set calling of pdb on exceptions
806 779 # self.call_pdb is a property
807 780 self.call_pdb = self.pdb
808 781
809 782 def _get_call_pdb(self):
810 783 return self._call_pdb
811 784
812 785 def _set_call_pdb(self,val):
813 786
814 787 if val not in (0,1,False,True):
815 788 raise ValueError,'new call_pdb value must be boolean'
816 789
817 790 # store value in instance
818 791 self._call_pdb = val
819 792
820 793 # notify the actual exception handlers
821 794 self.InteractiveTB.call_pdb = val
822 795
823 796 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
824 797 'Control auto-activation of pdb at exceptions')
825 798
826 799 def debugger(self,force=False):
827 800 """Call the pydb/pdb debugger.
828 801
829 802 Keywords:
830 803
831 804 - force(False): by default, this routine checks the instance call_pdb
832 805 flag and does not actually invoke the debugger if the flag is false.
833 806 The 'force' option forces the debugger to activate even if the flag
834 807 is false.
835 808 """
836 809
837 810 if not (force or self.call_pdb):
838 811 return
839 812
840 813 if not hasattr(sys,'last_traceback'):
841 814 error('No traceback has been produced, nothing to debug.')
842 815 return
843 816
844 817 # use pydb if available
845 818 if debugger.has_pydb:
846 819 from pydb import pm
847 820 else:
848 821 # fallback to our internal debugger
849 822 pm = lambda : self.InteractiveTB.debugger(force=True)
850 823
851 824 with self.readline_no_record:
852 825 pm()
853 826
854 827 #-------------------------------------------------------------------------
855 828 # Things related to IPython's various namespaces
856 829 #-------------------------------------------------------------------------
857 830
858 831 def init_create_namespaces(self, user_ns=None, user_global_ns=None):
859 832 # Create the namespace where the user will operate. user_ns is
860 833 # normally the only one used, and it is passed to the exec calls as
861 834 # the locals argument. But we do carry a user_global_ns namespace
862 835 # given as the exec 'globals' argument, This is useful in embedding
863 836 # situations where the ipython shell opens in a context where the
864 837 # distinction between locals and globals is meaningful. For
865 838 # non-embedded contexts, it is just the same object as the user_ns dict.
866 839
867 840 # FIXME. For some strange reason, __builtins__ is showing up at user
868 841 # level as a dict instead of a module. This is a manual fix, but I
869 842 # should really track down where the problem is coming from. Alex
870 843 # Schmolck reported this problem first.
871 844
872 845 # A useful post by Alex Martelli on this topic:
873 846 # Re: inconsistent value from __builtins__
874 847 # Von: Alex Martelli <aleaxit@yahoo.com>
875 848 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
876 849 # Gruppen: comp.lang.python
877 850
878 851 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
879 852 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
880 853 # > <type 'dict'>
881 854 # > >>> print type(__builtins__)
882 855 # > <type 'module'>
883 856 # > Is this difference in return value intentional?
884 857
885 858 # Well, it's documented that '__builtins__' can be either a dictionary
886 859 # or a module, and it's been that way for a long time. Whether it's
887 860 # intentional (or sensible), I don't know. In any case, the idea is
888 861 # that if you need to access the built-in namespace directly, you
889 862 # should start with "import __builtin__" (note, no 's') which will
890 863 # definitely give you a module. Yeah, it's somewhat confusing:-(.
891 864
892 865 # These routines return properly built dicts as needed by the rest of
893 866 # the code, and can also be used by extension writers to generate
894 867 # properly initialized namespaces.
895 868 user_ns, user_global_ns = self.make_user_namespaces(user_ns,
896 869 user_global_ns)
897 870
898 871 # Assign namespaces
899 872 # This is the namespace where all normal user variables live
900 873 self.user_ns = user_ns
901 874 self.user_global_ns = user_global_ns
902 875
903 876 # An auxiliary namespace that checks what parts of the user_ns were
904 877 # loaded at startup, so we can list later only variables defined in
905 878 # actual interactive use. Since it is always a subset of user_ns, it
906 879 # doesn't need to be separately tracked in the ns_table.
907 880 self.user_ns_hidden = {}
908 881
909 882 # A namespace to keep track of internal data structures to prevent
910 883 # them from cluttering user-visible stuff. Will be updated later
911 884 self.internal_ns = {}
912 885
913 886 # Now that FakeModule produces a real module, we've run into a nasty
914 887 # problem: after script execution (via %run), the module where the user
915 888 # code ran is deleted. Now that this object is a true module (needed
916 889 # so docetst and other tools work correctly), the Python module
917 890 # teardown mechanism runs over it, and sets to None every variable
918 891 # present in that module. Top-level references to objects from the
919 892 # script survive, because the user_ns is updated with them. However,
920 893 # calling functions defined in the script that use other things from
921 894 # the script will fail, because the function's closure had references
922 895 # to the original objects, which are now all None. So we must protect
923 896 # these modules from deletion by keeping a cache.
924 897 #
925 898 # To avoid keeping stale modules around (we only need the one from the
926 899 # last run), we use a dict keyed with the full path to the script, so
927 900 # only the last version of the module is held in the cache. Note,
928 901 # however, that we must cache the module *namespace contents* (their
929 902 # __dict__). Because if we try to cache the actual modules, old ones
930 903 # (uncached) could be destroyed while still holding references (such as
931 904 # those held by GUI objects that tend to be long-lived)>
932 905 #
933 906 # The %reset command will flush this cache. See the cache_main_mod()
934 907 # and clear_main_mod_cache() methods for details on use.
935 908
936 909 # This is the cache used for 'main' namespaces
937 910 self._main_ns_cache = {}
938 911 # And this is the single instance of FakeModule whose __dict__ we keep
939 912 # copying and clearing for reuse on each %run
940 913 self._user_main_module = FakeModule()
941 914
942 915 # A table holding all the namespaces IPython deals with, so that
943 916 # introspection facilities can search easily.
944 917 self.ns_table = {'user':user_ns,
945 918 'user_global':user_global_ns,
946 919 'internal':self.internal_ns,
947 920 'builtin':__builtin__.__dict__
948 921 }
949 922
950 923 # Similarly, track all namespaces where references can be held and that
951 924 # we can safely clear (so it can NOT include builtin). This one can be
952 925 # a simple list. Note that the main execution namespaces, user_ns and
953 926 # user_global_ns, can NOT be listed here, as clearing them blindly
954 927 # causes errors in object __del__ methods. Instead, the reset() method
955 928 # clears them manually and carefully.
956 929 self.ns_refs_table = [ self.user_ns_hidden,
957 930 self.internal_ns, self._main_ns_cache ]
958 931
959 932 def make_user_namespaces(self, user_ns=None, user_global_ns=None):
960 933 """Return a valid local and global user interactive namespaces.
961 934
962 935 This builds a dict with the minimal information needed to operate as a
963 936 valid IPython user namespace, which you can pass to the various
964 937 embedding classes in ipython. The default implementation returns the
965 938 same dict for both the locals and the globals to allow functions to
966 939 refer to variables in the namespace. Customized implementations can
967 940 return different dicts. The locals dictionary can actually be anything
968 941 following the basic mapping protocol of a dict, but the globals dict
969 942 must be a true dict, not even a subclass. It is recommended that any
970 943 custom object for the locals namespace synchronize with the globals
971 944 dict somehow.
972 945
973 946 Raises TypeError if the provided globals namespace is not a true dict.
974 947
975 948 Parameters
976 949 ----------
977 950 user_ns : dict-like, optional
978 951 The current user namespace. The items in this namespace should
979 952 be included in the output. If None, an appropriate blank
980 953 namespace should be created.
981 954 user_global_ns : dict, optional
982 955 The current user global namespace. The items in this namespace
983 956 should be included in the output. If None, an appropriate
984 957 blank namespace should be created.
985 958
986 959 Returns
987 960 -------
988 961 A pair of dictionary-like object to be used as the local namespace
989 962 of the interpreter and a dict to be used as the global namespace.
990 963 """
991 964
992 965
993 966 # We must ensure that __builtin__ (without the final 's') is always
994 967 # available and pointing to the __builtin__ *module*. For more details:
995 968 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
996 969
997 970 if user_ns is None:
998 971 # Set __name__ to __main__ to better match the behavior of the
999 972 # normal interpreter.
1000 973 user_ns = {'__name__' :'__main__',
1001 974 '__builtin__' : __builtin__,
1002 975 '__builtins__' : __builtin__,
1003 976 }
1004 977 else:
1005 978 user_ns.setdefault('__name__','__main__')
1006 979 user_ns.setdefault('__builtin__',__builtin__)
1007 980 user_ns.setdefault('__builtins__',__builtin__)
1008 981
1009 982 if user_global_ns is None:
1010 983 user_global_ns = user_ns
1011 984 if type(user_global_ns) is not dict:
1012 985 raise TypeError("user_global_ns must be a true dict; got %r"
1013 986 % type(user_global_ns))
1014 987
1015 988 return user_ns, user_global_ns
1016 989
1017 990 def init_sys_modules(self):
1018 991 # We need to insert into sys.modules something that looks like a
1019 992 # module but which accesses the IPython namespace, for shelve and
1020 993 # pickle to work interactively. Normally they rely on getting
1021 994 # everything out of __main__, but for embedding purposes each IPython
1022 995 # instance has its own private namespace, so we can't go shoving
1023 996 # everything into __main__.
1024 997
1025 998 # note, however, that we should only do this for non-embedded
1026 999 # ipythons, which really mimic the __main__.__dict__ with their own
1027 1000 # namespace. Embedded instances, on the other hand, should not do
1028 1001 # this because they need to manage the user local/global namespaces
1029 1002 # only, but they live within a 'normal' __main__ (meaning, they
1030 1003 # shouldn't overtake the execution environment of the script they're
1031 1004 # embedded in).
1032 1005
1033 1006 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
1034 1007
1035 1008 try:
1036 1009 main_name = self.user_ns['__name__']
1037 1010 except KeyError:
1038 1011 raise KeyError('user_ns dictionary MUST have a "__name__" key')
1039 1012 else:
1040 1013 sys.modules[main_name] = FakeModule(self.user_ns)
1041 1014
1042 1015 def init_user_ns(self):
1043 1016 """Initialize all user-visible namespaces to their minimum defaults.
1044 1017
1045 1018 Certain history lists are also initialized here, as they effectively
1046 1019 act as user namespaces.
1047 1020
1048 1021 Notes
1049 1022 -----
1050 1023 All data structures here are only filled in, they are NOT reset by this
1051 1024 method. If they were not empty before, data will simply be added to
1052 1025 therm.
1053 1026 """
1054 1027 # This function works in two parts: first we put a few things in
1055 1028 # user_ns, and we sync that contents into user_ns_hidden so that these
1056 1029 # initial variables aren't shown by %who. After the sync, we add the
1057 1030 # rest of what we *do* want the user to see with %who even on a new
1058 1031 # session (probably nothing, so theye really only see their own stuff)
1059 1032
1060 1033 # The user dict must *always* have a __builtin__ reference to the
1061 1034 # Python standard __builtin__ namespace, which must be imported.
1062 1035 # This is so that certain operations in prompt evaluation can be
1063 1036 # reliably executed with builtins. Note that we can NOT use
1064 1037 # __builtins__ (note the 's'), because that can either be a dict or a
1065 1038 # module, and can even mutate at runtime, depending on the context
1066 1039 # (Python makes no guarantees on it). In contrast, __builtin__ is
1067 1040 # always a module object, though it must be explicitly imported.
1068 1041
1069 1042 # For more details:
1070 1043 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1071 1044 ns = dict(__builtin__ = __builtin__)
1072 1045
1073 1046 # Put 'help' in the user namespace
1074 1047 try:
1075 1048 from site import _Helper
1076 1049 ns['help'] = _Helper()
1077 1050 except ImportError:
1078 1051 warn('help() not available - check site.py')
1079 1052
1080 1053 # make global variables for user access to the histories
1081 1054 ns['_ih'] = self.history_manager.input_hist_parsed
1082 1055 ns['_oh'] = self.history_manager.output_hist
1083 1056 ns['_dh'] = self.history_manager.dir_hist
1084 1057
1085 1058 ns['_sh'] = shadowns
1086 1059
1087 1060 # user aliases to input and output histories. These shouldn't show up
1088 1061 # in %who, as they can have very large reprs.
1089 1062 ns['In'] = self.history_manager.input_hist_parsed
1090 1063 ns['Out'] = self.history_manager.output_hist
1091 1064
1092 1065 # Store myself as the public api!!!
1093 1066 ns['get_ipython'] = self.get_ipython
1094 1067
1095 1068 ns['exit'] = self.exiter
1096 1069 ns['quit'] = self.exiter
1097 1070
1098 1071 # Sync what we've added so far to user_ns_hidden so these aren't seen
1099 1072 # by %who
1100 1073 self.user_ns_hidden.update(ns)
1101 1074
1102 1075 # Anything put into ns now would show up in %who. Think twice before
1103 1076 # putting anything here, as we really want %who to show the user their
1104 1077 # stuff, not our variables.
1105 1078
1106 1079 # Finally, update the real user's namespace
1107 1080 self.user_ns.update(ns)
1108 1081
1109 1082 def reset(self, new_session=True):
1110 1083 """Clear all internal namespaces, and attempt to release references to
1111 1084 user objects.
1112 1085
1113 1086 If new_session is True, a new history session will be opened.
1114 1087 """
1115 1088 # Clear histories
1116 1089 self.history_manager.reset(new_session)
1117 1090 # Reset counter used to index all histories
1118 1091 if new_session:
1119 1092 self.execution_count = 1
1120 1093
1121 1094 # Flush cached output items
1122 1095 self.displayhook.flush()
1123 1096
1124 1097 # Restore the user namespaces to minimal usability
1125 1098 for ns in self.ns_refs_table:
1126 1099 ns.clear()
1127 1100
1128 1101 # The main execution namespaces must be cleared very carefully,
1129 1102 # skipping the deletion of the builtin-related keys, because doing so
1130 1103 # would cause errors in many object's __del__ methods.
1131 1104 for ns in [self.user_ns, self.user_global_ns]:
1132 1105 drop_keys = set(ns.keys())
1133 1106 drop_keys.discard('__builtin__')
1134 1107 drop_keys.discard('__builtins__')
1135 1108 for k in drop_keys:
1136 1109 del ns[k]
1137 1110
1138 1111 # Restore the user namespaces to minimal usability
1139 1112 self.init_user_ns()
1140 1113
1141 1114 # Restore the default and user aliases
1142 1115 self.alias_manager.clear_aliases()
1143 1116 self.alias_manager.init_aliases()
1144 1117
1145 1118 # Flush the private list of module references kept for script
1146 1119 # execution protection
1147 1120 self.clear_main_mod_cache()
1148 1121
1149 1122 # Clear out the namespace from the last %run
1150 1123 self.new_main_mod()
1151 1124
1152 1125 def reset_selective(self, regex=None):
1153 1126 """Clear selective variables from internal namespaces based on a
1154 1127 specified regular expression.
1155 1128
1156 1129 Parameters
1157 1130 ----------
1158 1131 regex : string or compiled pattern, optional
1159 1132 A regular expression pattern that will be used in searching
1160 1133 variable names in the users namespaces.
1161 1134 """
1162 1135 if regex is not None:
1163 1136 try:
1164 1137 m = re.compile(regex)
1165 1138 except TypeError:
1166 1139 raise TypeError('regex must be a string or compiled pattern')
1167 1140 # Search for keys in each namespace that match the given regex
1168 1141 # If a match is found, delete the key/value pair.
1169 1142 for ns in self.ns_refs_table:
1170 1143 for var in ns:
1171 1144 if m.search(var):
1172 1145 del ns[var]
1173 1146
1174 1147 def push(self, variables, interactive=True):
1175 1148 """Inject a group of variables into the IPython user namespace.
1176 1149
1177 1150 Parameters
1178 1151 ----------
1179 1152 variables : dict, str or list/tuple of str
1180 1153 The variables to inject into the user's namespace. If a dict, a
1181 1154 simple update is done. If a str, the string is assumed to have
1182 1155 variable names separated by spaces. A list/tuple of str can also
1183 1156 be used to give the variable names. If just the variable names are
1184 1157 give (list/tuple/str) then the variable values looked up in the
1185 1158 callers frame.
1186 1159 interactive : bool
1187 1160 If True (default), the variables will be listed with the ``who``
1188 1161 magic.
1189 1162 """
1190 1163 vdict = None
1191 1164
1192 1165 # We need a dict of name/value pairs to do namespace updates.
1193 1166 if isinstance(variables, dict):
1194 1167 vdict = variables
1195 1168 elif isinstance(variables, (basestring, list, tuple)):
1196 1169 if isinstance(variables, basestring):
1197 1170 vlist = variables.split()
1198 1171 else:
1199 1172 vlist = variables
1200 1173 vdict = {}
1201 1174 cf = sys._getframe(1)
1202 1175 for name in vlist:
1203 1176 try:
1204 1177 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1205 1178 except:
1206 1179 print ('Could not get variable %s from %s' %
1207 1180 (name,cf.f_code.co_name))
1208 1181 else:
1209 1182 raise ValueError('variables must be a dict/str/list/tuple')
1210 1183
1211 1184 # Propagate variables to user namespace
1212 1185 self.user_ns.update(vdict)
1213 1186
1214 1187 # And configure interactive visibility
1215 1188 config_ns = self.user_ns_hidden
1216 1189 if interactive:
1217 1190 for name, val in vdict.iteritems():
1218 1191 config_ns.pop(name, None)
1219 1192 else:
1220 1193 for name,val in vdict.iteritems():
1221 1194 config_ns[name] = val
1222 1195
1223 1196 #-------------------------------------------------------------------------
1224 1197 # Things related to object introspection
1225 1198 #-------------------------------------------------------------------------
1226 1199
1227 1200 def _ofind(self, oname, namespaces=None):
1228 1201 """Find an object in the available namespaces.
1229 1202
1230 1203 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
1231 1204
1232 1205 Has special code to detect magic functions.
1233 1206 """
1234 1207 #oname = oname.strip()
1235 1208 #print '1- oname: <%r>' % oname # dbg
1236 1209 try:
1237 1210 oname = oname.strip().encode('ascii')
1238 1211 #print '2- oname: <%r>' % oname # dbg
1239 1212 except UnicodeEncodeError:
1240 1213 print 'Python identifiers can only contain ascii characters.'
1241 1214 return dict(found=False)
1242 1215
1243 1216 alias_ns = None
1244 1217 if namespaces is None:
1245 1218 # Namespaces to search in:
1246 1219 # Put them in a list. The order is important so that we
1247 1220 # find things in the same order that Python finds them.
1248 1221 namespaces = [ ('Interactive', self.user_ns),
1249 1222 ('IPython internal', self.internal_ns),
1250 1223 ('Python builtin', __builtin__.__dict__),
1251 1224 ('Alias', self.alias_manager.alias_table),
1252 1225 ]
1253 1226 alias_ns = self.alias_manager.alias_table
1254 1227
1255 1228 # initialize results to 'null'
1256 1229 found = False; obj = None; ospace = None; ds = None;
1257 1230 ismagic = False; isalias = False; parent = None
1258 1231
1259 1232 # We need to special-case 'print', which as of python2.6 registers as a
1260 1233 # function but should only be treated as one if print_function was
1261 1234 # loaded with a future import. In this case, just bail.
1262 1235 if (oname == 'print' and not (self.compile.compiler_flags &
1263 1236 __future__.CO_FUTURE_PRINT_FUNCTION)):
1264 1237 return {'found':found, 'obj':obj, 'namespace':ospace,
1265 1238 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1266 1239
1267 1240 # Look for the given name by splitting it in parts. If the head is
1268 1241 # found, then we look for all the remaining parts as members, and only
1269 1242 # declare success if we can find them all.
1270 1243 oname_parts = oname.split('.')
1271 1244 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
1272 1245 for nsname,ns in namespaces:
1273 1246 try:
1274 1247 obj = ns[oname_head]
1275 1248 except KeyError:
1276 1249 continue
1277 1250 else:
1278 1251 #print 'oname_rest:', oname_rest # dbg
1279 1252 for part in oname_rest:
1280 1253 try:
1281 1254 parent = obj
1282 1255 obj = getattr(obj,part)
1283 1256 except:
1284 1257 # Blanket except b/c some badly implemented objects
1285 1258 # allow __getattr__ to raise exceptions other than
1286 1259 # AttributeError, which then crashes IPython.
1287 1260 break
1288 1261 else:
1289 1262 # If we finish the for loop (no break), we got all members
1290 1263 found = True
1291 1264 ospace = nsname
1292 1265 if ns == alias_ns:
1293 1266 isalias = True
1294 1267 break # namespace loop
1295 1268
1296 1269 # Try to see if it's magic
1297 1270 if not found:
1298 1271 if oname.startswith(ESC_MAGIC):
1299 1272 oname = oname[1:]
1300 1273 obj = getattr(self,'magic_'+oname,None)
1301 1274 if obj is not None:
1302 1275 found = True
1303 1276 ospace = 'IPython internal'
1304 1277 ismagic = True
1305 1278
1306 1279 # Last try: special-case some literals like '', [], {}, etc:
1307 1280 if not found and oname_head in ["''",'""','[]','{}','()']:
1308 1281 obj = eval(oname_head)
1309 1282 found = True
1310 1283 ospace = 'Interactive'
1311 1284
1312 1285 return {'found':found, 'obj':obj, 'namespace':ospace,
1313 1286 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1314 1287
1315 1288 def _ofind_property(self, oname, info):
1316 1289 """Second part of object finding, to look for property details."""
1317 1290 if info.found:
1318 1291 # Get the docstring of the class property if it exists.
1319 1292 path = oname.split('.')
1320 1293 root = '.'.join(path[:-1])
1321 1294 if info.parent is not None:
1322 1295 try:
1323 1296 target = getattr(info.parent, '__class__')
1324 1297 # The object belongs to a class instance.
1325 1298 try:
1326 1299 target = getattr(target, path[-1])
1327 1300 # The class defines the object.
1328 1301 if isinstance(target, property):
1329 1302 oname = root + '.__class__.' + path[-1]
1330 1303 info = Struct(self._ofind(oname))
1331 1304 except AttributeError: pass
1332 1305 except AttributeError: pass
1333 1306
1334 1307 # We return either the new info or the unmodified input if the object
1335 1308 # hadn't been found
1336 1309 return info
1337 1310
1338 1311 def _object_find(self, oname, namespaces=None):
1339 1312 """Find an object and return a struct with info about it."""
1340 1313 inf = Struct(self._ofind(oname, namespaces))
1341 1314 return Struct(self._ofind_property(oname, inf))
1342 1315
1343 1316 def _inspect(self, meth, oname, namespaces=None, **kw):
1344 1317 """Generic interface to the inspector system.
1345 1318
1346 1319 This function is meant to be called by pdef, pdoc & friends."""
1347 1320 info = self._object_find(oname)
1348 1321 if info.found:
1349 1322 pmethod = getattr(self.inspector, meth)
1350 1323 formatter = format_screen if info.ismagic else None
1351 1324 if meth == 'pdoc':
1352 1325 pmethod(info.obj, oname, formatter)
1353 1326 elif meth == 'pinfo':
1354 1327 pmethod(info.obj, oname, formatter, info, **kw)
1355 1328 else:
1356 1329 pmethod(info.obj, oname)
1357 1330 else:
1358 1331 print 'Object `%s` not found.' % oname
1359 1332 return 'not found' # so callers can take other action
1360 1333
1361 1334 def object_inspect(self, oname):
1362 1335 with self.builtin_trap:
1363 1336 info = self._object_find(oname)
1364 1337 if info.found:
1365 1338 return self.inspector.info(info.obj, oname, info=info)
1366 1339 else:
1367 1340 return oinspect.object_info(name=oname, found=False)
1368 1341
1369 1342 #-------------------------------------------------------------------------
1370 1343 # Things related to history management
1371 1344 #-------------------------------------------------------------------------
1372 1345
1373 1346 def init_history(self):
1374 1347 """Sets up the command history, and starts regular autosaves."""
1375 1348 self.history_manager = HistoryManager(shell=self, config=self.config)
1376 1349
1377 1350 #-------------------------------------------------------------------------
1378 1351 # Things related to exception handling and tracebacks (not debugging)
1379 1352 #-------------------------------------------------------------------------
1380 1353
1381 1354 def init_traceback_handlers(self, custom_exceptions):
1382 1355 # Syntax error handler.
1383 1356 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor')
1384 1357
1385 1358 # The interactive one is initialized with an offset, meaning we always
1386 1359 # want to remove the topmost item in the traceback, which is our own
1387 1360 # internal code. Valid modes: ['Plain','Context','Verbose']
1388 1361 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1389 1362 color_scheme='NoColor',
1390 1363 tb_offset = 1,
1391 1364 check_cache=self.compile.check_cache)
1392 1365
1393 1366 # The instance will store a pointer to the system-wide exception hook,
1394 1367 # so that runtime code (such as magics) can access it. This is because
1395 1368 # during the read-eval loop, it may get temporarily overwritten.
1396 1369 self.sys_excepthook = sys.excepthook
1397 1370
1398 1371 # and add any custom exception handlers the user may have specified
1399 1372 self.set_custom_exc(*custom_exceptions)
1400 1373
1401 1374 # Set the exception mode
1402 1375 self.InteractiveTB.set_mode(mode=self.xmode)
1403 1376
1404 1377 def set_custom_exc(self, exc_tuple, handler):
1405 1378 """set_custom_exc(exc_tuple,handler)
1406 1379
1407 1380 Set a custom exception handler, which will be called if any of the
1408 1381 exceptions in exc_tuple occur in the mainloop (specifically, in the
1409 1382 run_code() method.
1410 1383
1411 1384 Inputs:
1412 1385
1413 1386 - exc_tuple: a *tuple* of valid exceptions to call the defined
1414 1387 handler for. It is very important that you use a tuple, and NOT A
1415 1388 LIST here, because of the way Python's except statement works. If
1416 1389 you only want to trap a single exception, use a singleton tuple:
1417 1390
1418 1391 exc_tuple == (MyCustomException,)
1419 1392
1420 1393 - handler: this must be defined as a function with the following
1421 1394 basic interface::
1422 1395
1423 1396 def my_handler(self, etype, value, tb, tb_offset=None)
1424 1397 ...
1425 1398 # The return value must be
1426 1399 return structured_traceback
1427 1400
1428 1401 This will be made into an instance method (via types.MethodType)
1429 1402 of IPython itself, and it will be called if any of the exceptions
1430 1403 listed in the exc_tuple are caught. If the handler is None, an
1431 1404 internal basic one is used, which just prints basic info.
1432 1405
1433 1406 WARNING: by putting in your own exception handler into IPython's main
1434 1407 execution loop, you run a very good chance of nasty crashes. This
1435 1408 facility should only be used if you really know what you are doing."""
1436 1409
1437 1410 assert type(exc_tuple)==type(()) , \
1438 1411 "The custom exceptions must be given AS A TUPLE."
1439 1412
1440 1413 def dummy_handler(self,etype,value,tb):
1441 1414 print '*** Simple custom exception handler ***'
1442 1415 print 'Exception type :',etype
1443 1416 print 'Exception value:',value
1444 1417 print 'Traceback :',tb
1445 1418 #print 'Source code :','\n'.join(self.buffer)
1446 1419
1447 1420 if handler is None: handler = dummy_handler
1448 1421
1449 1422 self.CustomTB = types.MethodType(handler,self)
1450 1423 self.custom_exceptions = exc_tuple
1451 1424
1452 1425 def excepthook(self, etype, value, tb):
1453 1426 """One more defense for GUI apps that call sys.excepthook.
1454 1427
1455 1428 GUI frameworks like wxPython trap exceptions and call
1456 1429 sys.excepthook themselves. I guess this is a feature that
1457 1430 enables them to keep running after exceptions that would
1458 1431 otherwise kill their mainloop. This is a bother for IPython
1459 1432 which excepts to catch all of the program exceptions with a try:
1460 1433 except: statement.
1461 1434
1462 1435 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1463 1436 any app directly invokes sys.excepthook, it will look to the user like
1464 1437 IPython crashed. In order to work around this, we can disable the
1465 1438 CrashHandler and replace it with this excepthook instead, which prints a
1466 1439 regular traceback using our InteractiveTB. In this fashion, apps which
1467 1440 call sys.excepthook will generate a regular-looking exception from
1468 1441 IPython, and the CrashHandler will only be triggered by real IPython
1469 1442 crashes.
1470 1443
1471 1444 This hook should be used sparingly, only in places which are not likely
1472 1445 to be true IPython errors.
1473 1446 """
1474 1447 self.showtraceback((etype,value,tb),tb_offset=0)
1475 1448
1476 1449 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None,
1477 1450 exception_only=False):
1478 1451 """Display the exception that just occurred.
1479 1452
1480 1453 If nothing is known about the exception, this is the method which
1481 1454 should be used throughout the code for presenting user tracebacks,
1482 1455 rather than directly invoking the InteractiveTB object.
1483 1456
1484 1457 A specific showsyntaxerror() also exists, but this method can take
1485 1458 care of calling it if needed, so unless you are explicitly catching a
1486 1459 SyntaxError exception, don't try to analyze the stack manually and
1487 1460 simply call this method."""
1488 1461
1489 1462 try:
1490 1463 if exc_tuple is None:
1491 1464 etype, value, tb = sys.exc_info()
1492 1465 else:
1493 1466 etype, value, tb = exc_tuple
1494 1467
1495 1468 if etype is None:
1496 1469 if hasattr(sys, 'last_type'):
1497 1470 etype, value, tb = sys.last_type, sys.last_value, \
1498 1471 sys.last_traceback
1499 1472 else:
1500 1473 self.write_err('No traceback available to show.\n')
1501 1474 return
1502 1475
1503 1476 if etype is SyntaxError:
1504 1477 # Though this won't be called by syntax errors in the input
1505 1478 # line, there may be SyntaxError cases whith imported code.
1506 1479 self.showsyntaxerror(filename)
1507 1480 elif etype is UsageError:
1508 1481 print "UsageError:", value
1509 1482 else:
1510 1483 # WARNING: these variables are somewhat deprecated and not
1511 1484 # necessarily safe to use in a threaded environment, but tools
1512 1485 # like pdb depend on their existence, so let's set them. If we
1513 1486 # find problems in the field, we'll need to revisit their use.
1514 1487 sys.last_type = etype
1515 1488 sys.last_value = value
1516 1489 sys.last_traceback = tb
1517 1490 if etype in self.custom_exceptions:
1518 1491 # FIXME: Old custom traceback objects may just return a
1519 1492 # string, in that case we just put it into a list
1520 1493 stb = self.CustomTB(etype, value, tb, tb_offset)
1521 1494 if isinstance(ctb, basestring):
1522 1495 stb = [stb]
1523 1496 else:
1524 1497 if exception_only:
1525 1498 stb = ['An exception has occurred, use %tb to see '
1526 1499 'the full traceback.\n']
1527 1500 stb.extend(self.InteractiveTB.get_exception_only(etype,
1528 1501 value))
1529 1502 else:
1530 1503 stb = self.InteractiveTB.structured_traceback(etype,
1531 1504 value, tb, tb_offset=tb_offset)
1532 1505
1533 1506 if self.call_pdb:
1534 1507 # drop into debugger
1535 1508 self.debugger(force=True)
1536 1509
1537 1510 # Actually show the traceback
1538 1511 self._showtraceback(etype, value, stb)
1539 1512
1540 1513 except KeyboardInterrupt:
1541 1514 self.write_err("\nKeyboardInterrupt\n")
1542 1515
1543 1516 def _showtraceback(self, etype, evalue, stb):
1544 1517 """Actually show a traceback.
1545 1518
1546 1519 Subclasses may override this method to put the traceback on a different
1547 1520 place, like a side channel.
1548 1521 """
1549 1522 print >> io.Term.cout, self.InteractiveTB.stb2text(stb)
1550 1523
1551 1524 def showsyntaxerror(self, filename=None):
1552 1525 """Display the syntax error that just occurred.
1553 1526
1554 1527 This doesn't display a stack trace because there isn't one.
1555 1528
1556 1529 If a filename is given, it is stuffed in the exception instead
1557 1530 of what was there before (because Python's parser always uses
1558 1531 "<string>" when reading from a string).
1559 1532 """
1560 1533 etype, value, last_traceback = sys.exc_info()
1561 1534
1562 1535 # See note about these variables in showtraceback() above
1563 1536 sys.last_type = etype
1564 1537 sys.last_value = value
1565 1538 sys.last_traceback = last_traceback
1566 1539
1567 1540 if filename and etype is SyntaxError:
1568 1541 # Work hard to stuff the correct filename in the exception
1569 1542 try:
1570 1543 msg, (dummy_filename, lineno, offset, line) = value
1571 1544 except:
1572 1545 # Not the format we expect; leave it alone
1573 1546 pass
1574 1547 else:
1575 1548 # Stuff in the right filename
1576 1549 try:
1577 1550 # Assume SyntaxError is a class exception
1578 1551 value = SyntaxError(msg, (filename, lineno, offset, line))
1579 1552 except:
1580 1553 # If that failed, assume SyntaxError is a string
1581 1554 value = msg, (filename, lineno, offset, line)
1582 1555 stb = self.SyntaxTB.structured_traceback(etype, value, [])
1583 1556 self._showtraceback(etype, value, stb)
1584 1557
1585 1558 #-------------------------------------------------------------------------
1586 1559 # Things related to readline
1587 1560 #-------------------------------------------------------------------------
1588 1561
1589 1562 def init_readline(self):
1590 1563 """Command history completion/saving/reloading."""
1591 1564
1592 1565 if self.readline_use:
1593 1566 import IPython.utils.rlineimpl as readline
1594 1567
1595 1568 self.rl_next_input = None
1596 1569 self.rl_do_indent = False
1597 1570
1598 1571 if not self.readline_use or not readline.have_readline:
1599 1572 self.has_readline = False
1600 1573 self.readline = None
1601 1574 # Set a number of methods that depend on readline to be no-op
1602 1575 self.set_readline_completer = no_op
1603 1576 self.set_custom_completer = no_op
1604 1577 self.set_completer_frame = no_op
1605 1578 warn('Readline services not available or not loaded.')
1606 1579 else:
1607 1580 self.has_readline = True
1608 1581 self.readline = readline
1609 1582 sys.modules['readline'] = readline
1610 1583
1611 1584 # Platform-specific configuration
1612 1585 if os.name == 'nt':
1613 1586 # FIXME - check with Frederick to see if we can harmonize
1614 1587 # naming conventions with pyreadline to avoid this
1615 1588 # platform-dependent check
1616 1589 self.readline_startup_hook = readline.set_pre_input_hook
1617 1590 else:
1618 1591 self.readline_startup_hook = readline.set_startup_hook
1619 1592
1620 1593 # Load user's initrc file (readline config)
1621 1594 # Or if libedit is used, load editrc.
1622 1595 inputrc_name = os.environ.get('INPUTRC')
1623 1596 if inputrc_name is None:
1624 1597 home_dir = get_home_dir()
1625 1598 if home_dir is not None:
1626 1599 inputrc_name = '.inputrc'
1627 1600 if readline.uses_libedit:
1628 1601 inputrc_name = '.editrc'
1629 1602 inputrc_name = os.path.join(home_dir, inputrc_name)
1630 1603 if os.path.isfile(inputrc_name):
1631 1604 try:
1632 1605 readline.read_init_file(inputrc_name)
1633 1606 except:
1634 1607 warn('Problems reading readline initialization file <%s>'
1635 1608 % inputrc_name)
1636 1609
1637 1610 # Configure readline according to user's prefs
1638 1611 # This is only done if GNU readline is being used. If libedit
1639 1612 # is being used (as on Leopard) the readline config is
1640 1613 # not run as the syntax for libedit is different.
1641 1614 if not readline.uses_libedit:
1642 1615 for rlcommand in self.readline_parse_and_bind:
1643 1616 #print "loading rl:",rlcommand # dbg
1644 1617 readline.parse_and_bind(rlcommand)
1645 1618
1646 1619 # Remove some chars from the delimiters list. If we encounter
1647 1620 # unicode chars, discard them.
1648 1621 delims = readline.get_completer_delims().encode("ascii", "ignore")
1649 1622 delims = delims.translate(None, self.readline_remove_delims)
1650 1623 delims = delims.replace(ESC_MAGIC, '')
1651 1624 readline.set_completer_delims(delims)
1652 1625 # otherwise we end up with a monster history after a while:
1653 1626 readline.set_history_length(self.history_length)
1654 1627
1655 1628 self.refill_readline_hist()
1656 1629 self.readline_no_record = ReadlineNoRecord(self)
1657 1630
1658 1631 # Configure auto-indent for all platforms
1659 1632 self.set_autoindent(self.autoindent)
1660 1633
1661 1634 def refill_readline_hist(self):
1662 1635 # Load the last 1000 lines from history
1663 1636 self.readline.clear_history()
1664 1637 stdin_encoding = sys.stdin.encoding or "utf-8"
1665 1638 for _, _, cell in self.history_manager.get_tail(1000,
1666 1639 include_latest=True):
1667 1640 if cell.strip(): # Ignore blank lines
1668 1641 for line in cell.splitlines():
1669 1642 self.readline.add_history(line.encode(stdin_encoding))
1670 1643
1671 1644 def set_next_input(self, s):
1672 1645 """ Sets the 'default' input string for the next command line.
1673 1646
1674 1647 Requires readline.
1675 1648
1676 1649 Example:
1677 1650
1678 1651 [D:\ipython]|1> _ip.set_next_input("Hello Word")
1679 1652 [D:\ipython]|2> Hello Word_ # cursor is here
1680 1653 """
1681 1654
1682 1655 self.rl_next_input = s
1683 1656
1684 1657 # Maybe move this to the terminal subclass?
1685 1658 def pre_readline(self):
1686 1659 """readline hook to be used at the start of each line.
1687 1660
1688 1661 Currently it handles auto-indent only."""
1689 1662
1690 1663 if self.rl_do_indent:
1691 1664 self.readline.insert_text(self._indent_current_str())
1692 1665 if self.rl_next_input is not None:
1693 1666 self.readline.insert_text(self.rl_next_input)
1694 1667 self.rl_next_input = None
1695 1668
1696 1669 def _indent_current_str(self):
1697 1670 """return the current level of indentation as a string"""
1698 1671 return self.input_splitter.indent_spaces * ' '
1699 1672
1700 1673 #-------------------------------------------------------------------------
1701 1674 # Things related to text completion
1702 1675 #-------------------------------------------------------------------------
1703 1676
1704 1677 def init_completer(self):
1705 1678 """Initialize the completion machinery.
1706 1679
1707 1680 This creates completion machinery that can be used by client code,
1708 1681 either interactively in-process (typically triggered by the readline
1709 1682 library), programatically (such as in test suites) or out-of-prcess
1710 1683 (typically over the network by remote frontends).
1711 1684 """
1712 1685 from IPython.core.completer import IPCompleter
1713 1686 from IPython.core.completerlib import (module_completer,
1714 1687 magic_run_completer, cd_completer)
1715 1688
1716 1689 self.Completer = IPCompleter(self,
1717 1690 self.user_ns,
1718 1691 self.user_global_ns,
1719 1692 self.readline_omit__names,
1720 1693 self.alias_manager.alias_table,
1721 1694 self.has_readline)
1722 1695
1723 1696 # Add custom completers to the basic ones built into IPCompleter
1724 1697 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1725 1698 self.strdispatchers['complete_command'] = sdisp
1726 1699 self.Completer.custom_completers = sdisp
1727 1700
1728 1701 self.set_hook('complete_command', module_completer, str_key = 'import')
1729 1702 self.set_hook('complete_command', module_completer, str_key = 'from')
1730 1703 self.set_hook('complete_command', magic_run_completer, str_key = '%run')
1731 1704 self.set_hook('complete_command', cd_completer, str_key = '%cd')
1732 1705
1733 1706 # Only configure readline if we truly are using readline. IPython can
1734 1707 # do tab-completion over the network, in GUIs, etc, where readline
1735 1708 # itself may be absent
1736 1709 if self.has_readline:
1737 1710 self.set_readline_completer()
1738 1711
1739 1712 def complete(self, text, line=None, cursor_pos=None):
1740 1713 """Return the completed text and a list of completions.
1741 1714
1742 1715 Parameters
1743 1716 ----------
1744 1717
1745 1718 text : string
1746 1719 A string of text to be completed on. It can be given as empty and
1747 1720 instead a line/position pair are given. In this case, the
1748 1721 completer itself will split the line like readline does.
1749 1722
1750 1723 line : string, optional
1751 1724 The complete line that text is part of.
1752 1725
1753 1726 cursor_pos : int, optional
1754 1727 The position of the cursor on the input line.
1755 1728
1756 1729 Returns
1757 1730 -------
1758 1731 text : string
1759 1732 The actual text that was completed.
1760 1733
1761 1734 matches : list
1762 1735 A sorted list with all possible completions.
1763 1736
1764 1737 The optional arguments allow the completion to take more context into
1765 1738 account, and are part of the low-level completion API.
1766 1739
1767 1740 This is a wrapper around the completion mechanism, similar to what
1768 1741 readline does at the command line when the TAB key is hit. By
1769 1742 exposing it as a method, it can be used by other non-readline
1770 1743 environments (such as GUIs) for text completion.
1771 1744
1772 1745 Simple usage example:
1773 1746
1774 1747 In [1]: x = 'hello'
1775 1748
1776 1749 In [2]: _ip.complete('x.l')
1777 1750 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
1778 1751 """
1779 1752
1780 1753 # Inject names into __builtin__ so we can complete on the added names.
1781 1754 with self.builtin_trap:
1782 1755 return self.Completer.complete(text, line, cursor_pos)
1783 1756
1784 1757 def set_custom_completer(self, completer, pos=0):
1785 1758 """Adds a new custom completer function.
1786 1759
1787 1760 The position argument (defaults to 0) is the index in the completers
1788 1761 list where you want the completer to be inserted."""
1789 1762
1790 1763 newcomp = types.MethodType(completer,self.Completer)
1791 1764 self.Completer.matchers.insert(pos,newcomp)
1792 1765
1793 1766 def set_readline_completer(self):
1794 1767 """Reset readline's completer to be our own."""
1795 1768 self.readline.set_completer(self.Completer.rlcomplete)
1796 1769
1797 1770 def set_completer_frame(self, frame=None):
1798 1771 """Set the frame of the completer."""
1799 1772 if frame:
1800 1773 self.Completer.namespace = frame.f_locals
1801 1774 self.Completer.global_namespace = frame.f_globals
1802 1775 else:
1803 1776 self.Completer.namespace = self.user_ns
1804 1777 self.Completer.global_namespace = self.user_global_ns
1805 1778
1806 1779 #-------------------------------------------------------------------------
1807 1780 # Things related to magics
1808 1781 #-------------------------------------------------------------------------
1809 1782
1810 1783 def init_magics(self):
1811 1784 # FIXME: Move the color initialization to the DisplayHook, which
1812 1785 # should be split into a prompt manager and displayhook. We probably
1813 1786 # even need a centralize colors management object.
1814 1787 self.magic_colors(self.colors)
1815 1788 # History was moved to a separate module
1816 1789 from . import history
1817 1790 history.init_ipython(self)
1818 1791
1819 1792 def magic(self,arg_s):
1820 1793 """Call a magic function by name.
1821 1794
1822 1795 Input: a string containing the name of the magic function to call and
1823 1796 any additional arguments to be passed to the magic.
1824 1797
1825 1798 magic('name -opt foo bar') is equivalent to typing at the ipython
1826 1799 prompt:
1827 1800
1828 1801 In[1]: %name -opt foo bar
1829 1802
1830 1803 To call a magic without arguments, simply use magic('name').
1831 1804
1832 1805 This provides a proper Python function to call IPython's magics in any
1833 1806 valid Python code you can type at the interpreter, including loops and
1834 1807 compound statements.
1835 1808 """
1836 1809 args = arg_s.split(' ',1)
1837 1810 magic_name = args[0]
1838 1811 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
1839 1812
1840 1813 try:
1841 1814 magic_args = args[1]
1842 1815 except IndexError:
1843 1816 magic_args = ''
1844 1817 fn = getattr(self,'magic_'+magic_name,None)
1845 1818 if fn is None:
1846 1819 error("Magic function `%s` not found." % magic_name)
1847 1820 else:
1848 1821 magic_args = self.var_expand(magic_args,1)
1849 1822 # Grab local namespace if we need it:
1850 1823 if getattr(fn, "needs_local_scope", False):
1851 1824 self._magic_locals = sys._getframe(1).f_locals
1852 1825 with self.builtin_trap:
1853 1826 result = fn(magic_args)
1854 1827 # Ensure we're not keeping object references around:
1855 1828 self._magic_locals = {}
1856 1829 return result
1857 1830
1858 1831 def define_magic(self, magicname, func):
1859 1832 """Expose own function as magic function for ipython
1860 1833
1861 1834 def foo_impl(self,parameter_s=''):
1862 1835 'My very own magic!. (Use docstrings, IPython reads them).'
1863 1836 print 'Magic function. Passed parameter is between < >:'
1864 1837 print '<%s>' % parameter_s
1865 1838 print 'The self object is:',self
1866 1839
1867 1840 self.define_magic('foo',foo_impl)
1868 1841 """
1869 1842
1870 1843 import new
1871 1844 im = types.MethodType(func,self)
1872 1845 old = getattr(self, "magic_" + magicname, None)
1873 1846 setattr(self, "magic_" + magicname, im)
1874 1847 return old
1875 1848
1876 1849 #-------------------------------------------------------------------------
1877 1850 # Things related to macros
1878 1851 #-------------------------------------------------------------------------
1879 1852
1880 1853 def define_macro(self, name, themacro):
1881 1854 """Define a new macro
1882 1855
1883 1856 Parameters
1884 1857 ----------
1885 1858 name : str
1886 1859 The name of the macro.
1887 1860 themacro : str or Macro
1888 1861 The action to do upon invoking the macro. If a string, a new
1889 1862 Macro object is created by passing the string to it.
1890 1863 """
1891 1864
1892 1865 from IPython.core import macro
1893 1866
1894 1867 if isinstance(themacro, basestring):
1895 1868 themacro = macro.Macro(themacro)
1896 1869 if not isinstance(themacro, macro.Macro):
1897 1870 raise ValueError('A macro must be a string or a Macro instance.')
1898 1871 self.user_ns[name] = themacro
1899 1872
1900 1873 #-------------------------------------------------------------------------
1901 1874 # Things related to the running of system commands
1902 1875 #-------------------------------------------------------------------------
1903 1876
1904 1877 def system(self, cmd):
1905 1878 """Call the given cmd in a subprocess.
1906 1879
1907 1880 Parameters
1908 1881 ----------
1909 1882 cmd : str
1910 1883 Command to execute (can not end in '&', as bacground processes are
1911 1884 not supported.
1912 1885 """
1913 1886 # We do not support backgrounding processes because we either use
1914 1887 # pexpect or pipes to read from. Users can always just call
1915 1888 # os.system() if they really want a background process.
1916 1889 if cmd.endswith('&'):
1917 1890 raise OSError("Background processes not supported.")
1918 1891
1919 1892 return system(self.var_expand(cmd, depth=2))
1920 1893
1921 1894 def getoutput(self, cmd, split=True):
1922 1895 """Get output (possibly including stderr) from a subprocess.
1923 1896
1924 1897 Parameters
1925 1898 ----------
1926 1899 cmd : str
1927 1900 Command to execute (can not end in '&', as background processes are
1928 1901 not supported.
1929 1902 split : bool, optional
1930 1903
1931 1904 If True, split the output into an IPython SList. Otherwise, an
1932 1905 IPython LSString is returned. These are objects similar to normal
1933 1906 lists and strings, with a few convenience attributes for easier
1934 1907 manipulation of line-based output. You can use '?' on them for
1935 1908 details.
1936 1909 """
1937 1910 if cmd.endswith('&'):
1938 1911 raise OSError("Background processes not supported.")
1939 1912 out = getoutput(self.var_expand(cmd, depth=2))
1940 1913 if split:
1941 1914 out = SList(out.splitlines())
1942 1915 else:
1943 1916 out = LSString(out)
1944 1917 return out
1945 1918
1946 1919 #-------------------------------------------------------------------------
1947 1920 # Things related to aliases
1948 1921 #-------------------------------------------------------------------------
1949 1922
1950 1923 def init_alias(self):
1951 1924 self.alias_manager = AliasManager(shell=self, config=self.config)
1952 1925 self.ns_table['alias'] = self.alias_manager.alias_table,
1953 1926
1954 1927 #-------------------------------------------------------------------------
1955 1928 # Things related to extensions and plugins
1956 1929 #-------------------------------------------------------------------------
1957 1930
1958 1931 def init_extension_manager(self):
1959 1932 self.extension_manager = ExtensionManager(shell=self, config=self.config)
1960 1933
1961 1934 def init_plugin_manager(self):
1962 1935 self.plugin_manager = PluginManager(config=self.config)
1963 1936
1964 1937 #-------------------------------------------------------------------------
1965 1938 # Things related to payloads
1966 1939 #-------------------------------------------------------------------------
1967 1940
1968 1941 def init_payload(self):
1969 1942 self.payload_manager = PayloadManager(config=self.config)
1970 1943
1971 1944 #-------------------------------------------------------------------------
1972 1945 # Things related to the prefilter
1973 1946 #-------------------------------------------------------------------------
1974 1947
1975 1948 def init_prefilter(self):
1976 1949 self.prefilter_manager = PrefilterManager(shell=self, config=self.config)
1977 1950 # Ultimately this will be refactored in the new interpreter code, but
1978 1951 # for now, we should expose the main prefilter method (there's legacy
1979 1952 # code out there that may rely on this).
1980 1953 self.prefilter = self.prefilter_manager.prefilter_lines
1981 1954
1982 1955 def auto_rewrite_input(self, cmd):
1983 1956 """Print to the screen the rewritten form of the user's command.
1984 1957
1985 1958 This shows visual feedback by rewriting input lines that cause
1986 1959 automatic calling to kick in, like::
1987 1960
1988 1961 /f x
1989 1962
1990 1963 into::
1991 1964
1992 1965 ------> f(x)
1993 1966
1994 1967 after the user's input prompt. This helps the user understand that the
1995 1968 input line was transformed automatically by IPython.
1996 1969 """
1997 1970 rw = self.displayhook.prompt1.auto_rewrite() + cmd
1998 1971
1999 1972 try:
2000 1973 # plain ascii works better w/ pyreadline, on some machines, so
2001 1974 # we use it and only print uncolored rewrite if we have unicode
2002 1975 rw = str(rw)
2003 1976 print >> IPython.utils.io.Term.cout, rw
2004 1977 except UnicodeEncodeError:
2005 1978 print "------> " + cmd
2006 1979
2007 1980 #-------------------------------------------------------------------------
2008 1981 # Things related to extracting values/expressions from kernel and user_ns
2009 1982 #-------------------------------------------------------------------------
2010 1983
2011 1984 def _simple_error(self):
2012 1985 etype, value = sys.exc_info()[:2]
2013 1986 return u'[ERROR] {e.__name__}: {v}'.format(e=etype, v=value)
2014 1987
2015 1988 def user_variables(self, names):
2016 1989 """Get a list of variable names from the user's namespace.
2017 1990
2018 1991 Parameters
2019 1992 ----------
2020 1993 names : list of strings
2021 1994 A list of names of variables to be read from the user namespace.
2022 1995
2023 1996 Returns
2024 1997 -------
2025 1998 A dict, keyed by the input names and with the repr() of each value.
2026 1999 """
2027 2000 out = {}
2028 2001 user_ns = self.user_ns
2029 2002 for varname in names:
2030 2003 try:
2031 2004 value = repr(user_ns[varname])
2032 2005 except:
2033 2006 value = self._simple_error()
2034 2007 out[varname] = value
2035 2008 return out
2036 2009
2037 2010 def user_expressions(self, expressions):
2038 2011 """Evaluate a dict of expressions in the user's namespace.
2039 2012
2040 2013 Parameters
2041 2014 ----------
2042 2015 expressions : dict
2043 2016 A dict with string keys and string values. The expression values
2044 2017 should be valid Python expressions, each of which will be evaluated
2045 2018 in the user namespace.
2046 2019
2047 2020 Returns
2048 2021 -------
2049 2022 A dict, keyed like the input expressions dict, with the repr() of each
2050 2023 value.
2051 2024 """
2052 2025 out = {}
2053 2026 user_ns = self.user_ns
2054 2027 global_ns = self.user_global_ns
2055 2028 for key, expr in expressions.iteritems():
2056 2029 try:
2057 2030 value = repr(eval(expr, global_ns, user_ns))
2058 2031 except:
2059 2032 value = self._simple_error()
2060 2033 out[key] = value
2061 2034 return out
2062 2035
2063 2036 #-------------------------------------------------------------------------
2064 2037 # Things related to the running of code
2065 2038 #-------------------------------------------------------------------------
2066 2039
2067 2040 def ex(self, cmd):
2068 2041 """Execute a normal python statement in user namespace."""
2069 2042 with self.builtin_trap:
2070 2043 exec cmd in self.user_global_ns, self.user_ns
2071 2044
2072 2045 def ev(self, expr):
2073 2046 """Evaluate python expression expr in user namespace.
2074 2047
2075 2048 Returns the result of evaluation
2076 2049 """
2077 2050 with self.builtin_trap:
2078 2051 return eval(expr, self.user_global_ns, self.user_ns)
2079 2052
2080 2053 def safe_execfile(self, fname, *where, **kw):
2081 2054 """A safe version of the builtin execfile().
2082 2055
2083 2056 This version will never throw an exception, but instead print
2084 2057 helpful error messages to the screen. This only works on pure
2085 2058 Python files with the .py extension.
2086 2059
2087 2060 Parameters
2088 2061 ----------
2089 2062 fname : string
2090 2063 The name of the file to be executed.
2091 2064 where : tuple
2092 2065 One or two namespaces, passed to execfile() as (globals,locals).
2093 2066 If only one is given, it is passed as both.
2094 2067 exit_ignore : bool (False)
2095 2068 If True, then silence SystemExit for non-zero status (it is always
2096 2069 silenced for zero status, as it is so common).
2097 2070 """
2098 2071 kw.setdefault('exit_ignore', False)
2099 2072
2100 2073 fname = os.path.abspath(os.path.expanduser(fname))
2101 2074 # Make sure we have a .py file
2102 2075 if not fname.endswith('.py'):
2103 2076 warn('File must end with .py to be run using execfile: <%s>' % fname)
2104 2077
2105 2078 # Make sure we can open the file
2106 2079 try:
2107 2080 with open(fname) as thefile:
2108 2081 pass
2109 2082 except:
2110 2083 warn('Could not open file <%s> for safe execution.' % fname)
2111 2084 return
2112 2085
2113 2086 # Find things also in current directory. This is needed to mimic the
2114 2087 # behavior of running a script from the system command line, where
2115 2088 # Python inserts the script's directory into sys.path
2116 2089 dname = os.path.dirname(fname)
2117 2090
2118 2091 if isinstance(fname, unicode):
2119 2092 # execfile uses default encoding instead of filesystem encoding
2120 2093 # so unicode filenames will fail
2121 2094 fname = fname.encode(sys.getfilesystemencoding() or sys.getdefaultencoding())
2122 2095
2123 2096 with prepended_to_syspath(dname):
2124 2097 try:
2125 2098 execfile(fname,*where)
2126 2099 except SystemExit, status:
2127 2100 # If the call was made with 0 or None exit status (sys.exit(0)
2128 2101 # or sys.exit() ), don't bother showing a traceback, as both of
2129 2102 # these are considered normal by the OS:
2130 2103 # > python -c'import sys;sys.exit(0)'; echo $?
2131 2104 # 0
2132 2105 # > python -c'import sys;sys.exit()'; echo $?
2133 2106 # 0
2134 2107 # For other exit status, we show the exception unless
2135 2108 # explicitly silenced, but only in short form.
2136 2109 if status.code not in (0, None) and not kw['exit_ignore']:
2137 2110 self.showtraceback(exception_only=True)
2138 2111 except:
2139 2112 self.showtraceback()
2140 2113
2141 2114 def safe_execfile_ipy(self, fname):
2142 2115 """Like safe_execfile, but for .ipy files with IPython syntax.
2143 2116
2144 2117 Parameters
2145 2118 ----------
2146 2119 fname : str
2147 2120 The name of the file to execute. The filename must have a
2148 2121 .ipy extension.
2149 2122 """
2150 2123 fname = os.path.abspath(os.path.expanduser(fname))
2151 2124
2152 2125 # Make sure we have a .py file
2153 2126 if not fname.endswith('.ipy'):
2154 2127 warn('File must end with .py to be run using execfile: <%s>' % fname)
2155 2128
2156 2129 # Make sure we can open the file
2157 2130 try:
2158 2131 with open(fname) as thefile:
2159 2132 pass
2160 2133 except:
2161 2134 warn('Could not open file <%s> for safe execution.' % fname)
2162 2135 return
2163 2136
2164 2137 # Find things also in current directory. This is needed to mimic the
2165 2138 # behavior of running a script from the system command line, where
2166 2139 # Python inserts the script's directory into sys.path
2167 2140 dname = os.path.dirname(fname)
2168 2141
2169 2142 with prepended_to_syspath(dname):
2170 2143 try:
2171 2144 with open(fname) as thefile:
2172 2145 # self.run_cell currently captures all exceptions
2173 2146 # raised in user code. It would be nice if there were
2174 2147 # versions of runlines, execfile that did raise, so
2175 2148 # we could catch the errors.
2176 2149 self.run_cell(thefile.read(), store_history=False)
2177 2150 except:
2178 2151 self.showtraceback()
2179 2152 warn('Unknown failure executing file: <%s>' % fname)
2180 2153
2181 2154 def run_cell(self, raw_cell, store_history=True):
2182 2155 """Run a complete IPython cell.
2183 2156
2184 2157 Parameters
2185 2158 ----------
2186 2159 raw_cell : str
2187 2160 The code (including IPython code such as %magic functions) to run.
2188 2161 store_history : bool
2189 2162 If True, the raw and translated cell will be stored in IPython's
2190 2163 history. For user code calling back into IPython's machinery, this
2191 2164 should be set to False.
2192 2165 """
2193 2166 if (not raw_cell) or raw_cell.isspace():
2194 2167 return
2195 2168
2196 2169 for line in raw_cell.splitlines():
2197 2170 self.input_splitter.push(line)
2198 2171 cell = self.input_splitter.source_reset()
2199 2172
2200 2173 with self.builtin_trap:
2201 2174 if len(cell.splitlines()) == 1:
2202 2175 cell = self.prefilter_manager.prefilter_lines(cell)
2203 2176
2204 2177 # Store raw and processed history
2205 2178 if store_history:
2206 2179 self.history_manager.store_inputs(self.execution_count,
2207 2180 cell, raw_cell)
2208 2181
2209 2182 self.logger.log(cell, raw_cell)
2210 2183
2211 2184 cell_name = self.compile.cache(cell, self.execution_count)
2212 2185
2213 2186 with self.display_trap:
2214 2187 try:
2215 2188 code_ast = ast.parse(cell, filename=cell_name)
2216 2189 except (OverflowError, SyntaxError, ValueError, TypeError,
2217 2190 MemoryError):
2218 2191 self.showsyntaxerror()
2219 2192 self.execution_count += 1
2220 2193 return None
2221 2194
2222 2195 self.run_ast_nodes(code_ast.body, cell_name,
2223 2196 interactivity="last_expr")
2224 2197
2225 2198 # Execute any registered post-execution functions.
2226 2199 for func, status in self._post_execute.iteritems():
2227 2200 if not status:
2228 2201 continue
2229 2202 try:
2230 2203 func()
2231 2204 except:
2232 2205 self.showtraceback()
2233 2206 # Deactivate failing function
2234 2207 self._post_execute[func] = False
2235 2208
2236 2209 if store_history:
2237 2210 # Write output to the database. Does nothing unless
2238 2211 # history output logging is enabled.
2239 2212 self.history_manager.store_output(self.execution_count)
2240 2213 # Each cell is a *single* input, regardless of how many lines it has
2241 2214 self.execution_count += 1
2242 2215
2243 2216 def run_ast_nodes(self, nodelist, cell_name, interactivity='last_expr'):
2244 2217 """Run a sequence of AST nodes. The execution mode depends on the
2245 2218 interactivity parameter.
2246 2219
2247 2220 Parameters
2248 2221 ----------
2249 2222 nodelist : list
2250 2223 A sequence of AST nodes to run.
2251 2224 cell_name : str
2252 2225 Will be passed to the compiler as the filename of the cell. Typically
2253 2226 the value returned by ip.compile.cache(cell).
2254 2227 interactivity : str
2255 2228 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
2256 2229 run interactively (displaying output from expressions). 'last_expr'
2257 2230 will run the last node interactively only if it is an expression (i.e.
2258 2231 expressions in loops or other blocks are not displayed. Other values
2259 2232 for this parameter will raise a ValueError.
2260 2233 """
2261 2234 if not nodelist:
2262 2235 return
2263 2236
2264 2237 if interactivity == 'last_expr':
2265 2238 if isinstance(nodelist[-1], ast.Expr):
2266 2239 interactivity = "last"
2267 2240 else:
2268 2241 interactivity = "none"
2269 2242
2270 2243 if interactivity == 'none':
2271 2244 to_run_exec, to_run_interactive = nodelist, []
2272 2245 elif interactivity == 'last':
2273 2246 to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:]
2274 2247 elif interactivity == 'all':
2275 2248 to_run_exec, to_run_interactive = [], nodelist
2276 2249 else:
2277 2250 raise ValueError("Interactivity was %r" % interactivity)
2278 2251
2279 2252 exec_count = self.execution_count
2280 2253
2281 2254 for i, node in enumerate(to_run_exec):
2282 2255 mod = ast.Module([node])
2283 2256 code = self.compile(mod, cell_name, "exec")
2284 2257 if self.run_code(code):
2285 2258 return True
2286 2259
2287 2260 for i, node in enumerate(to_run_interactive):
2288 2261 mod = ast.Interactive([node])
2289 2262 code = self.compile(mod, cell_name, "single")
2290 2263 if self.run_code(code):
2291 2264 return True
2292 2265
2293 2266 return False
2294 2267
2295 2268 def run_code(self, code_obj):
2296 2269 """Execute a code object.
2297 2270
2298 2271 When an exception occurs, self.showtraceback() is called to display a
2299 2272 traceback.
2300 2273
2301 2274 Parameters
2302 2275 ----------
2303 2276 code_obj : code object
2304 2277 A compiled code object, to be executed
2305 2278 post_execute : bool [default: True]
2306 2279 whether to call post_execute hooks after this particular execution.
2307 2280
2308 2281 Returns
2309 2282 -------
2310 2283 False : successful execution.
2311 2284 True : an error occurred.
2312 2285 """
2313 2286
2314 2287 # Set our own excepthook in case the user code tries to call it
2315 2288 # directly, so that the IPython crash handler doesn't get triggered
2316 2289 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
2317 2290
2318 2291 # we save the original sys.excepthook in the instance, in case config
2319 2292 # code (such as magics) needs access to it.
2320 2293 self.sys_excepthook = old_excepthook
2321 2294 outflag = 1 # happens in more places, so it's easier as default
2322 2295 try:
2323 2296 try:
2324 2297 self.hooks.pre_run_code_hook()
2325 2298 #rprint('Running code', repr(code_obj)) # dbg
2326 2299 exec code_obj in self.user_global_ns, self.user_ns
2327 2300 finally:
2328 2301 # Reset our crash handler in place
2329 2302 sys.excepthook = old_excepthook
2330 2303 except SystemExit:
2331 2304 self.showtraceback(exception_only=True)
2332 2305 warn("To exit: use 'exit', 'quit', or Ctrl-D.", level=1)
2333 2306 except self.custom_exceptions:
2334 2307 etype,value,tb = sys.exc_info()
2335 2308 self.CustomTB(etype,value,tb)
2336 2309 except:
2337 2310 self.showtraceback()
2338 2311 else:
2339 2312 outflag = 0
2340 2313 if softspace(sys.stdout, 0):
2341 2314 print
2342 2315
2343 2316 return outflag
2344 2317
2345 2318 # For backwards compatibility
2346 2319 runcode = run_code
2347 2320
2348 2321 #-------------------------------------------------------------------------
2349 2322 # Things related to GUI support and pylab
2350 2323 #-------------------------------------------------------------------------
2351 2324
2352 2325 def enable_pylab(self, gui=None):
2353 2326 raise NotImplementedError('Implement enable_pylab in a subclass')
2354 2327
2355 2328 #-------------------------------------------------------------------------
2356 2329 # Utilities
2357 2330 #-------------------------------------------------------------------------
2358 2331
2359 2332 def var_expand(self,cmd,depth=0):
2360 2333 """Expand python variables in a string.
2361 2334
2362 2335 The depth argument indicates how many frames above the caller should
2363 2336 be walked to look for the local namespace where to expand variables.
2364 2337
2365 2338 The global namespace for expansion is always the user's interactive
2366 2339 namespace.
2367 2340 """
2368 2341 res = ItplNS(cmd, self.user_ns, # globals
2369 2342 # Skip our own frame in searching for locals:
2370 2343 sys._getframe(depth+1).f_locals # locals
2371 2344 )
2372 2345 return str(res).decode(res.codec)
2373 2346
2374 2347 def mktempfile(self, data=None, prefix='ipython_edit_'):
2375 2348 """Make a new tempfile and return its filename.
2376 2349
2377 2350 This makes a call to tempfile.mktemp, but it registers the created
2378 2351 filename internally so ipython cleans it up at exit time.
2379 2352
2380 2353 Optional inputs:
2381 2354
2382 2355 - data(None): if data is given, it gets written out to the temp file
2383 2356 immediately, and the file is closed again."""
2384 2357
2385 2358 filename = tempfile.mktemp('.py', prefix)
2386 2359 self.tempfiles.append(filename)
2387 2360
2388 2361 if data:
2389 2362 tmp_file = open(filename,'w')
2390 2363 tmp_file.write(data)
2391 2364 tmp_file.close()
2392 2365 return filename
2393 2366
2394 2367 # TODO: This should be removed when Term is refactored.
2395 2368 def write(self,data):
2396 2369 """Write a string to the default output"""
2397 2370 io.Term.cout.write(data)
2398 2371
2399 2372 # TODO: This should be removed when Term is refactored.
2400 2373 def write_err(self,data):
2401 2374 """Write a string to the default error output"""
2402 2375 io.Term.cerr.write(data)
2403 2376
2404 2377 def ask_yes_no(self,prompt,default=True):
2405 2378 if self.quiet:
2406 2379 return True
2407 2380 return ask_yes_no(prompt,default)
2408 2381
2409 2382 def show_usage(self):
2410 2383 """Show a usage message"""
2411 2384 page.page(IPython.core.usage.interactive_usage)
2412 2385
2413 2386 def find_user_code(self, target, raw=True):
2414 2387 """Get a code string from history, file, or a string or macro.
2415 2388
2416 2389 This is mainly used by magic functions.
2417 2390
2418 2391 Parameters
2419 2392 ----------
2420 2393 target : str
2421 2394 A string specifying code to retrieve. This will be tried respectively
2422 2395 as: ranges of input history (see %history for syntax), a filename, or
2423 2396 an expression evaluating to a string or Macro in the user namespace.
2424 2397 raw : bool
2425 2398 If true (default), retrieve raw history. Has no effect on the other
2426 2399 retrieval mechanisms.
2427 2400
2428 2401 Returns
2429 2402 -------
2430 2403 A string of code.
2431 2404
2432 2405 ValueError is raised if nothing is found, and TypeError if it evaluates
2433 2406 to an object of another type. In each case, .args[0] is a printable
2434 2407 message.
2435 2408 """
2436 2409 code = self.extract_input_lines(target, raw=raw) # Grab history
2437 2410 if code:
2438 2411 return code
2439 2412 if os.path.isfile(target): # Read file
2440 2413 return open(target, "r").read()
2441 2414
2442 2415 try: # User namespace
2443 2416 codeobj = eval(target, self.user_ns)
2444 2417 except Exception:
2445 2418 raise ValueError(("'%s' was not found in history, as a file, nor in"
2446 2419 " the user namespace.") % target)
2447 2420 if isinstance(codeobj, basestring):
2448 2421 return codeobj
2449 2422 elif isinstance(codeobj, Macro):
2450 2423 return codeobj.value
2451 2424
2452 2425 raise TypeError("%s is neither a string nor a macro." % target,
2453 2426 codeobj)
2454 2427
2455 2428 #-------------------------------------------------------------------------
2456 2429 # Things related to IPython exiting
2457 2430 #-------------------------------------------------------------------------
2458 2431 def atexit_operations(self):
2459 2432 """This will be executed at the time of exit.
2460 2433
2461 2434 Cleanup operations and saving of persistent data that is done
2462 2435 unconditionally by IPython should be performed here.
2463 2436
2464 2437 For things that may depend on startup flags or platform specifics (such
2465 2438 as having readline or not), register a separate atexit function in the
2466 2439 code that has the appropriate information, rather than trying to
2467 2440 clutter
2468 2441 """
2469 2442 # Cleanup all tempfiles left around
2470 2443 for tfile in self.tempfiles:
2471 2444 try:
2472 2445 os.unlink(tfile)
2473 2446 except OSError:
2474 2447 pass
2475 2448
2476 2449 # Close the history session (this stores the end time and line count)
2477 2450 self.history_manager.end_session()
2478 2451
2479 2452 # Clear all user namespaces to release all references cleanly.
2480 2453 self.reset(new_session=False)
2481 2454
2482 2455 # Run user hooks
2483 2456 self.hooks.shutdown_hook()
2484 2457
2485 2458 def cleanup(self):
2486 2459 self.restore_sys_module_state()
2487 2460
2488 2461
2489 2462 class InteractiveShellABC(object):
2490 2463 """An abstract base class for InteractiveShell."""
2491 2464 __metaclass__ = abc.ABCMeta
2492 2465
2493 2466 InteractiveShellABC.register(InteractiveShell)
General Comments 0
You need to be logged in to leave comments. Login now