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