##// END OF EJS Templates
Created context manager for the things injected into __builtin__.
Brian Granger -
Show More
@@ -0,0 +1,104 b''
1 #!/usr/bin/env python
2 # encoding: utf-8
3 """
4 A context manager for managing things injected into :mod:`__builtin__`.
5
6 Authors:
7
8 * Brian Granger
9 """
10
11 #-----------------------------------------------------------------------------
12 # Copyright (C) 2008-2009 The IPython Development Team
13 #
14 # Distributed under the terms of the BSD License. The full license is in
15 # the file COPYING, distributed as part of this software.
16 #-----------------------------------------------------------------------------
17
18 #-----------------------------------------------------------------------------
19 # Imports
20 #-----------------------------------------------------------------------------
21
22 import __builtin__
23
24 from IPython.core.component import Component
25 from IPython.core.quitter import Quitter
26
27 #-----------------------------------------------------------------------------
28 # Classes and functions
29 #-----------------------------------------------------------------------------
30
31
32 class BuiltinUndefined(object): pass
33 BuiltinUndefined = BuiltinUndefined()
34
35
36 class BuiltinTrap(Component):
37
38 def __init__(self, parent, name=None, config=None):
39 super(BuiltinTrap, self).__init__(parent, name, config)
40 # Don't just grab parent!!!
41 from IPython.core.iplib import InteractiveShell
42 self.shell = InteractiveShell.get_instances(root=self.root)[0]
43 self._orig_builtins = {}
44
45 def __enter__(self):
46 self.set()
47 # I return self, so callers can use add_builtin in a with clause.
48 return self
49
50 def __exit__(self, type, value, traceback):
51 self.unset()
52 return True
53
54 def add_builtin(self, key, value):
55 """Add a builtin and save the original."""
56 orig = __builtin__.__dict__.get(key, BuiltinUndefined)
57 self._orig_builtins[key] = orig
58 __builtin__.__dict__[key] = value
59
60 def remove_builtin(self, key):
61 """Remove an added builtin and re-set the original."""
62 try:
63 orig = self._orig_builtins.pop(key)
64 except KeyError:
65 pass
66 else:
67 if orig is BuiltinUndefined:
68 del __builtin__.__dict__[key]
69 else:
70 __builtin__.__dict__[key] = orig
71
72 def set(self):
73 """Store ipython references in the __builtin__ namespace."""
74 self.add_builtin('exit', Quitter(self.shell, 'exit'))
75 self.add_builtin('quit', Quitter(self.shell, 'quit'))
76
77 # Recursive reload function
78 try:
79 from IPython.lib import deepreload
80 if self.shell.deep_reload:
81 self.add_builtin('reload', deepreload.reload)
82 else:
83 self.add_builtin('dreload', deepreload.reload)
84 del deepreload
85 except ImportError:
86 pass
87
88 # Keep in the builtins a flag for when IPython is active. We set it
89 # with setdefault so that multiple nested IPythons don't clobber one
90 # another. Each will increase its value by one upon being activated,
91 # which also gives us a way to determine the nesting level.
92 __builtin__.__dict__.setdefault('__IPYTHON__active',0)
93
94 def unset(self):
95 """Remove any builtins which might have been added by add_builtins, or
96 restore overwritten ones to their previous values."""
97 for key in self._orig_builtins.keys():
98 self.remove_builtin(key)
99 self._orig_builtins.clear()
100 self._builtins_added = False
101 try:
102 del __builtin__.__dict__['__IPYTHON__active']
103 except KeyError:
104 pass No newline at end of file
@@ -0,0 +1,38 b''
1 #!/usr/bin/env python
2 # encoding: utf-8
3 """
4 A simple class for quitting IPython.
5
6 Authors:
7
8 * Brian Granger
9 """
10
11 #-----------------------------------------------------------------------------
12 # Copyright (C) 2008-2009 The IPython Development Team
13 #
14 # Distributed under the terms of the BSD License. The full license is in
15 # the file COPYING, distributed as part of this software.
16 #-----------------------------------------------------------------------------
17
18 #-----------------------------------------------------------------------------
19 # Imports
20 #-----------------------------------------------------------------------------
21
22
23 class Quitter(object):
24 """Simple class to handle exit, similar to Python 2.5's.
25
26 It handles exiting in an ipython-safe manner, which the one in Python 2.5
27 doesn't do (obviously, since it doesn't know about ipython)."""
28
29 def __init__(self, shell, name):
30 self.shell = shell
31 self.name = name
32
33 def __repr__(self):
34 return 'Type %s() to exit.' % self.name
35 __str__ = __repr__
36
37 def __call__(self):
38 self.shell.exit() No newline at end of file
@@ -1,233 +1,242 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 # encoding: utf-8
2 # encoding: utf-8
3 """
3 """
4 A lightweight component system for IPython.
4 A lightweight component system for IPython.
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-2009 The IPython Development Team
13 # Copyright (C) 2008-2009 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 from weakref import WeakValueDictionary
25 from weakref import WeakValueDictionary
26
26
27 from IPython.utils.ipstruct import Struct
27 from IPython.utils.ipstruct import Struct
28 from IPython.utils.traitlets import (
28 from IPython.utils.traitlets import (
29 HasTraitlets, TraitletError, MetaHasTraitlets, Instance, This
29 HasTraitlets, TraitletError, MetaHasTraitlets, Instance, This
30 )
30 )
31
31
32
32
33 #-----------------------------------------------------------------------------
33 #-----------------------------------------------------------------------------
34 # Helper classes for Components
34 # Helper classes for Components
35 #-----------------------------------------------------------------------------
35 #-----------------------------------------------------------------------------
36
36
37
37
38 class ComponentError(Exception):
38 class ComponentError(Exception):
39 pass
39 pass
40
40
41 class MetaComponentTracker(type):
41 class MetaComponentTracker(type):
42 """A metaclass that tracks instances of Components and its subclasses."""
42 """A metaclass that tracks instances of Components and its subclasses."""
43
43
44 def __init__(cls, name, bases, d):
44 def __init__(cls, name, bases, d):
45 super(MetaComponentTracker, cls).__init__(name, bases, d)
45 super(MetaComponentTracker, cls).__init__(name, bases, d)
46 cls.__instance_refs = WeakValueDictionary()
46 cls.__instance_refs = WeakValueDictionary()
47 cls.__numcreated = 0
47 cls.__numcreated = 0
48
48
49 def __call__(cls, *args, **kw):
49 def __call__(cls, *args, **kw):
50 """Called when *class* is called (instantiated)!!!
50 """Called when *class* is called (instantiated)!!!
51
51
52 When a Component or subclass is instantiated, this is called and
52 When a Component or subclass is instantiated, this is called and
53 the instance is saved in a WeakValueDictionary for tracking.
53 the instance is saved in a WeakValueDictionary for tracking.
54 """
54 """
55
55 instance = cls.__new__(cls, *args, **kw)
56 instance = super(MetaComponentTracker, cls).__call__(*args, **kw)
56 # Do this before __init__ is called so get_instances works inside
57 # __init__ methods!
57 for c in cls.__mro__:
58 for c in cls.__mro__:
58 if issubclass(cls, c) and issubclass(c, Component):
59 if issubclass(cls, c) and issubclass(c, Component):
59 c.__numcreated += 1
60 c.__numcreated += 1
60 c.__instance_refs[c.__numcreated] = instance
61 c.__instance_refs[c.__numcreated] = instance
62 if isinstance(instance, cls):
63 cls.__init__(instance, *args, **kw)
64
61 return instance
65 return instance
62
66
63 def get_instances(cls, name=None, root=None):
67 def get_instances(cls, name=None, root=None, classname=None):
64 """Get all instances of cls and its subclasses.
68 """Get all instances of cls and its subclasses.
65
69
66 Parameters
70 Parameters
67 ----------
71 ----------
68 name : str
72 name : str
69 Limit to components with this name.
73 Limit to components with this name.
70 root : Component or subclass
74 root : Component or subclass
71 Limit to components having this root.
75 Limit to components having this root.
76 classname : str
77 The string name of a class to match exactly.
72 """
78 """
73 instances = cls.__instance_refs.values()
79 instances = cls.__instance_refs.values()
74 if name is not None:
80 if name is not None:
75 instances = [i for i in instances if i.name == name]
81 instances = [i for i in instances if i.name == name]
82 if classname is not None:
83 instances = [i for i in instances if i.__class__.__name__ == classname]
76 if root is not None:
84 if root is not None:
77 instances = [i for i in instances if i.root == root]
85 instances = [i for i in instances if i.root == root]
78 return instances
86 return instances
79
87
80 def get_instances_by_condition(cls, call, name=None, root=None):
88 def get_instances_by_condition(cls, call, name=None, root=None,
89 classname=None):
81 """Get all instances of cls, i such that call(i)==True.
90 """Get all instances of cls, i such that call(i)==True.
82
91
83 This also takes the ``name`` and ``root`` arguments of
92 This also takes the ``name`` and ``root`` and ``classname``
84 :meth:`get_instance`
93 arguments of :meth:`get_instance`
85 """
94 """
86 return [i for i in cls.get_instances(name, root) if call(i)]
95 return [i for i in cls.get_instances(name, root, classname) if call(i)]
87
96
88
97
89 class ComponentNameGenerator(object):
98 class ComponentNameGenerator(object):
90 """A Singleton to generate unique component names."""
99 """A Singleton to generate unique component names."""
91
100
92 def __init__(self, prefix):
101 def __init__(self, prefix):
93 self.prefix = prefix
102 self.prefix = prefix
94 self.i = 0
103 self.i = 0
95
104
96 def __call__(self):
105 def __call__(self):
97 count = self.i
106 count = self.i
98 self.i += 1
107 self.i += 1
99 return "%s%s" % (self.prefix, count)
108 return "%s%s" % (self.prefix, count)
100
109
101
110
102 ComponentNameGenerator = ComponentNameGenerator('ipython.component')
111 ComponentNameGenerator = ComponentNameGenerator('ipython.component')
103
112
104
113
105 class MetaComponent(MetaHasTraitlets, MetaComponentTracker):
114 class MetaComponent(MetaHasTraitlets, MetaComponentTracker):
106 pass
115 pass
107
116
108
117
109 #-----------------------------------------------------------------------------
118 #-----------------------------------------------------------------------------
110 # Component implementation
119 # Component implementation
111 #-----------------------------------------------------------------------------
120 #-----------------------------------------------------------------------------
112
121
113
122
114 class Component(HasTraitlets):
123 class Component(HasTraitlets):
115
124
116 __metaclass__ = MetaComponent
125 __metaclass__ = MetaComponent
117
126
118 # Traitlets are fun!
127 # Traitlets are fun!
119 config = Instance(Struct,(),{})
128 config = Instance(Struct,(),{})
120 parent = This()
129 parent = This()
121 root = This()
130 root = This()
122 created = None
131 created = None
123
132
124 def __init__(self, parent, name=None, config=None):
133 def __init__(self, parent, name=None, config=None):
125 """Create a component given a parent and possibly and name and config.
134 """Create a component given a parent and possibly and name and config.
126
135
127 Parameters
136 Parameters
128 ----------
137 ----------
129 parent : Component subclass
138 parent : Component subclass
130 The parent in the component graph. The parent is used
139 The parent in the component graph. The parent is used
131 to get the root of the component graph.
140 to get the root of the component graph.
132 name : str
141 name : str
133 The unique name of the component. If empty, then a unique
142 The unique name of the component. If empty, then a unique
134 one will be autogenerated.
143 one will be autogenerated.
135 config : Struct
144 config : Struct
136 If this is empty, self.config = parent.config, otherwise
145 If this is empty, self.config = parent.config, otherwise
137 self.config = config and root.config is ignored. This argument
146 self.config = config and root.config is ignored. This argument
138 should only be used to *override* the automatic inheritance of
147 should only be used to *override* the automatic inheritance of
139 parent.config. If a caller wants to modify parent.config
148 parent.config. If a caller wants to modify parent.config
140 (not override), the caller should make a copy and change
149 (not override), the caller should make a copy and change
141 attributes and then pass the copy to this argument.
150 attributes and then pass the copy to this argument.
142
151
143 Notes
152 Notes
144 -----
153 -----
145 Subclasses of Component must call the :meth:`__init__` method of
154 Subclasses of Component must call the :meth:`__init__` method of
146 :class:`Component` *before* doing anything else and using
155 :class:`Component` *before* doing anything else and using
147 :func:`super`::
156 :func:`super`::
148
157
149 class MyComponent(Component):
158 class MyComponent(Component):
150 def __init__(self, parent, name=None, config=None):
159 def __init__(self, parent, name=None, config=None):
151 super(MyComponent, self).__init__(parent, name, config)
160 super(MyComponent, self).__init__(parent, name, config)
152 # Then any other code you need to finish initialization.
161 # Then any other code you need to finish initialization.
153
162
154 This ensures that the :attr:`parent`, :attr:`name` and :attr:`config`
163 This ensures that the :attr:`parent`, :attr:`name` and :attr:`config`
155 attributes are handled properly.
164 attributes are handled properly.
156 """
165 """
157 super(Component, self).__init__()
166 super(Component, self).__init__()
158 self._children = []
167 self._children = []
159 if name is None:
168 if name is None:
160 self.name = ComponentNameGenerator()
169 self.name = ComponentNameGenerator()
161 else:
170 else:
162 self.name = name
171 self.name = name
163 self.root = self # This is the default, it is set when parent is set
172 self.root = self # This is the default, it is set when parent is set
164 self.parent = parent
173 self.parent = parent
165 if config is not None:
174 if config is not None:
166 self.config = deepcopy(config)
175 self.config = deepcopy(config)
167 else:
176 else:
168 if self.parent is not None:
177 if self.parent is not None:
169 self.config = deepcopy(self.parent.config)
178 self.config = deepcopy(self.parent.config)
170
179
171 self.created = datetime.datetime.now()
180 self.created = datetime.datetime.now()
172
181
173 #-------------------------------------------------------------------------
182 #-------------------------------------------------------------------------
174 # Static traitlet notifiations
183 # Static traitlet notifiations
175 #-------------------------------------------------------------------------
184 #-------------------------------------------------------------------------
176
185
177 def _parent_changed(self, name, old, new):
186 def _parent_changed(self, name, old, new):
178 if old is not None:
187 if old is not None:
179 old._remove_child(self)
188 old._remove_child(self)
180 if new is not None:
189 if new is not None:
181 new._add_child(self)
190 new._add_child(self)
182
191
183 if new is None:
192 if new is None:
184 self.root = self
193 self.root = self
185 else:
194 else:
186 self.root = new.root
195 self.root = new.root
187
196
188 def _root_changed(self, name, old, new):
197 def _root_changed(self, name, old, new):
189 if self.parent is None:
198 if self.parent is None:
190 if not (new is self):
199 if not (new is self):
191 raise ComponentError("Root not self, but parent is None.")
200 raise ComponentError("Root not self, but parent is None.")
192 else:
201 else:
193 if not self.parent.root is new:
202 if not self.parent.root is new:
194 raise ComponentError("Error in setting the root attribute: "
203 raise ComponentError("Error in setting the root attribute: "
195 "root != parent.root")
204 "root != parent.root")
196
205
197 def _config_changed(self, name, old, new):
206 def _config_changed(self, name, old, new):
198 """Update all the class traits having a config_key with the config.
207 """Update all the class traits having a config_key with the config.
199
208
200 For any class traitlet with a ``config_key`` metadata attribute, we
209 For any class traitlet with a ``config_key`` metadata attribute, we
201 update the traitlet with the value of the corresponding config entry.
210 update the traitlet with the value of the corresponding config entry.
202
211
203 In the future, we might want to do a pop here so stale config info
212 In the future, we might want to do a pop here so stale config info
204 is not passed onto children.
213 is not passed onto children.
205 """
214 """
206 # Get all traitlets with a config_key metadata entry
215 # Get all traitlets with a config_key metadata entry
207 traitlets = self.traitlets('config_key')
216 traitlets = self.traitlets('config_key')
208 for k, v in traitlets.items():
217 for k, v in traitlets.items():
209 try:
218 try:
210 config_value = new[v.get_metadata('config_key')]
219 config_value = new[v.get_metadata('config_key')]
211 except KeyError:
220 except KeyError:
212 pass
221 pass
213 else:
222 else:
214 setattr(self, k, config_value)
223 setattr(self, k, config_value)
215
224
216 @property
225 @property
217 def children(self):
226 def children(self):
218 """A list of all my child components."""
227 """A list of all my child components."""
219 return self._children
228 return self._children
220
229
221 def _remove_child(self, child):
230 def _remove_child(self, child):
222 """A private method for removing children components."""
231 """A private method for removing children components."""
223 if child in self._children:
232 if child in self._children:
224 index = self._children.index(child)
233 index = self._children.index(child)
225 del self._children[index]
234 del self._children[index]
226
235
227 def _add_child(self, child):
236 def _add_child(self, child):
228 """A private method for adding children components."""
237 """A private method for adding children components."""
229 if child not in self._children:
238 if child not in self._children:
230 self._children.append(child)
239 self._children.append(child)
231
240
232 def __repr__(self):
241 def __repr__(self):
233 return "<Component('%s')>" % self.name
242 return "<Component('%s')>" % self.name
@@ -1,215 +1,282 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 # encoding: utf-8
2 # encoding: utf-8
3 """
3 """
4 An embedded IPython shell.
4 An embedded IPython shell.
5
5
6 Authors:
6 Authors:
7
7
8 * Brian Granger
8 * Brian Granger
9 * Fernando Perez
9 * Fernando Perez
10
10
11 Notes
11 Notes
12 -----
12 -----
13 """
13 """
14
14
15 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
16 # Copyright (C) 2008-2009 The IPython Development Team
16 # Copyright (C) 2008-2009 The IPython Development Team
17 #
17 #
18 # Distributed under the terms of the BSD License. The full license is in
18 # Distributed under the terms of the BSD License. The full license is in
19 # the file COPYING, distributed as part of this software.
19 # the file COPYING, distributed as part of this software.
20 #-----------------------------------------------------------------------------
20 #-----------------------------------------------------------------------------
21
21
22 #-----------------------------------------------------------------------------
22 #-----------------------------------------------------------------------------
23 # Imports
23 # Imports
24 #-----------------------------------------------------------------------------
24 #-----------------------------------------------------------------------------
25
25
26 from __future__ import with_statement
27
26 import sys
28 import sys
27
29
28 from IPython.core import ultratb
30 from IPython.core import ultratb
29 from IPython.core.iplib import InteractiveShell
31 from IPython.core.iplib import InteractiveShell
30
32
31 from IPython.utils.traitlets import Bool, Str, CBool
33 from IPython.utils.traitlets import Bool, Str, CBool
32 from IPython.utils.genutils import ask_yes_no
34 from IPython.utils.genutils import ask_yes_no
33
35
34 #-----------------------------------------------------------------------------
36 #-----------------------------------------------------------------------------
35 # Classes and functions
37 # Classes and functions
36 #-----------------------------------------------------------------------------
38 #-----------------------------------------------------------------------------
37
39
38 # This is an additional magic that is exposed in embedded shells.
40 # This is an additional magic that is exposed in embedded shells.
39 def kill_embedded(self,parameter_s=''):
41 def kill_embedded(self,parameter_s=''):
40 """%kill_embedded : deactivate for good the current embedded IPython.
42 """%kill_embedded : deactivate for good the current embedded IPython.
41
43
42 This function (after asking for confirmation) sets an internal flag so that
44 This function (after asking for confirmation) sets an internal flag so that
43 an embedded IPython will never activate again. This is useful to
45 an embedded IPython will never activate again. This is useful to
44 permanently disable a shell that is being called inside a loop: once you've
46 permanently disable a shell that is being called inside a loop: once you've
45 figured out what you needed from it, you may then kill it and the program
47 figured out what you needed from it, you may then kill it and the program
46 will then continue to run without the interactive shell interfering again.
48 will then continue to run without the interactive shell interfering again.
47 """
49 """
48
50
49 kill = ask_yes_no("Are you sure you want to kill this embedded instance "
51 kill = ask_yes_no("Are you sure you want to kill this embedded instance "
50 "(y/n)? [y/N] ",'n')
52 "(y/n)? [y/N] ",'n')
51 if kill:
53 if kill:
52 self.embedded_active = False
54 self.embedded_active = False
53 print "This embedded IPython will not reactivate anymore once you exit."
55 print "This embedded IPython will not reactivate anymore once you exit."
54
56
55
57
56 class InteractiveShellEmbed(InteractiveShell):
58 class InteractiveShellEmbed(InteractiveShell):
57
59
58 dummy_mode = Bool(False)
60 dummy_mode = Bool(False)
59 exit_msg = Str('')
61 exit_msg = Str('')
60 embedded = CBool(True)
62 embedded = CBool(True)
61 embedded_active = CBool(True)
63 embedded_active = CBool(True)
62
64
63 def __init__(self, parent=None, config=None, ipythondir=None, usage=None,
65 def __init__(self, parent=None, config=None, ipythondir=None, usage=None,
64 user_ns=None, user_global_ns=None,
66 user_ns=None, user_global_ns=None,
65 banner1=None, banner2=None,
67 banner1=None, banner2=None,
66 custom_exceptions=((),None), exit_msg=None):
68 custom_exceptions=((),None), exit_msg=''):
67
69
68 # First we need to save the state of sys.displayhook and
70 # First we need to save the state of sys.displayhook and
69 # sys.ipcompleter so we can restore it when we are done.
71 # sys.ipcompleter so we can restore it when we are done.
70 self.save_sys_displayhook()
72 self.save_sys_displayhook()
71 self.save_sys_ipcompleter()
73 self.save_sys_ipcompleter()
72
74
73 super(InteractiveShellEmbed,self).__init__(
75 super(InteractiveShellEmbed,self).__init__(
74 parent=parent, config=config, ipythondir=ipythondir, usage=usage,
76 parent=parent, config=config, ipythondir=ipythondir, usage=usage,
75 user_ns=user_ns, user_global_ns=user_global_ns,
77 user_ns=user_ns, user_global_ns=user_global_ns,
76 banner1=banner1, banner2=banner2,
78 banner1=banner1, banner2=banner2,
77 custom_exceptions=custom_exceptions)
79 custom_exceptions=custom_exceptions)
78
80
79 self.save_sys_displayhook_embed()
81 self.save_sys_displayhook_embed()
80 self.exit_msg = exit_msg
82 self.exit_msg = exit_msg
81 self.define_magic("kill_embedded", kill_embedded)
83 self.define_magic("kill_embedded", kill_embedded)
82
84
83 # don't use the ipython crash handler so that user exceptions aren't
85 # don't use the ipython crash handler so that user exceptions aren't
84 # trapped
86 # trapped
85 sys.excepthook = ultratb.FormattedTB(color_scheme=self.colors,
87 sys.excepthook = ultratb.FormattedTB(color_scheme=self.colors,
86 mode=self.xmode,
88 mode=self.xmode,
87 call_pdb=self.pdb)
89 call_pdb=self.pdb)
88
90
89 self.restore_sys_displayhook()
91 self.restore_sys_displayhook()
90 self.restore_sys_ipcompleter()
92 self.restore_sys_ipcompleter()
91
93
92 def init_sys_modules(self):
94 def init_sys_modules(self):
93 pass
95 pass
94
96
95 def save_sys_displayhook(self):
97 def save_sys_displayhook(self):
96 # sys.displayhook is a global, we need to save the user's original
98 # sys.displayhook is a global, we need to save the user's original
97 # Don't rely on __displayhook__, as the user may have changed that.
99 # Don't rely on __displayhook__, as the user may have changed that.
98 self.sys_displayhook_orig = sys.displayhook
100 self.sys_displayhook_orig = sys.displayhook
99
101
100 def save_sys_ipcompleter(self):
102 def save_sys_ipcompleter(self):
101 """Save readline completer status."""
103 """Save readline completer status."""
102 try:
104 try:
103 #print 'Save completer',sys.ipcompleter # dbg
105 #print 'Save completer',sys.ipcompleter # dbg
104 self.sys_ipcompleter_orig = sys.ipcompleter
106 self.sys_ipcompleter_orig = sys.ipcompleter
105 except:
107 except:
106 pass # not nested with IPython
108 pass # not nested with IPython
107
109
108 def restore_sys_displayhook(self):
110 def restore_sys_displayhook(self):
109 sys.displayhook = self.sys_displayhook_orig
111 sys.displayhook = self.sys_displayhook_orig
110
112
111 def restore_sys_ipcompleter(self):
113 def restore_sys_ipcompleter(self):
112 """Restores the readline completer which was in place.
114 """Restores the readline completer which was in place.
113
115
114 This allows embedded IPython within IPython not to disrupt the
116 This allows embedded IPython within IPython not to disrupt the
115 parent's completion.
117 parent's completion.
116 """
118 """
117 try:
119 try:
118 self.readline.set_completer(self.sys_ipcompleter_orig)
120 self.readline.set_completer(self.sys_ipcompleter_orig)
119 sys.ipcompleter = self.sys_ipcompleter_orig
121 sys.ipcompleter = self.sys_ipcompleter_orig
120 except:
122 except:
121 pass
123 pass
122
124
123 def save_sys_displayhook_embed(self):
125 def save_sys_displayhook_embed(self):
124 self.sys_displayhook_embed = sys.displayhook
126 self.sys_displayhook_embed = sys.displayhook
125
127
126 def restore_sys_displayhook_embed(self):
128 def restore_sys_displayhook_embed(self):
127 sys.displayhook = self.sys_displayhook_embed
129 sys.displayhook = self.sys_displayhook_embed
128
130
129 def __call__(self, header='', local_ns=None, global_ns=None, dummy=None,
131 def __call__(self, header='', local_ns=None, global_ns=None, dummy=None,
130 stack_depth=1):
132 stack_depth=1):
131 """Activate the interactive interpreter.
133 """Activate the interactive interpreter.
132
134
133 __call__(self,header='',local_ns=None,global_ns,dummy=None) -> Start
135 __call__(self,header='',local_ns=None,global_ns,dummy=None) -> Start
134 the interpreter shell with the given local and global namespaces, and
136 the interpreter shell with the given local and global namespaces, and
135 optionally print a header string at startup.
137 optionally print a header string at startup.
136
138
137 The shell can be globally activated/deactivated using the
139 The shell can be globally activated/deactivated using the
138 set/get_dummy_mode methods. This allows you to turn off a shell used
140 set/get_dummy_mode methods. This allows you to turn off a shell used
139 for debugging globally.
141 for debugging globally.
140
142
141 However, *each* time you call the shell you can override the current
143 However, *each* time you call the shell you can override the current
142 state of dummy_mode with the optional keyword parameter 'dummy'. For
144 state of dummy_mode with the optional keyword parameter 'dummy'. For
143 example, if you set dummy mode on with IPShell.set_dummy_mode(1), you
145 example, if you set dummy mode on with IPShell.set_dummy_mode(1), you
144 can still have a specific call work by making it as IPShell(dummy=0).
146 can still have a specific call work by making it as IPShell(dummy=0).
145
147
146 The optional keyword parameter dummy controls whether the call
148 The optional keyword parameter dummy controls whether the call
147 actually does anything.
149 actually does anything.
148 """
150 """
149
151
150 # If the user has turned it off, go away
152 # If the user has turned it off, go away
151 if not self.embedded_active:
153 if not self.embedded_active:
152 return
154 return
153
155
154 # Normal exits from interactive mode set this flag, so the shell can't
156 # Normal exits from interactive mode set this flag, so the shell can't
155 # re-enter (it checks this variable at the start of interactive mode).
157 # re-enter (it checks this variable at the start of interactive mode).
156 self.exit_now = False
158 self.exit_now = False
157
159
158 # Allow the dummy parameter to override the global __dummy_mode
160 # Allow the dummy parameter to override the global __dummy_mode
159 if dummy or (dummy != 0 and self.dummy_mode):
161 if dummy or (dummy != 0 and self.dummy_mode):
160 return
162 return
161
163
162 self.restore_sys_displayhook_embed()
164 self.restore_sys_displayhook_embed()
163
165
164 if self.has_readline:
166 if self.has_readline:
165 self.set_completer()
167 self.set_completer()
166
168
167 if self.banner and header:
169 if self.banner and header:
168 format = '%s\n%s\n'
170 format = '%s\n%s\n'
169 else:
171 else:
170 format = '%s%s\n'
172 format = '%s%s\n'
171 banner = format % (self.banner,header)
173 banner = format % (self.banner,header)
172
174
173 # Call the embedding code with a stack depth of 1 so it can skip over
175 # Call the embedding code with a stack depth of 1 so it can skip over
174 # our call and get the original caller's namespaces.
176 # our call and get the original caller's namespaces.
175 self.embed_mainloop(banner, local_ns, global_ns,
177 self.mainloop(banner, local_ns, global_ns,
176 stack_depth=stack_depth)
178 stack_depth=stack_depth)
177
179
178 if self.exit_msg is not None:
180 if self.exit_msg is not None:
179 print self.exit_msg
181 print self.exit_msg
180
182
181 # Restore global systems (display, completion)
183 # Restore global systems (display, completion)
182 self.restore_sys_displayhook()
184 self.restore_sys_displayhook()
183 self.restore_sys_ipcompleter()
185 self.restore_sys_ipcompleter()
184
186
187 def mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0):
188 """Embeds IPython into a running python program.
189
190 Input:
191
192 - header: An optional header message can be specified.
193
194 - local_ns, global_ns: working namespaces. If given as None, the
195 IPython-initialized one is updated with __main__.__dict__, so that
196 program variables become visible but user-specific configuration
197 remains possible.
198
199 - stack_depth: specifies how many levels in the stack to go to
200 looking for namespaces (when local_ns and global_ns are None). This
201 allows an intermediate caller to make sure that this function gets
202 the namespace from the intended level in the stack. By default (0)
203 it will get its locals and globals from the immediate caller.
204
205 Warning: it's possible to use this in a program which is being run by
206 IPython itself (via %run), but some funny things will happen (a few
207 globals get overwritten). In the future this will be cleaned up, as
208 there is no fundamental reason why it can't work perfectly."""
209
210 # Get locals and globals from caller
211 if local_ns is None or global_ns is None:
212 call_frame = sys._getframe(stack_depth).f_back
213
214 if local_ns is None:
215 local_ns = call_frame.f_locals
216 if global_ns is None:
217 global_ns = call_frame.f_globals
218
219 # Update namespaces and fire up interpreter
220
221 # The global one is easy, we can just throw it in
222 self.user_global_ns = global_ns
223
224 # but the user/local one is tricky: ipython needs it to store internal
225 # data, but we also need the locals. We'll copy locals in the user
226 # one, but will track what got copied so we can delete them at exit.
227 # This is so that a later embedded call doesn't see locals from a
228 # previous call (which most likely existed in a separate scope).
229 local_varnames = local_ns.keys()
230 self.user_ns.update(local_ns)
231 #self.user_ns['local_ns'] = local_ns # dbg
232
233 # Patch for global embedding to make sure that things don't overwrite
234 # user globals accidentally. Thanks to Richard <rxe@renre-europe.com>
235 # FIXME. Test this a bit more carefully (the if.. is new)
236 if local_ns is None and global_ns is None:
237 self.user_global_ns.update(__main__.__dict__)
238
239 # make sure the tab-completer has the correct frame information, so it
240 # actually completes using the frame's locals/globals
241 self.set_completer_frame()
242
243 with self.builtin_trap:
244 self.interact(header)
245
246 # now, purge out the user namespace from anything we might have added
247 # from the caller's local namespace
248 delvar = self.user_ns.pop
249 for var in local_varnames:
250 delvar(var,None)
251
185
252
186 _embedded_shell = None
253 _embedded_shell = None
187
254
188
255
189 def embed(header='', config=None, usage=None, banner1=None, banner2=None,
256 def embed(header='', config=None, usage=None, banner1=None, banner2=None,
190 exit_msg=''):
257 exit_msg=''):
191 """Call this to embed IPython at the current point in your program.
258 """Call this to embed IPython at the current point in your program.
192
259
193 The first invocation of this will create an :class:`InteractiveShellEmbed`
260 The first invocation of this will create an :class:`InteractiveShellEmbed`
194 instance and then call it. Consecutive calls just call the already
261 instance and then call it. Consecutive calls just call the already
195 created instance.
262 created instance.
196
263
197 Here is a simple example::
264 Here is a simple example::
198
265
199 from IPython import embed
266 from IPython import embed
200 a = 10
267 a = 10
201 b = 20
268 b = 20
202 embed('First time')
269 embed('First time')
203 c = 30
270 c = 30
204 d = 40
271 d = 40
205 embed
272 embed
206
273
207 Full customization can be done by passing a :class:`Struct` in as the
274 Full customization can be done by passing a :class:`Struct` in as the
208 config argument.
275 config argument.
209 """
276 """
210 global _embedded_shell
277 global _embedded_shell
211 if _embedded_shell is None:
278 if _embedded_shell is None:
212 _embedded_shell = InteractiveShellEmbed(config=config,
279 _embedded_shell = InteractiveShellEmbed(config=config,
213 usage=usage, banner1=banner1, banner2=banner2, exit_msg=exit_msg)
280 usage=usage, banner1=banner1, banner2=banner2, exit_msg=exit_msg)
214 _embedded_shell(header=header, stack_depth=2)
281 _embedded_shell(header=header, stack_depth=2)
215
282
@@ -1,3100 +1,2962 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """
2 """
3 Main IPython Component
3 Main IPython Component
4 """
4 """
5
5
6 #-----------------------------------------------------------------------------
6 #-----------------------------------------------------------------------------
7 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
7 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
8 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
8 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
9 # Copyright (C) 2008-2009 The IPython Development Team
9 # Copyright (C) 2008-2009 The IPython Development Team
10 #
10 #
11 # Distributed under the terms of the BSD License. The full license is in
11 # Distributed under the terms of the BSD License. The full license is in
12 # the file COPYING, distributed as part of this software.
12 # the file COPYING, distributed as part of this software.
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14
14
15 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
16 # Imports
16 # Imports
17 #-----------------------------------------------------------------------------
17 #-----------------------------------------------------------------------------
18
18
19 from __future__ import with_statement
20
19 import __main__
21 import __main__
20 import __builtin__
22 import __builtin__
21 import StringIO
23 import StringIO
22 import bdb
24 import bdb
23 import codeop
25 import codeop
24 import exceptions
26 import exceptions
25 import glob
27 import glob
26 import keyword
28 import keyword
27 import new
29 import new
28 import os
30 import os
29 import re
31 import re
30 import shutil
32 import shutil
31 import string
33 import string
32 import sys
34 import sys
33 import tempfile
35 import tempfile
34
36
35 from IPython.core import ultratb
37 from IPython.core import ultratb
36 from IPython.core import debugger, oinspect
38 from IPython.core import debugger, oinspect
37 from IPython.core import shadowns
39 from IPython.core import shadowns
38 from IPython.core import history as ipcorehist
40 from IPython.core import history as ipcorehist
39 from IPython.core import prefilter
41 from IPython.core import prefilter
40 from IPython.core.autocall import IPyAutocall
42 from IPython.core.autocall import IPyAutocall
43 from IPython.core.builtin_trap import BuiltinTrap
41 from IPython.core.fakemodule import FakeModule, init_fakemod_dict
44 from IPython.core.fakemodule import FakeModule, init_fakemod_dict
42 from IPython.core.logger import Logger
45 from IPython.core.logger import Logger
43 from IPython.core.magic import Magic
46 from IPython.core.magic import Magic
44 from IPython.core.prompts import CachedOutput
47 from IPython.core.prompts import CachedOutput
45 from IPython.core.page import page
48 from IPython.core.page import page
46 from IPython.core.component import Component
49 from IPython.core.component import Component
47 from IPython.core.oldusersetup import user_setup
50 from IPython.core.oldusersetup import user_setup
48 from IPython.core.usage import interactive_usage, default_banner
51 from IPython.core.usage import interactive_usage, default_banner
49 from IPython.core.error import TryNext, UsageError
52 from IPython.core.error import TryNext, UsageError
50
53
51 from IPython.extensions import pickleshare
54 from IPython.extensions import pickleshare
52 from IPython.external.Itpl import ItplNS
55 from IPython.external.Itpl import ItplNS
53 from IPython.lib.backgroundjobs import BackgroundJobManager
56 from IPython.lib.backgroundjobs import BackgroundJobManager
54 from IPython.utils.ipstruct import Struct
57 from IPython.utils.ipstruct import Struct
55 from IPython.utils import PyColorize
58 from IPython.utils import PyColorize
56 from IPython.utils.genutils import *
59 from IPython.utils.genutils import *
57 from IPython.utils.strdispatch import StrDispatch
60 from IPython.utils.strdispatch import StrDispatch
58 from IPython.utils.platutils import toggle_set_term_title, set_term_title
61 from IPython.utils.platutils import toggle_set_term_title, set_term_title
59
62
60 from IPython.utils.traitlets import (
63 from IPython.utils.traitlets import (
61 Int, Float, Str, CBool, CaselessStrEnum, Enum, List, Unicode
64 Int, Float, Str, CBool, CaselessStrEnum, Enum, List, Unicode
62 )
65 )
63
66
64 #-----------------------------------------------------------------------------
67 #-----------------------------------------------------------------------------
65 # Globals
68 # Globals
66 #-----------------------------------------------------------------------------
69 #-----------------------------------------------------------------------------
67
70
68
71
69 # store the builtin raw_input globally, and use this always, in case user code
72 # store the builtin raw_input globally, and use this always, in case user code
70 # overwrites it (like wx.py.PyShell does)
73 # overwrites it (like wx.py.PyShell does)
71 raw_input_original = raw_input
74 raw_input_original = raw_input
72
75
73 # compiled regexps for autoindent management
76 # compiled regexps for autoindent management
74 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
77 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
75
78
76
79
77 #-----------------------------------------------------------------------------
80 #-----------------------------------------------------------------------------
78 # Utilities
81 # Utilities
79 #-----------------------------------------------------------------------------
82 #-----------------------------------------------------------------------------
80
83
81
84
82 ini_spaces_re = re.compile(r'^(\s+)')
85 ini_spaces_re = re.compile(r'^(\s+)')
83
86
84
87
85 def num_ini_spaces(strng):
88 def num_ini_spaces(strng):
86 """Return the number of initial spaces in a string"""
89 """Return the number of initial spaces in a string"""
87
90
88 ini_spaces = ini_spaces_re.match(strng)
91 ini_spaces = ini_spaces_re.match(strng)
89 if ini_spaces:
92 if ini_spaces:
90 return ini_spaces.end()
93 return ini_spaces.end()
91 else:
94 else:
92 return 0
95 return 0
93
96
94
97
95 def softspace(file, newvalue):
98 def softspace(file, newvalue):
96 """Copied from code.py, to remove the dependency"""
99 """Copied from code.py, to remove the dependency"""
97
100
98 oldvalue = 0
101 oldvalue = 0
99 try:
102 try:
100 oldvalue = file.softspace
103 oldvalue = file.softspace
101 except AttributeError:
104 except AttributeError:
102 pass
105 pass
103 try:
106 try:
104 file.softspace = newvalue
107 file.softspace = newvalue
105 except (AttributeError, TypeError):
108 except (AttributeError, TypeError):
106 # "attribute-less object" or "read-only attributes"
109 # "attribute-less object" or "read-only attributes"
107 pass
110 pass
108 return oldvalue
111 return oldvalue
109
112
110
113
111 class SpaceInInput(exceptions.Exception): pass
114 class SpaceInInput(exceptions.Exception): pass
112
115
113 class Bunch: pass
116 class Bunch: pass
114
117
115 class BuiltinUndefined: pass
116 BuiltinUndefined = BuiltinUndefined()
117
118
119 class Quitter(object):
120 """Simple class to handle exit, similar to Python 2.5's.
121
122 It handles exiting in an ipython-safe manner, which the one in Python 2.5
123 doesn't do (obviously, since it doesn't know about ipython)."""
124
125 def __init__(self, shell, name):
126 self.shell = shell
127 self.name = name
128
129 def __repr__(self):
130 return 'Type %s() to exit.' % self.name
131 __str__ = __repr__
132
133 def __call__(self):
134 self.shell.exit()
135
136
137 class InputList(list):
118 class InputList(list):
138 """Class to store user input.
119 """Class to store user input.
139
120
140 It's basically a list, but slices return a string instead of a list, thus
121 It's basically a list, but slices return a string instead of a list, thus
141 allowing things like (assuming 'In' is an instance):
122 allowing things like (assuming 'In' is an instance):
142
123
143 exec In[4:7]
124 exec In[4:7]
144
125
145 or
126 or
146
127
147 exec In[5:9] + In[14] + In[21:25]"""
128 exec In[5:9] + In[14] + In[21:25]"""
148
129
149 def __getslice__(self,i,j):
130 def __getslice__(self,i,j):
150 return ''.join(list.__getslice__(self,i,j))
131 return ''.join(list.__getslice__(self,i,j))
151
132
152
133
153 class SyntaxTB(ultratb.ListTB):
134 class SyntaxTB(ultratb.ListTB):
154 """Extension which holds some state: the last exception value"""
135 """Extension which holds some state: the last exception value"""
155
136
156 def __init__(self,color_scheme = 'NoColor'):
137 def __init__(self,color_scheme = 'NoColor'):
157 ultratb.ListTB.__init__(self,color_scheme)
138 ultratb.ListTB.__init__(self,color_scheme)
158 self.last_syntax_error = None
139 self.last_syntax_error = None
159
140
160 def __call__(self, etype, value, elist):
141 def __call__(self, etype, value, elist):
161 self.last_syntax_error = value
142 self.last_syntax_error = value
162 ultratb.ListTB.__call__(self,etype,value,elist)
143 ultratb.ListTB.__call__(self,etype,value,elist)
163
144
164 def clear_err_state(self):
145 def clear_err_state(self):
165 """Return the current error state and clear it"""
146 """Return the current error state and clear it"""
166 e = self.last_syntax_error
147 e = self.last_syntax_error
167 self.last_syntax_error = None
148 self.last_syntax_error = None
168 return e
149 return e
169
150
170
151
171 def get_default_editor():
152 def get_default_editor():
172 try:
153 try:
173 ed = os.environ['EDITOR']
154 ed = os.environ['EDITOR']
174 except KeyError:
155 except KeyError:
175 if os.name == 'posix':
156 if os.name == 'posix':
176 ed = 'vi' # the only one guaranteed to be there!
157 ed = 'vi' # the only one guaranteed to be there!
177 else:
158 else:
178 ed = 'notepad' # same in Windows!
159 ed = 'notepad' # same in Windows!
179 return ed
160 return ed
180
161
181
162
182 class SeparateStr(Str):
163 class SeparateStr(Str):
183 """A Str subclass to validate separate_in, separate_out, etc.
164 """A Str subclass to validate separate_in, separate_out, etc.
184
165
185 This is a Str based traitlet that converts '0'->'' and '\\n'->'\n'.
166 This is a Str based traitlet that converts '0'->'' and '\\n'->'\n'.
186 """
167 """
187
168
188 def validate(self, obj, value):
169 def validate(self, obj, value):
189 if value == '0': value = ''
170 if value == '0': value = ''
190 value = value.replace('\\n','\n')
171 value = value.replace('\\n','\n')
191 return super(SeparateStr, self).validate(obj, value)
172 return super(SeparateStr, self).validate(obj, value)
192
173
193
174
194 #-----------------------------------------------------------------------------
175 #-----------------------------------------------------------------------------
195 # Main IPython class
176 # Main IPython class
196 #-----------------------------------------------------------------------------
177 #-----------------------------------------------------------------------------
197
178
198
179
199 class InteractiveShell(Component, Magic):
180 class InteractiveShell(Component, Magic):
200 """An enhanced, interactive shell for Python."""
181 """An enhanced, interactive shell for Python."""
201
182
202 autocall = Enum((0,1,2), config_key='AUTOCALL')
183 autocall = Enum((0,1,2), config_key='AUTOCALL')
203 autoedit_syntax = CBool(False, config_key='AUTOEDIT_SYNTAX')
184 autoedit_syntax = CBool(False, config_key='AUTOEDIT_SYNTAX')
204 autoindent = CBool(True, config_key='AUTOINDENT')
185 autoindent = CBool(True, config_key='AUTOINDENT')
205 automagic = CBool(True, config_key='AUTOMAGIC')
186 automagic = CBool(True, config_key='AUTOMAGIC')
206 display_banner = CBool(True, config_key='DISPLAY_BANNER')
187 display_banner = CBool(True, config_key='DISPLAY_BANNER')
207 banner = Str('')
188 banner = Str('')
208 banner1 = Str(default_banner, config_key='BANNER1')
189 banner1 = Str(default_banner, config_key='BANNER1')
209 banner2 = Str('', config_key='BANNER2')
190 banner2 = Str('', config_key='BANNER2')
210 c = Str('', config_key='C')
191 c = Str('', config_key='C')
211 cache_size = Int(1000, config_key='CACHE_SIZE')
192 cache_size = Int(1000, config_key='CACHE_SIZE')
212 classic = CBool(False, config_key='CLASSIC')
193 classic = CBool(False, config_key='CLASSIC')
213 color_info = CBool(True, config_key='COLOR_INFO')
194 color_info = CBool(True, config_key='COLOR_INFO')
214 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
195 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
215 default_value='LightBG', config_key='COLORS')
196 default_value='LightBG', config_key='COLORS')
216 confirm_exit = CBool(True, config_key='CONFIRM_EXIT')
197 confirm_exit = CBool(True, config_key='CONFIRM_EXIT')
217 debug = CBool(False, config_key='DEBUG')
198 debug = CBool(False, config_key='DEBUG')
218 deep_reload = CBool(False, config_key='DEEP_RELOAD')
199 deep_reload = CBool(False, config_key='DEEP_RELOAD')
219 embedded = CBool(False)
200 embedded = CBool(False)
220 embedded_active = CBool(False)
201 embedded_active = CBool(False)
221 editor = Str(get_default_editor(), config_key='EDITOR')
202 editor = Str(get_default_editor(), config_key='EDITOR')
222 filename = Str("<ipython console>")
203 filename = Str("<ipython console>")
223 interactive = CBool(False, config_key='INTERACTIVE')
204 interactive = CBool(False, config_key='INTERACTIVE')
224 ipythondir= Unicode('', config_key='IPYTHONDIR') # Set to os.getcwd() in __init__
205 ipythondir= Unicode('', config_key='IPYTHONDIR') # Set to os.getcwd() in __init__
225 logstart = CBool(False, config_key='LOGSTART')
206 logstart = CBool(False, config_key='LOGSTART')
226 logfile = Str('', config_key='LOGFILE')
207 logfile = Str('', config_key='LOGFILE')
227 logplay = Str('', config_key='LOGPLAY')
208 logplay = Str('', config_key='LOGPLAY')
228 multi_line_specials = CBool(True, config_key='MULTI_LINE_SPECIALS')
209 multi_line_specials = CBool(True, config_key='MULTI_LINE_SPECIALS')
229 object_info_string_level = Enum((0,1,2), default_value=0,
210 object_info_string_level = Enum((0,1,2), default_value=0,
230 config_keys='OBJECT_INFO_STRING_LEVEL')
211 config_keys='OBJECT_INFO_STRING_LEVEL')
231 pager = Str('less', config_key='PAGER')
212 pager = Str('less', config_key='PAGER')
232 pdb = CBool(False, config_key='PDB')
213 pdb = CBool(False, config_key='PDB')
233 pprint = CBool(True, config_key='PPRINT')
214 pprint = CBool(True, config_key='PPRINT')
234 profile = Str('', config_key='PROFILE')
215 profile = Str('', config_key='PROFILE')
235 prompt_in1 = Str('In [\\#]: ', config_key='PROMPT_IN1')
216 prompt_in1 = Str('In [\\#]: ', config_key='PROMPT_IN1')
236 prompt_in2 = Str(' .\\D.: ', config_key='PROMPT_IN2')
217 prompt_in2 = Str(' .\\D.: ', config_key='PROMPT_IN2')
237 prompt_out = Str('Out[\\#]: ', config_key='PROMPT_OUT1')
218 prompt_out = Str('Out[\\#]: ', config_key='PROMPT_OUT1')
238 prompts_pad_left = CBool(True, config_key='PROMPTS_PAD_LEFT')
219 prompts_pad_left = CBool(True, config_key='PROMPTS_PAD_LEFT')
239 quiet = CBool(False, config_key='QUIET')
220 quiet = CBool(False, config_key='QUIET')
240
221
241 readline_use = CBool(True, config_key='READLINE_USE')
222 readline_use = CBool(True, config_key='READLINE_USE')
242 readline_merge_completions = CBool(True,
223 readline_merge_completions = CBool(True,
243 config_key='READLINE_MERGE_COMPLETIONS')
224 config_key='READLINE_MERGE_COMPLETIONS')
244 readline_omit__names = Enum((0,1,2), default_value=0,
225 readline_omit__names = Enum((0,1,2), default_value=0,
245 config_key='READLINE_OMIT_NAMES')
226 config_key='READLINE_OMIT_NAMES')
246 readline_remove_delims = Str('-/~', config_key='READLINE_REMOVE_DELIMS')
227 readline_remove_delims = Str('-/~', config_key='READLINE_REMOVE_DELIMS')
247 readline_parse_and_bind = List([
228 readline_parse_and_bind = List([
248 'tab: complete',
229 'tab: complete',
249 '"\C-l": possible-completions',
230 '"\C-l": possible-completions',
250 'set show-all-if-ambiguous on',
231 'set show-all-if-ambiguous on',
251 '"\C-o": tab-insert',
232 '"\C-o": tab-insert',
252 '"\M-i": " "',
233 '"\M-i": " "',
253 '"\M-o": "\d\d\d\d"',
234 '"\M-o": "\d\d\d\d"',
254 '"\M-I": "\d\d\d\d"',
235 '"\M-I": "\d\d\d\d"',
255 '"\C-r": reverse-search-history',
236 '"\C-r": reverse-search-history',
256 '"\C-s": forward-search-history',
237 '"\C-s": forward-search-history',
257 '"\C-p": history-search-backward',
238 '"\C-p": history-search-backward',
258 '"\C-n": history-search-forward',
239 '"\C-n": history-search-forward',
259 '"\e[A": history-search-backward',
240 '"\e[A": history-search-backward',
260 '"\e[B": history-search-forward',
241 '"\e[B": history-search-forward',
261 '"\C-k": kill-line',
242 '"\C-k": kill-line',
262 '"\C-u": unix-line-discard',
243 '"\C-u": unix-line-discard',
263 ], allow_none=False, config_key='READLINE_PARSE_AND_BIND'
244 ], allow_none=False, config_key='READLINE_PARSE_AND_BIND'
264 )
245 )
265
246
266 screen_length = Int(0, config_key='SCREEN_LENGTH')
247 screen_length = Int(0, config_key='SCREEN_LENGTH')
267
248
268 # Use custom TraitletTypes that convert '0'->'' and '\\n'->'\n'
249 # Use custom TraitletTypes that convert '0'->'' and '\\n'->'\n'
269 separate_in = SeparateStr('\n', config_key='SEPARATE_IN')
250 separate_in = SeparateStr('\n', config_key='SEPARATE_IN')
270 separate_out = SeparateStr('', config_key='SEPARATE_OUT')
251 separate_out = SeparateStr('', config_key='SEPARATE_OUT')
271 separate_out2 = SeparateStr('', config_key='SEPARATE_OUT2')
252 separate_out2 = SeparateStr('', config_key='SEPARATE_OUT2')
272
253
273 system_header = Str('IPython system call: ', config_key='SYSTEM_HEADER')
254 system_header = Str('IPython system call: ', config_key='SYSTEM_HEADER')
274 system_verbose = CBool(False, config_key='SYSTEM_VERBOSE')
255 system_verbose = CBool(False, config_key='SYSTEM_VERBOSE')
275 term_title = CBool(False, config_key='TERM_TITLE')
256 term_title = CBool(False, config_key='TERM_TITLE')
276 wildcards_case_sensitive = CBool(True, config_key='WILDCARDS_CASE_SENSITIVE')
257 wildcards_case_sensitive = CBool(True, config_key='WILDCARDS_CASE_SENSITIVE')
277 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
258 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
278 default_value='Context', config_key='XMODE')
259 default_value='Context', config_key='XMODE')
279
260
280 alias = List(allow_none=False, config_key='ALIAS')
261 alias = List(allow_none=False, config_key='ALIAS')
281 autoexec = List(allow_none=False)
262 autoexec = List(allow_none=False)
282
263
283 # class attribute to indicate whether the class supports threads or not.
264 # class attribute to indicate whether the class supports threads or not.
284 # Subclasses with thread support should override this as needed.
265 # Subclasses with thread support should override this as needed.
285 isthreaded = False
266 isthreaded = False
286
267
287 def __init__(self, parent=None, config=None, ipythondir=None, usage=None,
268 def __init__(self, parent=None, config=None, ipythondir=None, usage=None,
288 user_ns=None, user_global_ns=None,
269 user_ns=None, user_global_ns=None,
289 banner1=None, banner2=None,
270 banner1=None, banner2=None,
290 custom_exceptions=((),None)):
271 custom_exceptions=((),None)):
291
272
292 # This is where traitlets with a config_key argument are updated
273 # This is where traitlets with a config_key argument are updated
293 # from the values on config.
274 # from the values on config.
294 super(InteractiveShell, self).__init__(parent, config=config, name='__IP')
275 super(InteractiveShell, self).__init__(parent, config=config, name='__IP')
295
276
296 # These are relatively independent and stateless
277 # These are relatively independent and stateless
297 self.init_ipythondir(ipythondir)
278 self.init_ipythondir(ipythondir)
298 self.init_instance_attrs()
279 self.init_instance_attrs()
299 self.init_term_title()
280 self.init_term_title()
300 self.init_usage(usage)
281 self.init_usage(usage)
301 self.init_banner(banner1, banner2)
282 self.init_banner(banner1, banner2)
302
283
303 # Create namespaces (user_ns, user_global_ns, alias_table, etc.)
284 # Create namespaces (user_ns, user_global_ns, alias_table, etc.)
304 self.init_create_namespaces(user_ns, user_global_ns)
285 self.init_create_namespaces(user_ns, user_global_ns)
305 # This has to be done after init_create_namespaces because it uses
286 # This has to be done after init_create_namespaces because it uses
306 # something in self.user_ns, but before init_sys_modules, which
287 # something in self.user_ns, but before init_sys_modules, which
307 # is the first thing to modify sys.
288 # is the first thing to modify sys.
308 self.save_sys_module_state()
289 self.save_sys_module_state()
309 self.init_sys_modules()
290 self.init_sys_modules()
310
291
311 self.init_history()
292 self.init_history()
312 self.init_encoding()
293 self.init_encoding()
313 self.init_handlers()
294 self.init_handlers()
314
295
315 Magic.__init__(self, self)
296 Magic.__init__(self, self)
316
297
317 self.init_syntax_highlighting()
298 self.init_syntax_highlighting()
318 self.init_hooks()
299 self.init_hooks()
319 self.init_pushd_popd_magic()
300 self.init_pushd_popd_magic()
320 self.init_traceback_handlers(custom_exceptions)
301 self.init_traceback_handlers(custom_exceptions)
321 self.init_user_ns()
302 self.init_user_ns()
322 self.init_logger()
303 self.init_logger()
323 self.init_aliases()
304 self.init_aliases()
324 self.init_builtins()
305 self.init_builtins()
325
306
326 # pre_config_initialization
307 # pre_config_initialization
327 self.init_shadow_hist()
308 self.init_shadow_hist()
328
309
329 # The next section should contain averything that was in ipmaker.
310 # The next section should contain averything that was in ipmaker.
330 self.init_logstart()
311 self.init_logstart()
331
312
332 # The following was in post_config_initialization
313 # The following was in post_config_initialization
333 self.init_inspector()
314 self.init_inspector()
334 self.init_readline()
315 self.init_readline()
335 self.init_prompts()
316 self.init_prompts()
336 self.init_displayhook()
317 self.init_displayhook()
337 self.init_reload_doctest()
318 self.init_reload_doctest()
338 self.init_magics()
319 self.init_magics()
339 self.init_pdb()
320 self.init_pdb()
340 self.hooks.late_startup_hook()
321 self.hooks.late_startup_hook()
341
322
342 def cleanup(self):
323 def cleanup(self):
343 self.remove_builtins()
344 self.restore_sys_module_state()
324 self.restore_sys_module_state()
345
325
346 #-------------------------------------------------------------------------
326 #-------------------------------------------------------------------------
347 # Traitlet changed handlers
327 # Traitlet changed handlers
348 #-------------------------------------------------------------------------
328 #-------------------------------------------------------------------------
349
329
350 def _banner1_changed(self):
330 def _banner1_changed(self):
351 self.compute_banner()
331 self.compute_banner()
352
332
353 def _banner2_changed(self):
333 def _banner2_changed(self):
354 self.compute_banner()
334 self.compute_banner()
355
335
356 @property
336 @property
357 def usable_screen_length(self):
337 def usable_screen_length(self):
358 if self.screen_length == 0:
338 if self.screen_length == 0:
359 return 0
339 return 0
360 else:
340 else:
361 num_lines_bot = self.separate_in.count('\n')+1
341 num_lines_bot = self.separate_in.count('\n')+1
362 return self.screen_length - num_lines_bot
342 return self.screen_length - num_lines_bot
363
343
364 def _term_title_changed(self, name, new_value):
344 def _term_title_changed(self, name, new_value):
365 self.init_term_title()
345 self.init_term_title()
366
346
367 #-------------------------------------------------------------------------
347 #-------------------------------------------------------------------------
368 # init_* methods called by __init__
348 # init_* methods called by __init__
369 #-------------------------------------------------------------------------
349 #-------------------------------------------------------------------------
370
350
371 def init_ipythondir(self, ipythondir):
351 def init_ipythondir(self, ipythondir):
372 if ipythondir is not None:
352 if ipythondir is not None:
373 self.ipythondir = ipythondir
353 self.ipythondir = ipythondir
374 self.config.IPYTHONDIR = self.ipythondir
354 self.config.IPYTHONDIR = self.ipythondir
375 return
355 return
376
356
377 if hasattr(self.config, 'IPYTHONDIR'):
357 if hasattr(self.config, 'IPYTHONDIR'):
378 self.ipythondir = self.config.IPYTHONDIR
358 self.ipythondir = self.config.IPYTHONDIR
379 if not hasattr(self.config, 'IPYTHONDIR'):
359 if not hasattr(self.config, 'IPYTHONDIR'):
380 # cdw is always defined
360 # cdw is always defined
381 self.ipythondir = os.getcwd()
361 self.ipythondir = os.getcwd()
382
362
383 # The caller must make sure that ipythondir exists. We should
363 # The caller must make sure that ipythondir exists. We should
384 # probably handle this using a Dir traitlet.
364 # probably handle this using a Dir traitlet.
385 if not os.path.isdir(self.ipythondir):
365 if not os.path.isdir(self.ipythondir):
386 raise IOError('IPython dir does not exist: %s' % self.ipythondir)
366 raise IOError('IPython dir does not exist: %s' % self.ipythondir)
387
367
388 # All children can just read this
368 # All children can just read this
389 self.config.IPYTHONDIR = self.ipythondir
369 self.config.IPYTHONDIR = self.ipythondir
390
370
391 def init_instance_attrs(self):
371 def init_instance_attrs(self):
392 self.jobs = BackgroundJobManager()
372 self.jobs = BackgroundJobManager()
393 self.more = False
373 self.more = False
394
374
395 # command compiler
375 # command compiler
396 self.compile = codeop.CommandCompiler()
376 self.compile = codeop.CommandCompiler()
397
377
398 # User input buffer
378 # User input buffer
399 self.buffer = []
379 self.buffer = []
400
380
401 # Make an empty namespace, which extension writers can rely on both
381 # Make an empty namespace, which extension writers can rely on both
402 # existing and NEVER being used by ipython itself. This gives them a
382 # existing and NEVER being used by ipython itself. This gives them a
403 # convenient location for storing additional information and state
383 # convenient location for storing additional information and state
404 # their extensions may require, without fear of collisions with other
384 # their extensions may require, without fear of collisions with other
405 # ipython names that may develop later.
385 # ipython names that may develop later.
406 self.meta = Struct()
386 self.meta = Struct()
407
387
408 # Object variable to store code object waiting execution. This is
388 # Object variable to store code object waiting execution. This is
409 # used mainly by the multithreaded shells, but it can come in handy in
389 # used mainly by the multithreaded shells, but it can come in handy in
410 # other situations. No need to use a Queue here, since it's a single
390 # other situations. No need to use a Queue here, since it's a single
411 # item which gets cleared once run.
391 # item which gets cleared once run.
412 self.code_to_run = None
392 self.code_to_run = None
413
393
414 # Flag to mark unconditional exit
394 # Flag to mark unconditional exit
415 self.exit_now = False
395 self.exit_now = False
416
396
417 # Temporary files used for various purposes. Deleted at exit.
397 # Temporary files used for various purposes. Deleted at exit.
418 self.tempfiles = []
398 self.tempfiles = []
419
399
420 # Keep track of readline usage (later set by init_readline)
400 # Keep track of readline usage (later set by init_readline)
421 self.has_readline = False
401 self.has_readline = False
422
402
423 # keep track of where we started running (mainly for crash post-mortem)
403 # keep track of where we started running (mainly for crash post-mortem)
424 # This is not being used anywhere currently.
404 # This is not being used anywhere currently.
425 self.starting_dir = os.getcwd()
405 self.starting_dir = os.getcwd()
426
406
427 # Indentation management
407 # Indentation management
428 self.indent_current_nsp = 0
408 self.indent_current_nsp = 0
429
409
430 def init_term_title(self):
410 def init_term_title(self):
431 # Enable or disable the terminal title.
411 # Enable or disable the terminal title.
432 if self.term_title:
412 if self.term_title:
433 toggle_set_term_title(True)
413 toggle_set_term_title(True)
434 set_term_title('IPython: ' + abbrev_cwd())
414 set_term_title('IPython: ' + abbrev_cwd())
435 else:
415 else:
436 toggle_set_term_title(False)
416 toggle_set_term_title(False)
437
417
438 def init_usage(self, usage=None):
418 def init_usage(self, usage=None):
439 if usage is None:
419 if usage is None:
440 self.usage = interactive_usage
420 self.usage = interactive_usage
441 else:
421 else:
442 self.usage = usage
422 self.usage = usage
443
423
444 def init_banner(self, banner1, banner2):
424 def init_banner(self, banner1, banner2):
445 if self.c: # regular python doesn't print the banner with -c
425 if self.c: # regular python doesn't print the banner with -c
446 self.display_banner = False
426 self.display_banner = False
447 if banner1 is not None:
427 if banner1 is not None:
448 self.banner1 = banner1
428 self.banner1 = banner1
449 if banner2 is not None:
429 if banner2 is not None:
450 self.banner2 = banner2
430 self.banner2 = banner2
451 self.compute_banner()
431 self.compute_banner()
452
432
453 def compute_banner(self):
433 def compute_banner(self):
454 self.banner = self.banner1 + '\n'
434 self.banner = self.banner1 + '\n'
455 if self.profile:
435 if self.profile:
456 self.banner += '\nIPython profile: %s\n' % self.profile
436 self.banner += '\nIPython profile: %s\n' % self.profile
457 if self.banner2:
437 if self.banner2:
458 self.banner += '\n' + self.banner2 + '\n'
438 self.banner += '\n' + self.banner2 + '\n'
459
439
460 def init_create_namespaces(self, user_ns=None, user_global_ns=None):
440 def init_create_namespaces(self, user_ns=None, user_global_ns=None):
461 # Create the namespace where the user will operate. user_ns is
441 # Create the namespace where the user will operate. user_ns is
462 # normally the only one used, and it is passed to the exec calls as
442 # normally the only one used, and it is passed to the exec calls as
463 # the locals argument. But we do carry a user_global_ns namespace
443 # the locals argument. But we do carry a user_global_ns namespace
464 # given as the exec 'globals' argument, This is useful in embedding
444 # given as the exec 'globals' argument, This is useful in embedding
465 # situations where the ipython shell opens in a context where the
445 # situations where the ipython shell opens in a context where the
466 # distinction between locals and globals is meaningful. For
446 # distinction between locals and globals is meaningful. For
467 # non-embedded contexts, it is just the same object as the user_ns dict.
447 # non-embedded contexts, it is just the same object as the user_ns dict.
468
448
469 # FIXME. For some strange reason, __builtins__ is showing up at user
449 # FIXME. For some strange reason, __builtins__ is showing up at user
470 # level as a dict instead of a module. This is a manual fix, but I
450 # level as a dict instead of a module. This is a manual fix, but I
471 # should really track down where the problem is coming from. Alex
451 # should really track down where the problem is coming from. Alex
472 # Schmolck reported this problem first.
452 # Schmolck reported this problem first.
473
453
474 # A useful post by Alex Martelli on this topic:
454 # A useful post by Alex Martelli on this topic:
475 # Re: inconsistent value from __builtins__
455 # Re: inconsistent value from __builtins__
476 # Von: Alex Martelli <aleaxit@yahoo.com>
456 # Von: Alex Martelli <aleaxit@yahoo.com>
477 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
457 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
478 # Gruppen: comp.lang.python
458 # Gruppen: comp.lang.python
479
459
480 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
460 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
481 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
461 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
482 # > <type 'dict'>
462 # > <type 'dict'>
483 # > >>> print type(__builtins__)
463 # > >>> print type(__builtins__)
484 # > <type 'module'>
464 # > <type 'module'>
485 # > Is this difference in return value intentional?
465 # > Is this difference in return value intentional?
486
466
487 # Well, it's documented that '__builtins__' can be either a dictionary
467 # Well, it's documented that '__builtins__' can be either a dictionary
488 # or a module, and it's been that way for a long time. Whether it's
468 # or a module, and it's been that way for a long time. Whether it's
489 # intentional (or sensible), I don't know. In any case, the idea is
469 # intentional (or sensible), I don't know. In any case, the idea is
490 # that if you need to access the built-in namespace directly, you
470 # that if you need to access the built-in namespace directly, you
491 # should start with "import __builtin__" (note, no 's') which will
471 # should start with "import __builtin__" (note, no 's') which will
492 # definitely give you a module. Yeah, it's somewhat confusing:-(.
472 # definitely give you a module. Yeah, it's somewhat confusing:-(.
493
473
494 # These routines return properly built dicts as needed by the rest of
474 # These routines return properly built dicts as needed by the rest of
495 # the code, and can also be used by extension writers to generate
475 # the code, and can also be used by extension writers to generate
496 # properly initialized namespaces.
476 # properly initialized namespaces.
497 user_ns, user_global_ns = self.make_user_namespaces(user_ns,
477 user_ns, user_global_ns = self.make_user_namespaces(user_ns,
498 user_global_ns)
478 user_global_ns)
499
479
500 # Assign namespaces
480 # Assign namespaces
501 # This is the namespace where all normal user variables live
481 # This is the namespace where all normal user variables live
502 self.user_ns = user_ns
482 self.user_ns = user_ns
503 self.user_global_ns = user_global_ns
483 self.user_global_ns = user_global_ns
504
484
505 # An auxiliary namespace that checks what parts of the user_ns were
485 # An auxiliary namespace that checks what parts of the user_ns were
506 # loaded at startup, so we can list later only variables defined in
486 # loaded at startup, so we can list later only variables defined in
507 # actual interactive use. Since it is always a subset of user_ns, it
487 # actual interactive use. Since it is always a subset of user_ns, it
508 # doesn't need to be seaparately tracked in the ns_table
488 # doesn't need to be seaparately tracked in the ns_table
509 self.user_config_ns = {}
489 self.user_config_ns = {}
510
490
511 # A namespace to keep track of internal data structures to prevent
491 # A namespace to keep track of internal data structures to prevent
512 # them from cluttering user-visible stuff. Will be updated later
492 # them from cluttering user-visible stuff. Will be updated later
513 self.internal_ns = {}
493 self.internal_ns = {}
514
494
515 # Namespace of system aliases. Each entry in the alias
495 # Namespace of system aliases. Each entry in the alias
516 # table must be a 2-tuple of the form (N,name), where N is the number
496 # table must be a 2-tuple of the form (N,name), where N is the number
517 # of positional arguments of the alias.
497 # of positional arguments of the alias.
518 self.alias_table = {}
498 self.alias_table = {}
519
499
520 # Now that FakeModule produces a real module, we've run into a nasty
500 # Now that FakeModule produces a real module, we've run into a nasty
521 # problem: after script execution (via %run), the module where the user
501 # problem: after script execution (via %run), the module where the user
522 # code ran is deleted. Now that this object is a true module (needed
502 # code ran is deleted. Now that this object is a true module (needed
523 # so docetst and other tools work correctly), the Python module
503 # so docetst and other tools work correctly), the Python module
524 # teardown mechanism runs over it, and sets to None every variable
504 # teardown mechanism runs over it, and sets to None every variable
525 # present in that module. Top-level references to objects from the
505 # present in that module. Top-level references to objects from the
526 # script survive, because the user_ns is updated with them. However,
506 # script survive, because the user_ns is updated with them. However,
527 # calling functions defined in the script that use other things from
507 # calling functions defined in the script that use other things from
528 # the script will fail, because the function's closure had references
508 # the script will fail, because the function's closure had references
529 # to the original objects, which are now all None. So we must protect
509 # to the original objects, which are now all None. So we must protect
530 # these modules from deletion by keeping a cache.
510 # these modules from deletion by keeping a cache.
531 #
511 #
532 # To avoid keeping stale modules around (we only need the one from the
512 # To avoid keeping stale modules around (we only need the one from the
533 # last run), we use a dict keyed with the full path to the script, so
513 # last run), we use a dict keyed with the full path to the script, so
534 # only the last version of the module is held in the cache. Note,
514 # only the last version of the module is held in the cache. Note,
535 # however, that we must cache the module *namespace contents* (their
515 # however, that we must cache the module *namespace contents* (their
536 # __dict__). Because if we try to cache the actual modules, old ones
516 # __dict__). Because if we try to cache the actual modules, old ones
537 # (uncached) could be destroyed while still holding references (such as
517 # (uncached) could be destroyed while still holding references (such as
538 # those held by GUI objects that tend to be long-lived)>
518 # those held by GUI objects that tend to be long-lived)>
539 #
519 #
540 # The %reset command will flush this cache. See the cache_main_mod()
520 # The %reset command will flush this cache. See the cache_main_mod()
541 # and clear_main_mod_cache() methods for details on use.
521 # and clear_main_mod_cache() methods for details on use.
542
522
543 # This is the cache used for 'main' namespaces
523 # This is the cache used for 'main' namespaces
544 self._main_ns_cache = {}
524 self._main_ns_cache = {}
545 # And this is the single instance of FakeModule whose __dict__ we keep
525 # And this is the single instance of FakeModule whose __dict__ we keep
546 # copying and clearing for reuse on each %run
526 # copying and clearing for reuse on each %run
547 self._user_main_module = FakeModule()
527 self._user_main_module = FakeModule()
548
528
549 # A table holding all the namespaces IPython deals with, so that
529 # A table holding all the namespaces IPython deals with, so that
550 # introspection facilities can search easily.
530 # introspection facilities can search easily.
551 self.ns_table = {'user':user_ns,
531 self.ns_table = {'user':user_ns,
552 'user_global':user_global_ns,
532 'user_global':user_global_ns,
553 'alias':self.alias_table,
533 'alias':self.alias_table,
554 'internal':self.internal_ns,
534 'internal':self.internal_ns,
555 'builtin':__builtin__.__dict__
535 'builtin':__builtin__.__dict__
556 }
536 }
557
537
558 # Similarly, track all namespaces where references can be held and that
538 # Similarly, track all namespaces where references can be held and that
559 # we can safely clear (so it can NOT include builtin). This one can be
539 # we can safely clear (so it can NOT include builtin). This one can be
560 # a simple list.
540 # a simple list.
561 self.ns_refs_table = [ user_ns, user_global_ns, self.user_config_ns,
541 self.ns_refs_table = [ user_ns, user_global_ns, self.user_config_ns,
562 self.alias_table, self.internal_ns,
542 self.alias_table, self.internal_ns,
563 self._main_ns_cache ]
543 self._main_ns_cache ]
564
544
565 def init_sys_modules(self):
545 def init_sys_modules(self):
566 # We need to insert into sys.modules something that looks like a
546 # We need to insert into sys.modules something that looks like a
567 # module but which accesses the IPython namespace, for shelve and
547 # module but which accesses the IPython namespace, for shelve and
568 # pickle to work interactively. Normally they rely on getting
548 # pickle to work interactively. Normally they rely on getting
569 # everything out of __main__, but for embedding purposes each IPython
549 # everything out of __main__, but for embedding purposes each IPython
570 # instance has its own private namespace, so we can't go shoving
550 # instance has its own private namespace, so we can't go shoving
571 # everything into __main__.
551 # everything into __main__.
572
552
573 # note, however, that we should only do this for non-embedded
553 # note, however, that we should only do this for non-embedded
574 # ipythons, which really mimic the __main__.__dict__ with their own
554 # ipythons, which really mimic the __main__.__dict__ with their own
575 # namespace. Embedded instances, on the other hand, should not do
555 # namespace. Embedded instances, on the other hand, should not do
576 # this because they need to manage the user local/global namespaces
556 # this because they need to manage the user local/global namespaces
577 # only, but they live within a 'normal' __main__ (meaning, they
557 # only, but they live within a 'normal' __main__ (meaning, they
578 # shouldn't overtake the execution environment of the script they're
558 # shouldn't overtake the execution environment of the script they're
579 # embedded in).
559 # embedded in).
580
560
581 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
561 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
582
562
583 try:
563 try:
584 main_name = self.user_ns['__name__']
564 main_name = self.user_ns['__name__']
585 except KeyError:
565 except KeyError:
586 raise KeyError('user_ns dictionary MUST have a "__name__" key')
566 raise KeyError('user_ns dictionary MUST have a "__name__" key')
587 else:
567 else:
588 sys.modules[main_name] = FakeModule(self.user_ns)
568 sys.modules[main_name] = FakeModule(self.user_ns)
589
569
590 def make_user_namespaces(self, user_ns=None, user_global_ns=None):
570 def make_user_namespaces(self, user_ns=None, user_global_ns=None):
591 """Return a valid local and global user interactive namespaces.
571 """Return a valid local and global user interactive namespaces.
592
572
593 This builds a dict with the minimal information needed to operate as a
573 This builds a dict with the minimal information needed to operate as a
594 valid IPython user namespace, which you can pass to the various
574 valid IPython user namespace, which you can pass to the various
595 embedding classes in ipython. The default implementation returns the
575 embedding classes in ipython. The default implementation returns the
596 same dict for both the locals and the globals to allow functions to
576 same dict for both the locals and the globals to allow functions to
597 refer to variables in the namespace. Customized implementations can
577 refer to variables in the namespace. Customized implementations can
598 return different dicts. The locals dictionary can actually be anything
578 return different dicts. The locals dictionary can actually be anything
599 following the basic mapping protocol of a dict, but the globals dict
579 following the basic mapping protocol of a dict, but the globals dict
600 must be a true dict, not even a subclass. It is recommended that any
580 must be a true dict, not even a subclass. It is recommended that any
601 custom object for the locals namespace synchronize with the globals
581 custom object for the locals namespace synchronize with the globals
602 dict somehow.
582 dict somehow.
603
583
604 Raises TypeError if the provided globals namespace is not a true dict.
584 Raises TypeError if the provided globals namespace is not a true dict.
605
585
606 :Parameters:
586 :Parameters:
607 user_ns : dict-like, optional
587 user_ns : dict-like, optional
608 The current user namespace. The items in this namespace should
588 The current user namespace. The items in this namespace should
609 be included in the output. If None, an appropriate blank
589 be included in the output. If None, an appropriate blank
610 namespace should be created.
590 namespace should be created.
611 user_global_ns : dict, optional
591 user_global_ns : dict, optional
612 The current user global namespace. The items in this namespace
592 The current user global namespace. The items in this namespace
613 should be included in the output. If None, an appropriate
593 should be included in the output. If None, an appropriate
614 blank namespace should be created.
594 blank namespace should be created.
615
595
616 :Returns:
596 :Returns:
617 A tuple pair of dictionary-like object to be used as the local namespace
597 A tuple pair of dictionary-like object to be used as the local namespace
618 of the interpreter and a dict to be used as the global namespace.
598 of the interpreter and a dict to be used as the global namespace.
619 """
599 """
620
600
621 if user_ns is None:
601 if user_ns is None:
622 # Set __name__ to __main__ to better match the behavior of the
602 # Set __name__ to __main__ to better match the behavior of the
623 # normal interpreter.
603 # normal interpreter.
624 user_ns = {'__name__' :'__main__',
604 user_ns = {'__name__' :'__main__',
625 '__builtins__' : __builtin__,
605 '__builtins__' : __builtin__,
626 }
606 }
627 else:
607 else:
628 user_ns.setdefault('__name__','__main__')
608 user_ns.setdefault('__name__','__main__')
629 user_ns.setdefault('__builtins__',__builtin__)
609 user_ns.setdefault('__builtins__',__builtin__)
630
610
631 if user_global_ns is None:
611 if user_global_ns is None:
632 user_global_ns = user_ns
612 user_global_ns = user_ns
633 if type(user_global_ns) is not dict:
613 if type(user_global_ns) is not dict:
634 raise TypeError("user_global_ns must be a true dict; got %r"
614 raise TypeError("user_global_ns must be a true dict; got %r"
635 % type(user_global_ns))
615 % type(user_global_ns))
636
616
637 return user_ns, user_global_ns
617 return user_ns, user_global_ns
638
618
639 def init_history(self):
619 def init_history(self):
640 # List of input with multi-line handling.
620 # List of input with multi-line handling.
641 self.input_hist = InputList()
621 self.input_hist = InputList()
642 # This one will hold the 'raw' input history, without any
622 # This one will hold the 'raw' input history, without any
643 # pre-processing. This will allow users to retrieve the input just as
623 # pre-processing. This will allow users to retrieve the input just as
644 # it was exactly typed in by the user, with %hist -r.
624 # it was exactly typed in by the user, with %hist -r.
645 self.input_hist_raw = InputList()
625 self.input_hist_raw = InputList()
646
626
647 # list of visited directories
627 # list of visited directories
648 try:
628 try:
649 self.dir_hist = [os.getcwd()]
629 self.dir_hist = [os.getcwd()]
650 except OSError:
630 except OSError:
651 self.dir_hist = []
631 self.dir_hist = []
652
632
653 # dict of output history
633 # dict of output history
654 self.output_hist = {}
634 self.output_hist = {}
655
635
656 # Now the history file
636 # Now the history file
657 try:
637 try:
658 histfname = 'history-%s' % self.profile
638 histfname = 'history-%s' % self.profile
659 except AttributeError:
639 except AttributeError:
660 histfname = 'history'
640 histfname = 'history'
661 self.histfile = os.path.join(self.config.IPYTHONDIR, histfname)
641 self.histfile = os.path.join(self.config.IPYTHONDIR, histfname)
662
642
663 # Fill the history zero entry, user counter starts at 1
643 # Fill the history zero entry, user counter starts at 1
664 self.input_hist.append('\n')
644 self.input_hist.append('\n')
665 self.input_hist_raw.append('\n')
645 self.input_hist_raw.append('\n')
666
646
667 def init_encoding(self):
647 def init_encoding(self):
668 # Get system encoding at startup time. Certain terminals (like Emacs
648 # Get system encoding at startup time. Certain terminals (like Emacs
669 # under Win32 have it set to None, and we need to have a known valid
649 # under Win32 have it set to None, and we need to have a known valid
670 # encoding to use in the raw_input() method
650 # encoding to use in the raw_input() method
671 try:
651 try:
672 self.stdin_encoding = sys.stdin.encoding or 'ascii'
652 self.stdin_encoding = sys.stdin.encoding or 'ascii'
673 except AttributeError:
653 except AttributeError:
674 self.stdin_encoding = 'ascii'
654 self.stdin_encoding = 'ascii'
675
655
676 def init_handlers(self):
656 def init_handlers(self):
677 # escapes for automatic behavior on the command line
657 # escapes for automatic behavior on the command line
678 self.ESC_SHELL = '!'
658 self.ESC_SHELL = '!'
679 self.ESC_SH_CAP = '!!'
659 self.ESC_SH_CAP = '!!'
680 self.ESC_HELP = '?'
660 self.ESC_HELP = '?'
681 self.ESC_MAGIC = '%'
661 self.ESC_MAGIC = '%'
682 self.ESC_QUOTE = ','
662 self.ESC_QUOTE = ','
683 self.ESC_QUOTE2 = ';'
663 self.ESC_QUOTE2 = ';'
684 self.ESC_PAREN = '/'
664 self.ESC_PAREN = '/'
685
665
686 # And their associated handlers
666 # And their associated handlers
687 self.esc_handlers = {self.ESC_PAREN : self.handle_auto,
667 self.esc_handlers = {self.ESC_PAREN : self.handle_auto,
688 self.ESC_QUOTE : self.handle_auto,
668 self.ESC_QUOTE : self.handle_auto,
689 self.ESC_QUOTE2 : self.handle_auto,
669 self.ESC_QUOTE2 : self.handle_auto,
690 self.ESC_MAGIC : self.handle_magic,
670 self.ESC_MAGIC : self.handle_magic,
691 self.ESC_HELP : self.handle_help,
671 self.ESC_HELP : self.handle_help,
692 self.ESC_SHELL : self.handle_shell_escape,
672 self.ESC_SHELL : self.handle_shell_escape,
693 self.ESC_SH_CAP : self.handle_shell_escape,
673 self.ESC_SH_CAP : self.handle_shell_escape,
694 }
674 }
695
675
696 def init_syntax_highlighting(self):
676 def init_syntax_highlighting(self):
697 # Python source parser/formatter for syntax highlighting
677 # Python source parser/formatter for syntax highlighting
698 pyformat = PyColorize.Parser().format
678 pyformat = PyColorize.Parser().format
699 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
679 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
700
680
701 def init_hooks(self):
681 def init_hooks(self):
702 # hooks holds pointers used for user-side customizations
682 # hooks holds pointers used for user-side customizations
703 self.hooks = Struct()
683 self.hooks = Struct()
704
684
705 self.strdispatchers = {}
685 self.strdispatchers = {}
706
686
707 # Set all default hooks, defined in the IPython.hooks module.
687 # Set all default hooks, defined in the IPython.hooks module.
708 import IPython.core.hooks
688 import IPython.core.hooks
709 hooks = IPython.core.hooks
689 hooks = IPython.core.hooks
710 for hook_name in hooks.__all__:
690 for hook_name in hooks.__all__:
711 # default hooks have priority 100, i.e. low; user hooks should have
691 # default hooks have priority 100, i.e. low; user hooks should have
712 # 0-100 priority
692 # 0-100 priority
713 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
693 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
714
694
715 def init_pushd_popd_magic(self):
695 def init_pushd_popd_magic(self):
716 # for pushd/popd management
696 # for pushd/popd management
717 try:
697 try:
718 self.home_dir = get_home_dir()
698 self.home_dir = get_home_dir()
719 except HomeDirError, msg:
699 except HomeDirError, msg:
720 fatal(msg)
700 fatal(msg)
721
701
722 self.dir_stack = []
702 self.dir_stack = []
723
703
724 def init_traceback_handlers(self, custom_exceptions):
704 def init_traceback_handlers(self, custom_exceptions):
725 # Syntax error handler.
705 # Syntax error handler.
726 self.SyntaxTB = SyntaxTB(color_scheme='NoColor')
706 self.SyntaxTB = SyntaxTB(color_scheme='NoColor')
727
707
728 # The interactive one is initialized with an offset, meaning we always
708 # The interactive one is initialized with an offset, meaning we always
729 # want to remove the topmost item in the traceback, which is our own
709 # want to remove the topmost item in the traceback, which is our own
730 # internal code. Valid modes: ['Plain','Context','Verbose']
710 # internal code. Valid modes: ['Plain','Context','Verbose']
731 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
711 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
732 color_scheme='NoColor',
712 color_scheme='NoColor',
733 tb_offset = 1)
713 tb_offset = 1)
734
714
735 # IPython itself shouldn't crash. This will produce a detailed
715 # IPython itself shouldn't crash. This will produce a detailed
736 # post-mortem if it does. But we only install the crash handler for
716 # post-mortem if it does. But we only install the crash handler for
737 # non-threaded shells, the threaded ones use a normal verbose reporter
717 # non-threaded shells, the threaded ones use a normal verbose reporter
738 # and lose the crash handler. This is because exceptions in the main
718 # and lose the crash handler. This is because exceptions in the main
739 # thread (such as in GUI code) propagate directly to sys.excepthook,
719 # thread (such as in GUI code) propagate directly to sys.excepthook,
740 # and there's no point in printing crash dumps for every user exception.
720 # and there's no point in printing crash dumps for every user exception.
741 if self.isthreaded:
721 if self.isthreaded:
742 ipCrashHandler = ultratb.FormattedTB()
722 ipCrashHandler = ultratb.FormattedTB()
743 else:
723 else:
744 from IPython.core import crashhandler
724 from IPython.core import crashhandler
745 ipCrashHandler = crashhandler.IPythonCrashHandler(self)
725 ipCrashHandler = crashhandler.IPythonCrashHandler(self)
746 self.set_crash_handler(ipCrashHandler)
726 self.set_crash_handler(ipCrashHandler)
747
727
748 # and add any custom exception handlers the user may have specified
728 # and add any custom exception handlers the user may have specified
749 self.set_custom_exc(*custom_exceptions)
729 self.set_custom_exc(*custom_exceptions)
750
730
751 def init_logger(self):
731 def init_logger(self):
752 self.logger = Logger(self, logfname='ipython_log.py', logmode='rotate')
732 self.logger = Logger(self, logfname='ipython_log.py', logmode='rotate')
753 # local shortcut, this is used a LOT
733 # local shortcut, this is used a LOT
754 self.log = self.logger.log
734 self.log = self.logger.log
755 # template for logfile headers. It gets resolved at runtime by the
735 # template for logfile headers. It gets resolved at runtime by the
756 # logstart method.
736 # logstart method.
757 self.loghead_tpl = \
737 self.loghead_tpl = \
758 """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE ***
738 """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE ***
759 #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW
739 #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW
760 #log# opts = %s
740 #log# opts = %s
761 #log# args = %s
741 #log# args = %s
762 #log# It is safe to make manual edits below here.
742 #log# It is safe to make manual edits below here.
763 #log#-----------------------------------------------------------------------
743 #log#-----------------------------------------------------------------------
764 """
744 """
765
745
766 def init_logstart(self):
746 def init_logstart(self):
767 if self.logplay:
747 if self.logplay:
768 self.magic_logstart(self.logplay + ' append')
748 self.magic_logstart(self.logplay + ' append')
769 elif self.logfile:
749 elif self.logfile:
770 self.magic_logstart(self.logfile)
750 self.magic_logstart(self.logfile)
771 elif self.logstart:
751 elif self.logstart:
772 self.magic_logstart()
752 self.magic_logstart()
773
753
774 def init_aliases(self):
754 def init_aliases(self):
775 # dict of things NOT to alias (keywords, builtins and some magics)
755 # dict of things NOT to alias (keywords, builtins and some magics)
776 no_alias = {}
756 no_alias = {}
777 no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias']
757 no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias']
778 for key in keyword.kwlist + no_alias_magics:
758 for key in keyword.kwlist + no_alias_magics:
779 no_alias[key] = 1
759 no_alias[key] = 1
780 no_alias.update(__builtin__.__dict__)
760 no_alias.update(__builtin__.__dict__)
781 self.no_alias = no_alias
761 self.no_alias = no_alias
782
762
783 # Make some aliases automatically
763 # Make some aliases automatically
784 # Prepare list of shell aliases to auto-define
764 # Prepare list of shell aliases to auto-define
785 if os.name == 'posix':
765 if os.name == 'posix':
786 auto_alias = ('mkdir mkdir', 'rmdir rmdir',
766 auto_alias = ('mkdir mkdir', 'rmdir rmdir',
787 'mv mv -i','rm rm -i','cp cp -i',
767 'mv mv -i','rm rm -i','cp cp -i',
788 'cat cat','less less','clear clear',
768 'cat cat','less less','clear clear',
789 # a better ls
769 # a better ls
790 'ls ls -F',
770 'ls ls -F',
791 # long ls
771 # long ls
792 'll ls -lF')
772 'll ls -lF')
793 # Extra ls aliases with color, which need special treatment on BSD
773 # Extra ls aliases with color, which need special treatment on BSD
794 # variants
774 # variants
795 ls_extra = ( # color ls
775 ls_extra = ( # color ls
796 'lc ls -F -o --color',
776 'lc ls -F -o --color',
797 # ls normal files only
777 # ls normal files only
798 'lf ls -F -o --color %l | grep ^-',
778 'lf ls -F -o --color %l | grep ^-',
799 # ls symbolic links
779 # ls symbolic links
800 'lk ls -F -o --color %l | grep ^l',
780 'lk ls -F -o --color %l | grep ^l',
801 # directories or links to directories,
781 # directories or links to directories,
802 'ldir ls -F -o --color %l | grep /$',
782 'ldir ls -F -o --color %l | grep /$',
803 # things which are executable
783 # things which are executable
804 'lx ls -F -o --color %l | grep ^-..x',
784 'lx ls -F -o --color %l | grep ^-..x',
805 )
785 )
806 # The BSDs don't ship GNU ls, so they don't understand the
786 # The BSDs don't ship GNU ls, so they don't understand the
807 # --color switch out of the box
787 # --color switch out of the box
808 if 'bsd' in sys.platform:
788 if 'bsd' in sys.platform:
809 ls_extra = ( # ls normal files only
789 ls_extra = ( # ls normal files only
810 'lf ls -lF | grep ^-',
790 'lf ls -lF | grep ^-',
811 # ls symbolic links
791 # ls symbolic links
812 'lk ls -lF | grep ^l',
792 'lk ls -lF | grep ^l',
813 # directories or links to directories,
793 # directories or links to directories,
814 'ldir ls -lF | grep /$',
794 'ldir ls -lF | grep /$',
815 # things which are executable
795 # things which are executable
816 'lx ls -lF | grep ^-..x',
796 'lx ls -lF | grep ^-..x',
817 )
797 )
818 auto_alias = auto_alias + ls_extra
798 auto_alias = auto_alias + ls_extra
819 elif os.name in ['nt','dos']:
799 elif os.name in ['nt','dos']:
820 auto_alias = ('ls dir /on',
800 auto_alias = ('ls dir /on',
821 'ddir dir /ad /on', 'ldir dir /ad /on',
801 'ddir dir /ad /on', 'ldir dir /ad /on',
822 'mkdir mkdir','rmdir rmdir','echo echo',
802 'mkdir mkdir','rmdir rmdir','echo echo',
823 'ren ren','cls cls','copy copy')
803 'ren ren','cls cls','copy copy')
824 else:
804 else:
825 auto_alias = ()
805 auto_alias = ()
826 self.auto_alias = [s.split(None,1) for s in auto_alias]
806 self.auto_alias = [s.split(None,1) for s in auto_alias]
827
807
828 # Load default aliases
808 # Load default aliases
829 for alias, cmd in self.auto_alias:
809 for alias, cmd in self.auto_alias:
830 self.define_alias(alias,cmd)
810 self.define_alias(alias,cmd)
831
811
832 # Load user aliases
812 # Load user aliases
833 for alias in self.alias:
813 for alias in self.alias:
834 self.magic_alias(alias)
814 self.magic_alias(alias)
835
815
836 def init_builtins(self):
816 def init_builtins(self):
837 # track which builtins we add, so we can clean up later
817 self.builtin_trap = BuiltinTrap(self)
838 self._orig_builtins = {}
839 self._builtins_added = False
840 self.add_builtins()
841
818
842 def init_shadow_hist(self):
819 def init_shadow_hist(self):
843 try:
820 try:
844 self.db = pickleshare.PickleShareDB(self.config.IPYTHONDIR + "/db")
821 self.db = pickleshare.PickleShareDB(self.config.IPYTHONDIR + "/db")
845 except exceptions.UnicodeDecodeError:
822 except exceptions.UnicodeDecodeError:
846 print "Your ipythondir can't be decoded to unicode!"
823 print "Your ipythondir can't be decoded to unicode!"
847 print "Please set HOME environment variable to something that"
824 print "Please set HOME environment variable to something that"
848 print r"only has ASCII characters, e.g. c:\home"
825 print r"only has ASCII characters, e.g. c:\home"
849 print "Now it is", self.config.IPYTHONDIR
826 print "Now it is", self.config.IPYTHONDIR
850 sys.exit()
827 sys.exit()
851 self.shadowhist = ipcorehist.ShadowHist(self.db)
828 self.shadowhist = ipcorehist.ShadowHist(self.db)
852
829
853 def init_inspector(self):
830 def init_inspector(self):
854 # Object inspector
831 # Object inspector
855 self.inspector = oinspect.Inspector(oinspect.InspectColors,
832 self.inspector = oinspect.Inspector(oinspect.InspectColors,
856 PyColorize.ANSICodeColors,
833 PyColorize.ANSICodeColors,
857 'NoColor',
834 'NoColor',
858 self.object_info_string_level)
835 self.object_info_string_level)
859
836
860 def init_readline(self):
837 def init_readline(self):
861 """Command history completion/saving/reloading."""
838 """Command history completion/saving/reloading."""
862
839
863 self.rl_next_input = None
840 self.rl_next_input = None
864 self.rl_do_indent = False
841 self.rl_do_indent = False
865
842
866 if not self.readline_use:
843 if not self.readline_use:
867 return
844 return
868
845
869 import IPython.utils.rlineimpl as readline
846 import IPython.utils.rlineimpl as readline
870
847
871 if not readline.have_readline:
848 if not readline.have_readline:
872 self.has_readline = 0
849 self.has_readline = 0
873 self.readline = None
850 self.readline = None
874 # no point in bugging windows users with this every time:
851 # no point in bugging windows users with this every time:
875 warn('Readline services not available on this platform.')
852 warn('Readline services not available on this platform.')
876 else:
853 else:
877 sys.modules['readline'] = readline
854 sys.modules['readline'] = readline
878 import atexit
855 import atexit
879 from IPython.core.completer import IPCompleter
856 from IPython.core.completer import IPCompleter
880 self.Completer = IPCompleter(self,
857 self.Completer = IPCompleter(self,
881 self.user_ns,
858 self.user_ns,
882 self.user_global_ns,
859 self.user_global_ns,
883 self.readline_omit__names,
860 self.readline_omit__names,
884 self.alias_table)
861 self.alias_table)
885 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
862 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
886 self.strdispatchers['complete_command'] = sdisp
863 self.strdispatchers['complete_command'] = sdisp
887 self.Completer.custom_completers = sdisp
864 self.Completer.custom_completers = sdisp
888 # Platform-specific configuration
865 # Platform-specific configuration
889 if os.name == 'nt':
866 if os.name == 'nt':
890 self.readline_startup_hook = readline.set_pre_input_hook
867 self.readline_startup_hook = readline.set_pre_input_hook
891 else:
868 else:
892 self.readline_startup_hook = readline.set_startup_hook
869 self.readline_startup_hook = readline.set_startup_hook
893
870
894 # Load user's initrc file (readline config)
871 # Load user's initrc file (readline config)
895 # Or if libedit is used, load editrc.
872 # Or if libedit is used, load editrc.
896 inputrc_name = os.environ.get('INPUTRC')
873 inputrc_name = os.environ.get('INPUTRC')
897 if inputrc_name is None:
874 if inputrc_name is None:
898 home_dir = get_home_dir()
875 home_dir = get_home_dir()
899 if home_dir is not None:
876 if home_dir is not None:
900 inputrc_name = '.inputrc'
877 inputrc_name = '.inputrc'
901 if readline.uses_libedit:
878 if readline.uses_libedit:
902 inputrc_name = '.editrc'
879 inputrc_name = '.editrc'
903 inputrc_name = os.path.join(home_dir, inputrc_name)
880 inputrc_name = os.path.join(home_dir, inputrc_name)
904 if os.path.isfile(inputrc_name):
881 if os.path.isfile(inputrc_name):
905 try:
882 try:
906 readline.read_init_file(inputrc_name)
883 readline.read_init_file(inputrc_name)
907 except:
884 except:
908 warn('Problems reading readline initialization file <%s>'
885 warn('Problems reading readline initialization file <%s>'
909 % inputrc_name)
886 % inputrc_name)
910
887
911 self.has_readline = 1
888 self.has_readline = 1
912 self.readline = readline
889 self.readline = readline
913 # save this in sys so embedded copies can restore it properly
890 # save this in sys so embedded copies can restore it properly
914 sys.ipcompleter = self.Completer.complete
891 sys.ipcompleter = self.Completer.complete
915 self.set_completer()
892 self.set_completer()
916
893
917 # Configure readline according to user's prefs
894 # Configure readline according to user's prefs
918 # This is only done if GNU readline is being used. If libedit
895 # This is only done if GNU readline is being used. If libedit
919 # is being used (as on Leopard) the readline config is
896 # is being used (as on Leopard) the readline config is
920 # not run as the syntax for libedit is different.
897 # not run as the syntax for libedit is different.
921 if not readline.uses_libedit:
898 if not readline.uses_libedit:
922 for rlcommand in self.readline_parse_and_bind:
899 for rlcommand in self.readline_parse_and_bind:
923 #print "loading rl:",rlcommand # dbg
900 #print "loading rl:",rlcommand # dbg
924 readline.parse_and_bind(rlcommand)
901 readline.parse_and_bind(rlcommand)
925
902
926 # Remove some chars from the delimiters list. If we encounter
903 # Remove some chars from the delimiters list. If we encounter
927 # unicode chars, discard them.
904 # unicode chars, discard them.
928 delims = readline.get_completer_delims().encode("ascii", "ignore")
905 delims = readline.get_completer_delims().encode("ascii", "ignore")
929 delims = delims.translate(string._idmap,
906 delims = delims.translate(string._idmap,
930 self.readline_remove_delims)
907 self.readline_remove_delims)
931 readline.set_completer_delims(delims)
908 readline.set_completer_delims(delims)
932 # otherwise we end up with a monster history after a while:
909 # otherwise we end up with a monster history after a while:
933 readline.set_history_length(1000)
910 readline.set_history_length(1000)
934 try:
911 try:
935 #print '*** Reading readline history' # dbg
912 #print '*** Reading readline history' # dbg
936 readline.read_history_file(self.histfile)
913 readline.read_history_file(self.histfile)
937 except IOError:
914 except IOError:
938 pass # It doesn't exist yet.
915 pass # It doesn't exist yet.
939
916
940 atexit.register(self.atexit_operations)
917 atexit.register(self.atexit_operations)
941 del atexit
918 del atexit
942
919
943 # Configure auto-indent for all platforms
920 # Configure auto-indent for all platforms
944 self.set_autoindent(self.autoindent)
921 self.set_autoindent(self.autoindent)
945
922
946 def init_prompts(self):
923 def init_prompts(self):
947 # Initialize cache, set in/out prompts and printing system
924 # Initialize cache, set in/out prompts and printing system
948 self.outputcache = CachedOutput(self,
925 self.outputcache = CachedOutput(self,
949 self.cache_size,
926 self.cache_size,
950 self.pprint,
927 self.pprint,
951 input_sep = self.separate_in,
928 input_sep = self.separate_in,
952 output_sep = self.separate_out,
929 output_sep = self.separate_out,
953 output_sep2 = self.separate_out2,
930 output_sep2 = self.separate_out2,
954 ps1 = self.prompt_in1,
931 ps1 = self.prompt_in1,
955 ps2 = self.prompt_in2,
932 ps2 = self.prompt_in2,
956 ps_out = self.prompt_out,
933 ps_out = self.prompt_out,
957 pad_left = self.prompts_pad_left)
934 pad_left = self.prompts_pad_left)
958
935
959 # user may have over-ridden the default print hook:
936 # user may have over-ridden the default print hook:
960 try:
937 try:
961 self.outputcache.__class__.display = self.hooks.display
938 self.outputcache.__class__.display = self.hooks.display
962 except AttributeError:
939 except AttributeError:
963 pass
940 pass
964
941
965 def init_displayhook(self):
942 def init_displayhook(self):
966 # I don't like assigning globally to sys, because it means when
943 # I don't like assigning globally to sys, because it means when
967 # embedding instances, each embedded instance overrides the previous
944 # embedding instances, each embedded instance overrides the previous
968 # choice. But sys.displayhook seems to be called internally by exec,
945 # choice. But sys.displayhook seems to be called internally by exec,
969 # so I don't see a way around it. We first save the original and then
946 # so I don't see a way around it. We first save the original and then
970 # overwrite it.
947 # overwrite it.
971 self.sys_displayhook = sys.displayhook
948 self.sys_displayhook = sys.displayhook
972 sys.displayhook = self.outputcache
949 sys.displayhook = self.outputcache
973
950
974 def init_reload_doctest(self):
951 def init_reload_doctest(self):
975 # Do a proper resetting of doctest, including the necessary displayhook
952 # Do a proper resetting of doctest, including the necessary displayhook
976 # monkeypatching
953 # monkeypatching
977 try:
954 try:
978 doctest_reload()
955 doctest_reload()
979 except ImportError:
956 except ImportError:
980 warn("doctest module does not exist.")
957 warn("doctest module does not exist.")
981
958
982 def init_magics(self):
959 def init_magics(self):
983 # Set user colors (don't do it in the constructor above so that it
960 # Set user colors (don't do it in the constructor above so that it
984 # doesn't crash if colors option is invalid)
961 # doesn't crash if colors option is invalid)
985 self.magic_colors(self.colors)
962 self.magic_colors(self.colors)
986
963
987 def init_pdb(self):
964 def init_pdb(self):
988 # Set calling of pdb on exceptions
965 # Set calling of pdb on exceptions
989 # self.call_pdb is a property
966 # self.call_pdb is a property
990 self.call_pdb = self.pdb
967 self.call_pdb = self.pdb
991
968
992 # def init_exec_commands(self):
969 # def init_exec_commands(self):
993 # for cmd in self.config.EXECUTE:
970 # for cmd in self.config.EXECUTE:
994 # print "execute:", cmd
971 # print "execute:", cmd
995 # self.api.runlines(cmd)
972 # self.api.runlines(cmd)
996 #
973 #
997 # batchrun = False
974 # batchrun = False
998 # if self.config.has_key('EXECFILE'):
975 # if self.config.has_key('EXECFILE'):
999 # for batchfile in [path(arg) for arg in self.config.EXECFILE
976 # for batchfile in [path(arg) for arg in self.config.EXECFILE
1000 # if arg.lower().endswith('.ipy')]:
977 # if arg.lower().endswith('.ipy')]:
1001 # if not batchfile.isfile():
978 # if not batchfile.isfile():
1002 # print "No such batch file:", batchfile
979 # print "No such batch file:", batchfile
1003 # continue
980 # continue
1004 # self.api.runlines(batchfile.text())
981 # self.api.runlines(batchfile.text())
1005 # batchrun = True
982 # batchrun = True
1006 # # without -i option, exit after running the batch file
983 # # without -i option, exit after running the batch file
1007 # if batchrun and not self.interactive:
984 # if batchrun and not self.interactive:
1008 # self.ask_exit()
985 # self.ask_exit()
1009
986
1010 # def load(self, mod):
987 # def load(self, mod):
1011 # """ Load an extension.
988 # """ Load an extension.
1012 #
989 #
1013 # Some modules should (or must) be 'load()':ed, rather than just imported.
990 # Some modules should (or must) be 'load()':ed, rather than just imported.
1014 #
991 #
1015 # Loading will do:
992 # Loading will do:
1016 #
993 #
1017 # - run init_ipython(ip)
994 # - run init_ipython(ip)
1018 # - run ipython_firstrun(ip)
995 # - run ipython_firstrun(ip)
1019 # """
996 # """
1020 #
997 #
1021 # if mod in self.extensions:
998 # if mod in self.extensions:
1022 # # just to make sure we don't init it twice
999 # # just to make sure we don't init it twice
1023 # # note that if you 'load' a module that has already been
1000 # # note that if you 'load' a module that has already been
1024 # # imported, init_ipython gets run anyway
1001 # # imported, init_ipython gets run anyway
1025 #
1002 #
1026 # return self.extensions[mod]
1003 # return self.extensions[mod]
1027 # __import__(mod)
1004 # __import__(mod)
1028 # m = sys.modules[mod]
1005 # m = sys.modules[mod]
1029 # if hasattr(m,'init_ipython'):
1006 # if hasattr(m,'init_ipython'):
1030 # m.init_ipython(self)
1007 # m.init_ipython(self)
1031 #
1008 #
1032 # if hasattr(m,'ipython_firstrun'):
1009 # if hasattr(m,'ipython_firstrun'):
1033 # already_loaded = self.db.get('firstrun_done', set())
1010 # already_loaded = self.db.get('firstrun_done', set())
1034 # if mod not in already_loaded:
1011 # if mod not in already_loaded:
1035 # m.ipython_firstrun(self)
1012 # m.ipython_firstrun(self)
1036 # already_loaded.add(mod)
1013 # already_loaded.add(mod)
1037 # self.db['firstrun_done'] = already_loaded
1014 # self.db['firstrun_done'] = already_loaded
1038 #
1015 #
1039 # self.extensions[mod] = m
1016 # self.extensions[mod] = m
1040 # return m
1017 # return m
1041
1018
1042 def init_user_ns(self):
1019 def init_user_ns(self):
1043 """Initialize all user-visible namespaces to their minimum defaults.
1020 """Initialize all user-visible namespaces to their minimum defaults.
1044
1021
1045 Certain history lists are also initialized here, as they effectively
1022 Certain history lists are also initialized here, as they effectively
1046 act as user namespaces.
1023 act as user namespaces.
1047
1024
1048 Notes
1025 Notes
1049 -----
1026 -----
1050 All data structures here are only filled in, they are NOT reset by this
1027 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
1028 method. If they were not empty before, data will simply be added to
1052 therm.
1029 therm.
1053 """
1030 """
1054 # The user namespace MUST have a pointer to the shell itself.
1031 # The user namespace MUST have a pointer to the shell itself.
1055 self.user_ns[self.name] = self
1032 self.user_ns[self.name] = self
1056
1033
1057 # Store myself as the public api!!!
1034 # Store myself as the public api!!!
1058 self.user_ns['_ip'] = self
1035 self.user_ns['_ip'] = self
1059
1036
1060 # make global variables for user access to the histories
1037 # make global variables for user access to the histories
1061 self.user_ns['_ih'] = self.input_hist
1038 self.user_ns['_ih'] = self.input_hist
1062 self.user_ns['_oh'] = self.output_hist
1039 self.user_ns['_oh'] = self.output_hist
1063 self.user_ns['_dh'] = self.dir_hist
1040 self.user_ns['_dh'] = self.dir_hist
1064
1041
1065 # user aliases to input and output histories
1042 # user aliases to input and output histories
1066 self.user_ns['In'] = self.input_hist
1043 self.user_ns['In'] = self.input_hist
1067 self.user_ns['Out'] = self.output_hist
1044 self.user_ns['Out'] = self.output_hist
1068
1045
1069 self.user_ns['_sh'] = shadowns
1046 self.user_ns['_sh'] = shadowns
1070
1047
1071 # Put 'help' in the user namespace
1048 # Put 'help' in the user namespace
1072 try:
1049 try:
1073 from site import _Helper
1050 from site import _Helper
1074 self.user_ns['help'] = _Helper()
1051 self.user_ns['help'] = _Helper()
1075 except ImportError:
1052 except ImportError:
1076 warn('help() not available - check site.py')
1053 warn('help() not available - check site.py')
1077
1054
1078 def add_builtin(self, key, value):
1079 """Add a builtin and save the original."""
1080 orig = __builtin__.__dict__.get(key, BuiltinUndefined)
1081 self._orig_builtins[key] = orig
1082 __builtin__.__dict__[key] = value
1083
1084 def remove_builtin(self, key):
1085 """Remove an added builtin and re-set the original."""
1086 try:
1087 orig = self._orig_builtins.pop(key)
1088 except KeyError:
1089 pass
1090 else:
1091 if orig is BuiltinUndefined:
1092 del __builtin__.__dict__[key]
1093 else:
1094 __builtin__.__dict__[key] = orig
1095
1096 def add_builtins(self):
1097 """Store ipython references into the __builtin__ namespace.
1098
1099 We strive to modify the __builtin__ namespace as little as possible.
1100 """
1101 if not self._builtins_added:
1102 self.add_builtin('exit', Quitter(self,'exit'))
1103 self.add_builtin('quit', Quitter(self,'quit'))
1104
1105 # Recursive reload function
1106 try:
1107 from IPython.lib import deepreload
1108 if self.deep_reload:
1109 self.add_builtin('reload', deepreload.reload)
1110 else:
1111 self.add_builtin('dreload', deepreload.reload)
1112 del deepreload
1113 except ImportError:
1114 pass
1115
1116 # Keep in the builtins a flag for when IPython is active. We set it
1117 # with setdefault so that multiple nested IPythons don't clobber one
1118 # another. Each will increase its value by one upon being activated,
1119 # which also gives us a way to determine the nesting level.
1120 __builtin__.__dict__.setdefault('__IPYTHON__active',0)
1121 self._builtins_added = True
1122
1123 def remove_builtins(self):
1124 """Remove any builtins which might have been added by add_builtins, or
1125 restore overwritten ones to their previous values."""
1126 if self._builtins_added:
1127 for key in self._orig_builtins.keys():
1128 self.remove_builtin(key)
1129 self._orig_builtins.clear()
1130 self._builtins_added = False
1131
1132 def save_sys_module_state(self):
1055 def save_sys_module_state(self):
1133 """Save the state of hooks in the sys module.
1056 """Save the state of hooks in the sys module.
1134
1057
1135 This has to be called after self.user_ns is created.
1058 This has to be called after self.user_ns is created.
1136 """
1059 """
1137 self._orig_sys_module_state = {}
1060 self._orig_sys_module_state = {}
1138 self._orig_sys_module_state['stdin'] = sys.stdin
1061 self._orig_sys_module_state['stdin'] = sys.stdin
1139 self._orig_sys_module_state['stdout'] = sys.stdout
1062 self._orig_sys_module_state['stdout'] = sys.stdout
1140 self._orig_sys_module_state['stderr'] = sys.stderr
1063 self._orig_sys_module_state['stderr'] = sys.stderr
1141 self._orig_sys_module_state['displayhook'] = sys.displayhook
1064 self._orig_sys_module_state['displayhook'] = sys.displayhook
1142 self._orig_sys_module_state['excepthook'] = sys.excepthook
1065 self._orig_sys_module_state['excepthook'] = sys.excepthook
1143 try:
1066 try:
1144 self._orig_sys_modules_main_name = self.user_ns['__name__']
1067 self._orig_sys_modules_main_name = self.user_ns['__name__']
1145 except KeyError:
1068 except KeyError:
1146 pass
1069 pass
1147
1070
1148 def restore_sys_module_state(self):
1071 def restore_sys_module_state(self):
1149 """Restore the state of the sys module."""
1072 """Restore the state of the sys module."""
1150 try:
1073 try:
1151 for k, v in self._orig_sys_module_state.items():
1074 for k, v in self._orig_sys_module_state.items():
1152 setattr(sys, k, v)
1075 setattr(sys, k, v)
1153 except AttributeError:
1076 except AttributeError:
1154 pass
1077 pass
1155 try:
1078 try:
1156 delattr(sys, 'ipcompleter')
1079 delattr(sys, 'ipcompleter')
1157 except AttributeError:
1080 except AttributeError:
1158 pass
1081 pass
1159 # Reset what what done in self.init_sys_modules
1082 # Reset what what done in self.init_sys_modules
1160 try:
1083 try:
1161 sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name
1084 sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name
1162 except (AttributeError, KeyError):
1085 except (AttributeError, KeyError):
1163 pass
1086 pass
1164
1087
1165 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
1088 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
1166 """set_hook(name,hook) -> sets an internal IPython hook.
1089 """set_hook(name,hook) -> sets an internal IPython hook.
1167
1090
1168 IPython exposes some of its internal API as user-modifiable hooks. By
1091 IPython exposes some of its internal API as user-modifiable hooks. By
1169 adding your function to one of these hooks, you can modify IPython's
1092 adding your function to one of these hooks, you can modify IPython's
1170 behavior to call at runtime your own routines."""
1093 behavior to call at runtime your own routines."""
1171
1094
1172 # At some point in the future, this should validate the hook before it
1095 # At some point in the future, this should validate the hook before it
1173 # accepts it. Probably at least check that the hook takes the number
1096 # accepts it. Probably at least check that the hook takes the number
1174 # of args it's supposed to.
1097 # of args it's supposed to.
1175
1098
1176 f = new.instancemethod(hook,self,self.__class__)
1099 f = new.instancemethod(hook,self,self.__class__)
1177
1100
1178 # check if the hook is for strdispatcher first
1101 # check if the hook is for strdispatcher first
1179 if str_key is not None:
1102 if str_key is not None:
1180 sdp = self.strdispatchers.get(name, StrDispatch())
1103 sdp = self.strdispatchers.get(name, StrDispatch())
1181 sdp.add_s(str_key, f, priority )
1104 sdp.add_s(str_key, f, priority )
1182 self.strdispatchers[name] = sdp
1105 self.strdispatchers[name] = sdp
1183 return
1106 return
1184 if re_key is not None:
1107 if re_key is not None:
1185 sdp = self.strdispatchers.get(name, StrDispatch())
1108 sdp = self.strdispatchers.get(name, StrDispatch())
1186 sdp.add_re(re.compile(re_key), f, priority )
1109 sdp.add_re(re.compile(re_key), f, priority )
1187 self.strdispatchers[name] = sdp
1110 self.strdispatchers[name] = sdp
1188 return
1111 return
1189
1112
1190 dp = getattr(self.hooks, name, None)
1113 dp = getattr(self.hooks, name, None)
1191 if name not in IPython.core.hooks.__all__:
1114 if name not in IPython.core.hooks.__all__:
1192 print "Warning! Hook '%s' is not one of %s" % (name, IPython.core.hooks.__all__ )
1115 print "Warning! Hook '%s' is not one of %s" % (name, IPython.core.hooks.__all__ )
1193 if not dp:
1116 if not dp:
1194 dp = IPython.core.hooks.CommandChainDispatcher()
1117 dp = IPython.core.hooks.CommandChainDispatcher()
1195
1118
1196 try:
1119 try:
1197 dp.add(f,priority)
1120 dp.add(f,priority)
1198 except AttributeError:
1121 except AttributeError:
1199 # it was not commandchain, plain old func - replace
1122 # it was not commandchain, plain old func - replace
1200 dp = f
1123 dp = f
1201
1124
1202 setattr(self.hooks,name, dp)
1125 setattr(self.hooks,name, dp)
1203
1126
1204 def set_crash_handler(self, crashHandler):
1127 def set_crash_handler(self, crashHandler):
1205 """Set the IPython crash handler.
1128 """Set the IPython crash handler.
1206
1129
1207 This must be a callable with a signature suitable for use as
1130 This must be a callable with a signature suitable for use as
1208 sys.excepthook."""
1131 sys.excepthook."""
1209
1132
1210 # Install the given crash handler as the Python exception hook
1133 # Install the given crash handler as the Python exception hook
1211 sys.excepthook = crashHandler
1134 sys.excepthook = crashHandler
1212
1135
1213 # The instance will store a pointer to this, so that runtime code
1136 # The instance will store a pointer to this, so that runtime code
1214 # (such as magics) can access it. This is because during the
1137 # (such as magics) can access it. This is because during the
1215 # read-eval loop, it gets temporarily overwritten (to deal with GUI
1138 # read-eval loop, it gets temporarily overwritten (to deal with GUI
1216 # frameworks).
1139 # frameworks).
1217 self.sys_excepthook = sys.excepthook
1140 self.sys_excepthook = sys.excepthook
1218
1141
1219 def set_custom_exc(self,exc_tuple,handler):
1142 def set_custom_exc(self,exc_tuple,handler):
1220 """set_custom_exc(exc_tuple,handler)
1143 """set_custom_exc(exc_tuple,handler)
1221
1144
1222 Set a custom exception handler, which will be called if any of the
1145 Set a custom exception handler, which will be called if any of the
1223 exceptions in exc_tuple occur in the mainloop (specifically, in the
1146 exceptions in exc_tuple occur in the mainloop (specifically, in the
1224 runcode() method.
1147 runcode() method.
1225
1148
1226 Inputs:
1149 Inputs:
1227
1150
1228 - exc_tuple: a *tuple* of valid exceptions to call the defined
1151 - exc_tuple: a *tuple* of valid exceptions to call the defined
1229 handler for. It is very important that you use a tuple, and NOT A
1152 handler for. It is very important that you use a tuple, and NOT A
1230 LIST here, because of the way Python's except statement works. If
1153 LIST here, because of the way Python's except statement works. If
1231 you only want to trap a single exception, use a singleton tuple:
1154 you only want to trap a single exception, use a singleton tuple:
1232
1155
1233 exc_tuple == (MyCustomException,)
1156 exc_tuple == (MyCustomException,)
1234
1157
1235 - handler: this must be defined as a function with the following
1158 - handler: this must be defined as a function with the following
1236 basic interface: def my_handler(self,etype,value,tb).
1159 basic interface: def my_handler(self,etype,value,tb).
1237
1160
1238 This will be made into an instance method (via new.instancemethod)
1161 This will be made into an instance method (via new.instancemethod)
1239 of IPython itself, and it will be called if any of the exceptions
1162 of IPython itself, and it will be called if any of the exceptions
1240 listed in the exc_tuple are caught. If the handler is None, an
1163 listed in the exc_tuple are caught. If the handler is None, an
1241 internal basic one is used, which just prints basic info.
1164 internal basic one is used, which just prints basic info.
1242
1165
1243 WARNING: by putting in your own exception handler into IPython's main
1166 WARNING: by putting in your own exception handler into IPython's main
1244 execution loop, you run a very good chance of nasty crashes. This
1167 execution loop, you run a very good chance of nasty crashes. This
1245 facility should only be used if you really know what you are doing."""
1168 facility should only be used if you really know what you are doing."""
1246
1169
1247 assert type(exc_tuple)==type(()) , \
1170 assert type(exc_tuple)==type(()) , \
1248 "The custom exceptions must be given AS A TUPLE."
1171 "The custom exceptions must be given AS A TUPLE."
1249
1172
1250 def dummy_handler(self,etype,value,tb):
1173 def dummy_handler(self,etype,value,tb):
1251 print '*** Simple custom exception handler ***'
1174 print '*** Simple custom exception handler ***'
1252 print 'Exception type :',etype
1175 print 'Exception type :',etype
1253 print 'Exception value:',value
1176 print 'Exception value:',value
1254 print 'Traceback :',tb
1177 print 'Traceback :',tb
1255 print 'Source code :','\n'.join(self.buffer)
1178 print 'Source code :','\n'.join(self.buffer)
1256
1179
1257 if handler is None: handler = dummy_handler
1180 if handler is None: handler = dummy_handler
1258
1181
1259 self.CustomTB = new.instancemethod(handler,self,self.__class__)
1182 self.CustomTB = new.instancemethod(handler,self,self.__class__)
1260 self.custom_exceptions = exc_tuple
1183 self.custom_exceptions = exc_tuple
1261
1184
1262 def set_custom_completer(self,completer,pos=0):
1185 def set_custom_completer(self,completer,pos=0):
1263 """set_custom_completer(completer,pos=0)
1186 """set_custom_completer(completer,pos=0)
1264
1187
1265 Adds a new custom completer function.
1188 Adds a new custom completer function.
1266
1189
1267 The position argument (defaults to 0) is the index in the completers
1190 The position argument (defaults to 0) is the index in the completers
1268 list where you want the completer to be inserted."""
1191 list where you want the completer to be inserted."""
1269
1192
1270 newcomp = new.instancemethod(completer,self.Completer,
1193 newcomp = new.instancemethod(completer,self.Completer,
1271 self.Completer.__class__)
1194 self.Completer.__class__)
1272 self.Completer.matchers.insert(pos,newcomp)
1195 self.Completer.matchers.insert(pos,newcomp)
1273
1196
1274 def set_completer(self):
1197 def set_completer(self):
1275 """reset readline's completer to be our own."""
1198 """reset readline's completer to be our own."""
1276 self.readline.set_completer(self.Completer.complete)
1199 self.readline.set_completer(self.Completer.complete)
1277
1200
1278 def _get_call_pdb(self):
1201 def _get_call_pdb(self):
1279 return self._call_pdb
1202 return self._call_pdb
1280
1203
1281 def _set_call_pdb(self,val):
1204 def _set_call_pdb(self,val):
1282
1205
1283 if val not in (0,1,False,True):
1206 if val not in (0,1,False,True):
1284 raise ValueError,'new call_pdb value must be boolean'
1207 raise ValueError,'new call_pdb value must be boolean'
1285
1208
1286 # store value in instance
1209 # store value in instance
1287 self._call_pdb = val
1210 self._call_pdb = val
1288
1211
1289 # notify the actual exception handlers
1212 # notify the actual exception handlers
1290 self.InteractiveTB.call_pdb = val
1213 self.InteractiveTB.call_pdb = val
1291 if self.isthreaded:
1214 if self.isthreaded:
1292 try:
1215 try:
1293 self.sys_excepthook.call_pdb = val
1216 self.sys_excepthook.call_pdb = val
1294 except:
1217 except:
1295 warn('Failed to activate pdb for threaded exception handler')
1218 warn('Failed to activate pdb for threaded exception handler')
1296
1219
1297 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
1220 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
1298 'Control auto-activation of pdb at exceptions')
1221 'Control auto-activation of pdb at exceptions')
1299
1222
1300 def magic(self,arg_s):
1223 def magic(self,arg_s):
1301 """Call a magic function by name.
1224 """Call a magic function by name.
1302
1225
1303 Input: a string containing the name of the magic function to call and any
1226 Input: a string containing the name of the magic function to call and any
1304 additional arguments to be passed to the magic.
1227 additional arguments to be passed to the magic.
1305
1228
1306 magic('name -opt foo bar') is equivalent to typing at the ipython
1229 magic('name -opt foo bar') is equivalent to typing at the ipython
1307 prompt:
1230 prompt:
1308
1231
1309 In[1]: %name -opt foo bar
1232 In[1]: %name -opt foo bar
1310
1233
1311 To call a magic without arguments, simply use magic('name').
1234 To call a magic without arguments, simply use magic('name').
1312
1235
1313 This provides a proper Python function to call IPython's magics in any
1236 This provides a proper Python function to call IPython's magics in any
1314 valid Python code you can type at the interpreter, including loops and
1237 valid Python code you can type at the interpreter, including loops and
1315 compound statements.
1238 compound statements.
1316 """
1239 """
1317
1240
1318 args = arg_s.split(' ',1)
1241 args = arg_s.split(' ',1)
1319 magic_name = args[0]
1242 magic_name = args[0]
1320 magic_name = magic_name.lstrip(self.ESC_MAGIC)
1243 magic_name = magic_name.lstrip(self.ESC_MAGIC)
1321
1244
1322 try:
1245 try:
1323 magic_args = args[1]
1246 magic_args = args[1]
1324 except IndexError:
1247 except IndexError:
1325 magic_args = ''
1248 magic_args = ''
1326 fn = getattr(self,'magic_'+magic_name,None)
1249 fn = getattr(self,'magic_'+magic_name,None)
1327 if fn is None:
1250 if fn is None:
1328 error("Magic function `%s` not found." % magic_name)
1251 error("Magic function `%s` not found." % magic_name)
1329 else:
1252 else:
1330 magic_args = self.var_expand(magic_args,1)
1253 magic_args = self.var_expand(magic_args,1)
1331 return fn(magic_args)
1254 with self.builtin_trap:
1255 result = fn(magic_args)
1256 return result
1332
1257
1333 def define_magic(self, magicname, func):
1258 def define_magic(self, magicname, func):
1334 """Expose own function as magic function for ipython
1259 """Expose own function as magic function for ipython
1335
1260
1336 def foo_impl(self,parameter_s=''):
1261 def foo_impl(self,parameter_s=''):
1337 'My very own magic!. (Use docstrings, IPython reads them).'
1262 'My very own magic!. (Use docstrings, IPython reads them).'
1338 print 'Magic function. Passed parameter is between < >:'
1263 print 'Magic function. Passed parameter is between < >:'
1339 print '<%s>' % parameter_s
1264 print '<%s>' % parameter_s
1340 print 'The self object is:',self
1265 print 'The self object is:',self
1341
1266
1342 self.define_magic('foo',foo_impl)
1267 self.define_magic('foo',foo_impl)
1343 """
1268 """
1344
1269
1345 import new
1270 import new
1346 im = new.instancemethod(func,self, self.__class__)
1271 im = new.instancemethod(func,self, self.__class__)
1347 old = getattr(self, "magic_" + magicname, None)
1272 old = getattr(self, "magic_" + magicname, None)
1348 setattr(self, "magic_" + magicname, im)
1273 setattr(self, "magic_" + magicname, im)
1349 return old
1274 return old
1350
1275
1351 def define_macro(self, name, themacro):
1276 def define_macro(self, name, themacro):
1352 """Define a new macro
1277 """Define a new macro
1353
1278
1354 Parameters
1279 Parameters
1355 ----------
1280 ----------
1356 name : str
1281 name : str
1357 The name of the macro.
1282 The name of the macro.
1358 themacro : str or Macro
1283 themacro : str or Macro
1359 The action to do upon invoking the macro. If a string, a new
1284 The action to do upon invoking the macro. If a string, a new
1360 Macro object is created by passing the string to it.
1285 Macro object is created by passing the string to it.
1361 """
1286 """
1362
1287
1363 from IPython.core import macro
1288 from IPython.core import macro
1364
1289
1365 if isinstance(themacro, basestring):
1290 if isinstance(themacro, basestring):
1366 themacro = macro.Macro(themacro)
1291 themacro = macro.Macro(themacro)
1367 if not isinstance(themacro, macro.Macro):
1292 if not isinstance(themacro, macro.Macro):
1368 raise ValueError('A macro must be a string or a Macro instance.')
1293 raise ValueError('A macro must be a string or a Macro instance.')
1369 self.user_ns[name] = themacro
1294 self.user_ns[name] = themacro
1370
1295
1371 def define_alias(self, name, cmd):
1296 def define_alias(self, name, cmd):
1372 """ Define a new alias."""
1297 """ Define a new alias."""
1373
1298
1374 if callable(cmd):
1299 if callable(cmd):
1375 self.alias_table[name] = cmd
1300 self.alias_table[name] = cmd
1376 from IPython.core import shadowns
1301 from IPython.core import shadowns
1377 setattr(shadowns, name, cmd)
1302 setattr(shadowns, name, cmd)
1378 return
1303 return
1379
1304
1380 if isinstance(cmd, basestring):
1305 if isinstance(cmd, basestring):
1381 nargs = cmd.count('%s')
1306 nargs = cmd.count('%s')
1382 if nargs>0 and cmd.find('%l')>=0:
1307 if nargs>0 and cmd.find('%l')>=0:
1383 raise Exception('The %s and %l specifiers are mutually '
1308 raise Exception('The %s and %l specifiers are mutually '
1384 'exclusive in alias definitions.')
1309 'exclusive in alias definitions.')
1385
1310
1386 self.alias_table[name] = (nargs,cmd)
1311 self.alias_table[name] = (nargs,cmd)
1387 return
1312 return
1388
1313
1389 self.alias_table[name] = cmd
1314 self.alias_table[name] = cmd
1390
1315
1391 def ipalias(self,arg_s):
1316 def ipalias(self,arg_s):
1392 """Call an alias by name.
1317 """Call an alias by name.
1393
1318
1394 Input: a string containing the name of the alias to call and any
1319 Input: a string containing the name of the alias to call and any
1395 additional arguments to be passed to the magic.
1320 additional arguments to be passed to the magic.
1396
1321
1397 ipalias('name -opt foo bar') is equivalent to typing at the ipython
1322 ipalias('name -opt foo bar') is equivalent to typing at the ipython
1398 prompt:
1323 prompt:
1399
1324
1400 In[1]: name -opt foo bar
1325 In[1]: name -opt foo bar
1401
1326
1402 To call an alias without arguments, simply use ipalias('name').
1327 To call an alias without arguments, simply use ipalias('name').
1403
1328
1404 This provides a proper Python function to call IPython's aliases in any
1329 This provides a proper Python function to call IPython's aliases in any
1405 valid Python code you can type at the interpreter, including loops and
1330 valid Python code you can type at the interpreter, including loops and
1406 compound statements. It is added by IPython to the Python builtin
1331 compound statements. It is added by IPython to the Python builtin
1407 namespace upon initialization."""
1332 namespace upon initialization."""
1408
1333
1409 args = arg_s.split(' ',1)
1334 args = arg_s.split(' ',1)
1410 alias_name = args[0]
1335 alias_name = args[0]
1411 try:
1336 try:
1412 alias_args = args[1]
1337 alias_args = args[1]
1413 except IndexError:
1338 except IndexError:
1414 alias_args = ''
1339 alias_args = ''
1415 if alias_name in self.alias_table:
1340 if alias_name in self.alias_table:
1416 self.call_alias(alias_name,alias_args)
1341 self.call_alias(alias_name,alias_args)
1417 else:
1342 else:
1418 error("Alias `%s` not found." % alias_name)
1343 error("Alias `%s` not found." % alias_name)
1419
1344
1420 def system(self, cmd):
1345 def system(self, cmd):
1421 """Make a system call, using IPython."""
1346 """Make a system call, using IPython."""
1422 return self.hooks.shell_hook(self.var_expand(cmd, depth=2))
1347 return self.hooks.shell_hook(self.var_expand(cmd, depth=2))
1423
1348
1424 def ex(self, cmd):
1349 def ex(self, cmd):
1425 """Execute a normal python statement in user namespace."""
1350 """Execute a normal python statement in user namespace."""
1426 exec cmd in self.user_global_ns, self.user_ns
1351 with self.builtin_trap:
1352 exec cmd in self.user_global_ns, self.user_ns
1427
1353
1428 def ev(self, expr):
1354 def ev(self, expr):
1429 """Evaluate python expression expr in user namespace.
1355 """Evaluate python expression expr in user namespace.
1430
1356
1431 Returns the result of evaluation
1357 Returns the result of evaluation
1432 """
1358 """
1433 return eval(expr, self.user_global_ns, self.user_ns)
1359 with self.builtin_trap:
1360 result = eval(expr, self.user_global_ns, self.user_ns)
1361 return result
1434
1362
1435 def getoutput(self, cmd):
1363 def getoutput(self, cmd):
1436 return getoutput(self.var_expand(cmd,depth=2),
1364 return getoutput(self.var_expand(cmd,depth=2),
1437 header=self.system_header,
1365 header=self.system_header,
1438 verbose=self.system_verbose)
1366 verbose=self.system_verbose)
1439
1367
1440 def getoutputerror(self, cmd):
1368 def getoutputerror(self, cmd):
1441 return getoutputerror(self.var_expand(cmd,depth=2),
1369 return getoutputerror(self.var_expand(cmd,depth=2),
1442 header=self.system_header,
1370 header=self.system_header,
1443 verbose=self.system_verbose)
1371 verbose=self.system_verbose)
1444
1372
1445 def complete(self, text):
1373 def complete(self, text):
1446 """Return a sorted list of all possible completions on text.
1374 """Return a sorted list of all possible completions on text.
1447
1375
1448 Inputs:
1376 Inputs:
1449
1377
1450 - text: a string of text to be completed on.
1378 - text: a string of text to be completed on.
1451
1379
1452 This is a wrapper around the completion mechanism, similar to what
1380 This is a wrapper around the completion mechanism, similar to what
1453 readline does at the command line when the TAB key is hit. By
1381 readline does at the command line when the TAB key is hit. By
1454 exposing it as a method, it can be used by other non-readline
1382 exposing it as a method, it can be used by other non-readline
1455 environments (such as GUIs) for text completion.
1383 environments (such as GUIs) for text completion.
1456
1384
1457 Simple usage example:
1385 Simple usage example:
1458
1386
1459 In [7]: x = 'hello'
1387 In [7]: x = 'hello'
1460
1388
1461 In [8]: x
1389 In [8]: x
1462 Out[8]: 'hello'
1390 Out[8]: 'hello'
1463
1391
1464 In [9]: print x
1392 In [9]: print x
1465 hello
1393 hello
1466
1394
1467 In [10]: _ip.complete('x.l')
1395 In [10]: _ip.complete('x.l')
1468 Out[10]: ['x.ljust', 'x.lower', 'x.lstrip']
1396 Out[10]: ['x.ljust', 'x.lower', 'x.lstrip']
1469 """
1397 """
1470
1398
1471 complete = self.Completer.complete
1399 # Inject names into __builtin__ so we can complete on the added names.
1472 state = 0
1400 with self.builtin_trap:
1473 # use a dict so we get unique keys, since ipyhton's multiple
1401 complete = self.Completer.complete
1474 # completers can return duplicates. When we make 2.4 a requirement,
1402 state = 0
1475 # start using sets instead, which are faster.
1403 # use a dict so we get unique keys, since ipyhton's multiple
1476 comps = {}
1404 # completers can return duplicates. When we make 2.4 a requirement,
1477 while True:
1405 # start using sets instead, which are faster.
1478 newcomp = complete(text,state,line_buffer=text)
1406 comps = {}
1479 if newcomp is None:
1407 while True:
1480 break
1408 newcomp = complete(text,state,line_buffer=text)
1481 comps[newcomp] = 1
1409 if newcomp is None:
1482 state += 1
1410 break
1483 outcomps = comps.keys()
1411 comps[newcomp] = 1
1484 outcomps.sort()
1412 state += 1
1485 #print "T:",text,"OC:",outcomps # dbg
1413 outcomps = comps.keys()
1486 #print "vars:",self.user_ns.keys()
1414 outcomps.sort()
1415 #print "T:",text,"OC:",outcomps # dbg
1416 #print "vars:",self.user_ns.keys()
1487 return outcomps
1417 return outcomps
1488
1418
1489 def set_completer_frame(self, frame=None):
1419 def set_completer_frame(self, frame=None):
1490 if frame:
1420 if frame:
1491 self.Completer.namespace = frame.f_locals
1421 self.Completer.namespace = frame.f_locals
1492 self.Completer.global_namespace = frame.f_globals
1422 self.Completer.global_namespace = frame.f_globals
1493 else:
1423 else:
1494 self.Completer.namespace = self.user_ns
1424 self.Completer.namespace = self.user_ns
1495 self.Completer.global_namespace = self.user_global_ns
1425 self.Completer.global_namespace = self.user_global_ns
1496
1426
1497 def init_auto_alias(self):
1427 def init_auto_alias(self):
1498 """Define some aliases automatically.
1428 """Define some aliases automatically.
1499
1429
1500 These are ALL parameter-less aliases"""
1430 These are ALL parameter-less aliases"""
1501
1431
1502 for alias,cmd in self.auto_alias:
1432 for alias,cmd in self.auto_alias:
1503 self.define_alias(alias,cmd)
1433 self.define_alias(alias,cmd)
1504
1434
1505 def alias_table_validate(self,verbose=0):
1435 def alias_table_validate(self,verbose=0):
1506 """Update information about the alias table.
1436 """Update information about the alias table.
1507
1437
1508 In particular, make sure no Python keywords/builtins are in it."""
1438 In particular, make sure no Python keywords/builtins are in it."""
1509
1439
1510 no_alias = self.no_alias
1440 no_alias = self.no_alias
1511 for k in self.alias_table.keys():
1441 for k in self.alias_table.keys():
1512 if k in no_alias:
1442 if k in no_alias:
1513 del self.alias_table[k]
1443 del self.alias_table[k]
1514 if verbose:
1444 if verbose:
1515 print ("Deleting alias <%s>, it's a Python "
1445 print ("Deleting alias <%s>, it's a Python "
1516 "keyword or builtin." % k)
1446 "keyword or builtin." % k)
1517
1447
1518 def set_next_input(self, s):
1448 def set_next_input(self, s):
1519 """ Sets the 'default' input string for the next command line.
1449 """ Sets the 'default' input string for the next command line.
1520
1450
1521 Requires readline.
1451 Requires readline.
1522
1452
1523 Example:
1453 Example:
1524
1454
1525 [D:\ipython]|1> _ip.set_next_input("Hello Word")
1455 [D:\ipython]|1> _ip.set_next_input("Hello Word")
1526 [D:\ipython]|2> Hello Word_ # cursor is here
1456 [D:\ipython]|2> Hello Word_ # cursor is here
1527 """
1457 """
1528
1458
1529 self.rl_next_input = s
1459 self.rl_next_input = s
1530
1460
1531 def set_autoindent(self,value=None):
1461 def set_autoindent(self,value=None):
1532 """Set the autoindent flag, checking for readline support.
1462 """Set the autoindent flag, checking for readline support.
1533
1463
1534 If called with no arguments, it acts as a toggle."""
1464 If called with no arguments, it acts as a toggle."""
1535
1465
1536 if not self.has_readline:
1466 if not self.has_readline:
1537 if os.name == 'posix':
1467 if os.name == 'posix':
1538 warn("The auto-indent feature requires the readline library")
1468 warn("The auto-indent feature requires the readline library")
1539 self.autoindent = 0
1469 self.autoindent = 0
1540 return
1470 return
1541 if value is None:
1471 if value is None:
1542 self.autoindent = not self.autoindent
1472 self.autoindent = not self.autoindent
1543 else:
1473 else:
1544 self.autoindent = value
1474 self.autoindent = value
1545
1475
1546 def atexit_operations(self):
1476 def atexit_operations(self):
1547 """This will be executed at the time of exit.
1477 """This will be executed at the time of exit.
1548
1478
1549 Saving of persistent data should be performed here. """
1479 Saving of persistent data should be performed here. """
1550
1480
1551 #print '*** IPython exit cleanup ***' # dbg
1481 #print '*** IPython exit cleanup ***' # dbg
1552 # input history
1482 # input history
1553 self.savehist()
1483 self.savehist()
1554
1484
1555 # Cleanup all tempfiles left around
1485 # Cleanup all tempfiles left around
1556 for tfile in self.tempfiles:
1486 for tfile in self.tempfiles:
1557 try:
1487 try:
1558 os.unlink(tfile)
1488 os.unlink(tfile)
1559 except OSError:
1489 except OSError:
1560 pass
1490 pass
1561
1491
1562 # Clear all user namespaces to release all references cleanly.
1492 # Clear all user namespaces to release all references cleanly.
1563 self.reset()
1493 self.reset()
1564
1494
1565 # Run user hooks
1495 # Run user hooks
1566 self.hooks.shutdown_hook()
1496 self.hooks.shutdown_hook()
1567
1497
1568 def reset(self):
1498 def reset(self):
1569 """Clear all internal namespaces.
1499 """Clear all internal namespaces.
1570
1500
1571 Note that this is much more aggressive than %reset, since it clears
1501 Note that this is much more aggressive than %reset, since it clears
1572 fully all namespaces, as well as all input/output lists.
1502 fully all namespaces, as well as all input/output lists.
1573 """
1503 """
1574 for ns in self.ns_refs_table:
1504 for ns in self.ns_refs_table:
1575 ns.clear()
1505 ns.clear()
1576
1506
1577 # Clear input and output histories
1507 # Clear input and output histories
1578 self.input_hist[:] = []
1508 self.input_hist[:] = []
1579 self.input_hist_raw[:] = []
1509 self.input_hist_raw[:] = []
1580 self.output_hist.clear()
1510 self.output_hist.clear()
1581 # Restore the user namespaces to minimal usability
1511 # Restore the user namespaces to minimal usability
1582 self.init_user_ns()
1512 self.init_user_ns()
1583
1513
1584 def savehist(self):
1514 def savehist(self):
1585 """Save input history to a file (via readline library)."""
1515 """Save input history to a file (via readline library)."""
1586
1516
1587 if not self.has_readline:
1517 if not self.has_readline:
1588 return
1518 return
1589
1519
1590 try:
1520 try:
1591 self.readline.write_history_file(self.histfile)
1521 self.readline.write_history_file(self.histfile)
1592 except:
1522 except:
1593 print 'Unable to save IPython command history to file: ' + \
1523 print 'Unable to save IPython command history to file: ' + \
1594 `self.histfile`
1524 `self.histfile`
1595
1525
1596 def reloadhist(self):
1526 def reloadhist(self):
1597 """Reload the input history from disk file."""
1527 """Reload the input history from disk file."""
1598
1528
1599 if self.has_readline:
1529 if self.has_readline:
1600 try:
1530 try:
1601 self.readline.clear_history()
1531 self.readline.clear_history()
1602 self.readline.read_history_file(self.shell.histfile)
1532 self.readline.read_history_file(self.shell.histfile)
1603 except AttributeError:
1533 except AttributeError:
1604 pass
1534 pass
1605
1535
1606
1536
1607 def history_saving_wrapper(self, func):
1537 def history_saving_wrapper(self, func):
1608 """ Wrap func for readline history saving
1538 """ Wrap func for readline history saving
1609
1539
1610 Convert func into callable that saves & restores
1540 Convert func into callable that saves & restores
1611 history around the call """
1541 history around the call """
1612
1542
1613 if not self.has_readline:
1543 if not self.has_readline:
1614 return func
1544 return func
1615
1545
1616 def wrapper():
1546 def wrapper():
1617 self.savehist()
1547 self.savehist()
1618 try:
1548 try:
1619 func()
1549 func()
1620 finally:
1550 finally:
1621 readline.read_history_file(self.histfile)
1551 readline.read_history_file(self.histfile)
1622 return wrapper
1552 return wrapper
1623
1553
1624 def pre_readline(self):
1554 def pre_readline(self):
1625 """readline hook to be used at the start of each line.
1555 """readline hook to be used at the start of each line.
1626
1556
1627 Currently it handles auto-indent only."""
1557 Currently it handles auto-indent only."""
1628
1558
1629 #debugx('self.indent_current_nsp','pre_readline:')
1559 #debugx('self.indent_current_nsp','pre_readline:')
1630
1560
1631 if self.rl_do_indent:
1561 if self.rl_do_indent:
1632 self.readline.insert_text(self.indent_current_str())
1562 self.readline.insert_text(self.indent_current_str())
1633 if self.rl_next_input is not None:
1563 if self.rl_next_input is not None:
1634 self.readline.insert_text(self.rl_next_input)
1564 self.readline.insert_text(self.rl_next_input)
1635 self.rl_next_input = None
1565 self.rl_next_input = None
1636
1566
1637 def ask_yes_no(self,prompt,default=True):
1567 def ask_yes_no(self,prompt,default=True):
1638 if self.quiet:
1568 if self.quiet:
1639 return True
1569 return True
1640 return ask_yes_no(prompt,default)
1570 return ask_yes_no(prompt,default)
1641
1571
1642 def new_main_mod(self,ns=None):
1572 def new_main_mod(self,ns=None):
1643 """Return a new 'main' module object for user code execution.
1573 """Return a new 'main' module object for user code execution.
1644 """
1574 """
1645 main_mod = self._user_main_module
1575 main_mod = self._user_main_module
1646 init_fakemod_dict(main_mod,ns)
1576 init_fakemod_dict(main_mod,ns)
1647 return main_mod
1577 return main_mod
1648
1578
1649 def cache_main_mod(self,ns,fname):
1579 def cache_main_mod(self,ns,fname):
1650 """Cache a main module's namespace.
1580 """Cache a main module's namespace.
1651
1581
1652 When scripts are executed via %run, we must keep a reference to the
1582 When scripts are executed via %run, we must keep a reference to the
1653 namespace of their __main__ module (a FakeModule instance) around so
1583 namespace of their __main__ module (a FakeModule instance) around so
1654 that Python doesn't clear it, rendering objects defined therein
1584 that Python doesn't clear it, rendering objects defined therein
1655 useless.
1585 useless.
1656
1586
1657 This method keeps said reference in a private dict, keyed by the
1587 This method keeps said reference in a private dict, keyed by the
1658 absolute path of the module object (which corresponds to the script
1588 absolute path of the module object (which corresponds to the script
1659 path). This way, for multiple executions of the same script we only
1589 path). This way, for multiple executions of the same script we only
1660 keep one copy of the namespace (the last one), thus preventing memory
1590 keep one copy of the namespace (the last one), thus preventing memory
1661 leaks from old references while allowing the objects from the last
1591 leaks from old references while allowing the objects from the last
1662 execution to be accessible.
1592 execution to be accessible.
1663
1593
1664 Note: we can not allow the actual FakeModule instances to be deleted,
1594 Note: we can not allow the actual FakeModule instances to be deleted,
1665 because of how Python tears down modules (it hard-sets all their
1595 because of how Python tears down modules (it hard-sets all their
1666 references to None without regard for reference counts). This method
1596 references to None without regard for reference counts). This method
1667 must therefore make a *copy* of the given namespace, to allow the
1597 must therefore make a *copy* of the given namespace, to allow the
1668 original module's __dict__ to be cleared and reused.
1598 original module's __dict__ to be cleared and reused.
1669
1599
1670
1600
1671 Parameters
1601 Parameters
1672 ----------
1602 ----------
1673 ns : a namespace (a dict, typically)
1603 ns : a namespace (a dict, typically)
1674
1604
1675 fname : str
1605 fname : str
1676 Filename associated with the namespace.
1606 Filename associated with the namespace.
1677
1607
1678 Examples
1608 Examples
1679 --------
1609 --------
1680
1610
1681 In [10]: import IPython
1611 In [10]: import IPython
1682
1612
1683 In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
1613 In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
1684
1614
1685 In [12]: IPython.__file__ in _ip._main_ns_cache
1615 In [12]: IPython.__file__ in _ip._main_ns_cache
1686 Out[12]: True
1616 Out[12]: True
1687 """
1617 """
1688 self._main_ns_cache[os.path.abspath(fname)] = ns.copy()
1618 self._main_ns_cache[os.path.abspath(fname)] = ns.copy()
1689
1619
1690 def clear_main_mod_cache(self):
1620 def clear_main_mod_cache(self):
1691 """Clear the cache of main modules.
1621 """Clear the cache of main modules.
1692
1622
1693 Mainly for use by utilities like %reset.
1623 Mainly for use by utilities like %reset.
1694
1624
1695 Examples
1625 Examples
1696 --------
1626 --------
1697
1627
1698 In [15]: import IPython
1628 In [15]: import IPython
1699
1629
1700 In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
1630 In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
1701
1631
1702 In [17]: len(_ip._main_ns_cache) > 0
1632 In [17]: len(_ip._main_ns_cache) > 0
1703 Out[17]: True
1633 Out[17]: True
1704
1634
1705 In [18]: _ip.clear_main_mod_cache()
1635 In [18]: _ip.clear_main_mod_cache()
1706
1636
1707 In [19]: len(_ip._main_ns_cache) == 0
1637 In [19]: len(_ip._main_ns_cache) == 0
1708 Out[19]: True
1638 Out[19]: True
1709 """
1639 """
1710 self._main_ns_cache.clear()
1640 self._main_ns_cache.clear()
1711
1641
1712 def _should_recompile(self,e):
1642 def _should_recompile(self,e):
1713 """Utility routine for edit_syntax_error"""
1643 """Utility routine for edit_syntax_error"""
1714
1644
1715 if e.filename in ('<ipython console>','<input>','<string>',
1645 if e.filename in ('<ipython console>','<input>','<string>',
1716 '<console>','<BackgroundJob compilation>',
1646 '<console>','<BackgroundJob compilation>',
1717 None):
1647 None):
1718
1648
1719 return False
1649 return False
1720 try:
1650 try:
1721 if (self.autoedit_syntax and
1651 if (self.autoedit_syntax and
1722 not self.ask_yes_no('Return to editor to correct syntax error? '
1652 not self.ask_yes_no('Return to editor to correct syntax error? '
1723 '[Y/n] ','y')):
1653 '[Y/n] ','y')):
1724 return False
1654 return False
1725 except EOFError:
1655 except EOFError:
1726 return False
1656 return False
1727
1657
1728 def int0(x):
1658 def int0(x):
1729 try:
1659 try:
1730 return int(x)
1660 return int(x)
1731 except TypeError:
1661 except TypeError:
1732 return 0
1662 return 0
1733 # always pass integer line and offset values to editor hook
1663 # always pass integer line and offset values to editor hook
1734 try:
1664 try:
1735 self.hooks.fix_error_editor(e.filename,
1665 self.hooks.fix_error_editor(e.filename,
1736 int0(e.lineno),int0(e.offset),e.msg)
1666 int0(e.lineno),int0(e.offset),e.msg)
1737 except TryNext:
1667 except TryNext:
1738 warn('Could not open editor')
1668 warn('Could not open editor')
1739 return False
1669 return False
1740 return True
1670 return True
1741
1671
1742 def edit_syntax_error(self):
1672 def edit_syntax_error(self):
1743 """The bottom half of the syntax error handler called in the main loop.
1673 """The bottom half of the syntax error handler called in the main loop.
1744
1674
1745 Loop until syntax error is fixed or user cancels.
1675 Loop until syntax error is fixed or user cancels.
1746 """
1676 """
1747
1677
1748 while self.SyntaxTB.last_syntax_error:
1678 while self.SyntaxTB.last_syntax_error:
1749 # copy and clear last_syntax_error
1679 # copy and clear last_syntax_error
1750 err = self.SyntaxTB.clear_err_state()
1680 err = self.SyntaxTB.clear_err_state()
1751 if not self._should_recompile(err):
1681 if not self._should_recompile(err):
1752 return
1682 return
1753 try:
1683 try:
1754 # may set last_syntax_error again if a SyntaxError is raised
1684 # may set last_syntax_error again if a SyntaxError is raised
1755 self.safe_execfile(err.filename,self.user_ns)
1685 self.safe_execfile(err.filename,self.user_ns)
1756 except:
1686 except:
1757 self.showtraceback()
1687 self.showtraceback()
1758 else:
1688 else:
1759 try:
1689 try:
1760 f = file(err.filename)
1690 f = file(err.filename)
1761 try:
1691 try:
1762 sys.displayhook(f.read())
1692 sys.displayhook(f.read())
1763 finally:
1693 finally:
1764 f.close()
1694 f.close()
1765 except:
1695 except:
1766 self.showtraceback()
1696 self.showtraceback()
1767
1697
1768 def showsyntaxerror(self, filename=None):
1698 def showsyntaxerror(self, filename=None):
1769 """Display the syntax error that just occurred.
1699 """Display the syntax error that just occurred.
1770
1700
1771 This doesn't display a stack trace because there isn't one.
1701 This doesn't display a stack trace because there isn't one.
1772
1702
1773 If a filename is given, it is stuffed in the exception instead
1703 If a filename is given, it is stuffed in the exception instead
1774 of what was there before (because Python's parser always uses
1704 of what was there before (because Python's parser always uses
1775 "<string>" when reading from a string).
1705 "<string>" when reading from a string).
1776 """
1706 """
1777 etype, value, last_traceback = sys.exc_info()
1707 etype, value, last_traceback = sys.exc_info()
1778
1708
1779 # See note about these variables in showtraceback() below
1709 # See note about these variables in showtraceback() below
1780 sys.last_type = etype
1710 sys.last_type = etype
1781 sys.last_value = value
1711 sys.last_value = value
1782 sys.last_traceback = last_traceback
1712 sys.last_traceback = last_traceback
1783
1713
1784 if filename and etype is SyntaxError:
1714 if filename and etype is SyntaxError:
1785 # Work hard to stuff the correct filename in the exception
1715 # Work hard to stuff the correct filename in the exception
1786 try:
1716 try:
1787 msg, (dummy_filename, lineno, offset, line) = value
1717 msg, (dummy_filename, lineno, offset, line) = value
1788 except:
1718 except:
1789 # Not the format we expect; leave it alone
1719 # Not the format we expect; leave it alone
1790 pass
1720 pass
1791 else:
1721 else:
1792 # Stuff in the right filename
1722 # Stuff in the right filename
1793 try:
1723 try:
1794 # Assume SyntaxError is a class exception
1724 # Assume SyntaxError is a class exception
1795 value = SyntaxError(msg, (filename, lineno, offset, line))
1725 value = SyntaxError(msg, (filename, lineno, offset, line))
1796 except:
1726 except:
1797 # If that failed, assume SyntaxError is a string
1727 # If that failed, assume SyntaxError is a string
1798 value = msg, (filename, lineno, offset, line)
1728 value = msg, (filename, lineno, offset, line)
1799 self.SyntaxTB(etype,value,[])
1729 self.SyntaxTB(etype,value,[])
1800
1730
1801 def debugger(self,force=False):
1731 def debugger(self,force=False):
1802 """Call the pydb/pdb debugger.
1732 """Call the pydb/pdb debugger.
1803
1733
1804 Keywords:
1734 Keywords:
1805
1735
1806 - force(False): by default, this routine checks the instance call_pdb
1736 - force(False): by default, this routine checks the instance call_pdb
1807 flag and does not actually invoke the debugger if the flag is false.
1737 flag and does not actually invoke the debugger if the flag is false.
1808 The 'force' option forces the debugger to activate even if the flag
1738 The 'force' option forces the debugger to activate even if the flag
1809 is false.
1739 is false.
1810 """
1740 """
1811
1741
1812 if not (force or self.call_pdb):
1742 if not (force or self.call_pdb):
1813 return
1743 return
1814
1744
1815 if not hasattr(sys,'last_traceback'):
1745 if not hasattr(sys,'last_traceback'):
1816 error('No traceback has been produced, nothing to debug.')
1746 error('No traceback has been produced, nothing to debug.')
1817 return
1747 return
1818
1748
1819 # use pydb if available
1749 # use pydb if available
1820 if debugger.has_pydb:
1750 if debugger.has_pydb:
1821 from pydb import pm
1751 from pydb import pm
1822 else:
1752 else:
1823 # fallback to our internal debugger
1753 # fallback to our internal debugger
1824 pm = lambda : self.InteractiveTB.debugger(force=True)
1754 pm = lambda : self.InteractiveTB.debugger(force=True)
1825 self.history_saving_wrapper(pm)()
1755 self.history_saving_wrapper(pm)()
1826
1756
1827 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None):
1757 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None):
1828 """Display the exception that just occurred.
1758 """Display the exception that just occurred.
1829
1759
1830 If nothing is known about the exception, this is the method which
1760 If nothing is known about the exception, this is the method which
1831 should be used throughout the code for presenting user tracebacks,
1761 should be used throughout the code for presenting user tracebacks,
1832 rather than directly invoking the InteractiveTB object.
1762 rather than directly invoking the InteractiveTB object.
1833
1763
1834 A specific showsyntaxerror() also exists, but this method can take
1764 A specific showsyntaxerror() also exists, but this method can take
1835 care of calling it if needed, so unless you are explicitly catching a
1765 care of calling it if needed, so unless you are explicitly catching a
1836 SyntaxError exception, don't try to analyze the stack manually and
1766 SyntaxError exception, don't try to analyze the stack manually and
1837 simply call this method."""
1767 simply call this method."""
1838
1768
1839
1769
1840 # Though this won't be called by syntax errors in the input line,
1770 # Though this won't be called by syntax errors in the input line,
1841 # there may be SyntaxError cases whith imported code.
1771 # there may be SyntaxError cases whith imported code.
1842
1772
1843 try:
1773 try:
1844 if exc_tuple is None:
1774 if exc_tuple is None:
1845 etype, value, tb = sys.exc_info()
1775 etype, value, tb = sys.exc_info()
1846 else:
1776 else:
1847 etype, value, tb = exc_tuple
1777 etype, value, tb = exc_tuple
1848
1778
1849 if etype is SyntaxError:
1779 if etype is SyntaxError:
1850 self.showsyntaxerror(filename)
1780 self.showsyntaxerror(filename)
1851 elif etype is UsageError:
1781 elif etype is UsageError:
1852 print "UsageError:", value
1782 print "UsageError:", value
1853 else:
1783 else:
1854 # WARNING: these variables are somewhat deprecated and not
1784 # WARNING: these variables are somewhat deprecated and not
1855 # necessarily safe to use in a threaded environment, but tools
1785 # necessarily safe to use in a threaded environment, but tools
1856 # like pdb depend on their existence, so let's set them. If we
1786 # like pdb depend on their existence, so let's set them. If we
1857 # find problems in the field, we'll need to revisit their use.
1787 # find problems in the field, we'll need to revisit their use.
1858 sys.last_type = etype
1788 sys.last_type = etype
1859 sys.last_value = value
1789 sys.last_value = value
1860 sys.last_traceback = tb
1790 sys.last_traceback = tb
1861
1791
1862 if etype in self.custom_exceptions:
1792 if etype in self.custom_exceptions:
1863 self.CustomTB(etype,value,tb)
1793 self.CustomTB(etype,value,tb)
1864 else:
1794 else:
1865 self.InteractiveTB(etype,value,tb,tb_offset=tb_offset)
1795 self.InteractiveTB(etype,value,tb,tb_offset=tb_offset)
1866 if self.InteractiveTB.call_pdb and self.has_readline:
1796 if self.InteractiveTB.call_pdb and self.has_readline:
1867 # pdb mucks up readline, fix it back
1797 # pdb mucks up readline, fix it back
1868 self.set_completer()
1798 self.set_completer()
1869 except KeyboardInterrupt:
1799 except KeyboardInterrupt:
1870 self.write("\nKeyboardInterrupt\n")
1800 self.write("\nKeyboardInterrupt\n")
1871
1801
1872 def mainloop(self, banner=None):
1802 def mainloop(self, banner=None):
1873 """Start the mainloop.
1803 """Start the mainloop.
1874
1804
1875 If an optional banner argument is given, it will override the
1805 If an optional banner argument is given, it will override the
1876 internally created default banner.
1806 internally created default banner.
1877 """
1807 """
1878 if self.c: # Emulate Python's -c option
1808
1879 self.exec_init_cmd()
1809 with self.builtin_trap:
1810 if self.c: # Emulate Python's -c option
1811 self.exec_init_cmd()
1880
1812
1881 if self.display_banner:
1813 if self.display_banner:
1882 if banner is None:
1814 if banner is None:
1883 banner = self.banner
1815 banner = self.banner
1884
1816
1885 # if you run stuff with -c <cmd>, raw hist is not updated
1817 # if you run stuff with -c <cmd>, raw hist is not updated
1886 # ensure that it's in sync
1818 # ensure that it's in sync
1887 if len(self.input_hist) != len (self.input_hist_raw):
1819 if len(self.input_hist) != len (self.input_hist_raw):
1888 self.input_hist_raw = InputList(self.input_hist)
1820 self.input_hist_raw = InputList(self.input_hist)
1889
1821
1890 while 1:
1822 while 1:
1891 try:
1823 try:
1892 self.interact()
1824 self.interact()
1893 #self.interact_with_readline()
1825 #self.interact_with_readline()
1894 # XXX for testing of a readline-decoupled repl loop, call
1826 # XXX for testing of a readline-decoupled repl loop, call
1895 # interact_with_readline above
1827 # interact_with_readline above
1896 break
1828 break
1897 except KeyboardInterrupt:
1829 except KeyboardInterrupt:
1898 # this should not be necessary, but KeyboardInterrupt
1830 # this should not be necessary, but KeyboardInterrupt
1899 # handling seems rather unpredictable...
1831 # handling seems rather unpredictable...
1900 self.write("\nKeyboardInterrupt in interact()\n")
1832 self.write("\nKeyboardInterrupt in interact()\n")
1901
1833
1902 def exec_init_cmd(self):
1834 def exec_init_cmd(self):
1903 """Execute a command given at the command line.
1835 """Execute a command given at the command line.
1904
1836
1905 This emulates Python's -c option."""
1837 This emulates Python's -c option."""
1906
1838
1907 #sys.argv = ['-c']
1839 #sys.argv = ['-c']
1908 self.push_line(self.prefilter(self.c, False))
1840 self.push_line(self.prefilter(self.c, False))
1909 if not self.interactive:
1841 if not self.interactive:
1910 self.ask_exit()
1842 self.ask_exit()
1911
1843
1912 def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0):
1913 """Embeds IPython into a running python program.
1914
1915 Input:
1916
1917 - header: An optional header message can be specified.
1918
1919 - local_ns, global_ns: working namespaces. If given as None, the
1920 IPython-initialized one is updated with __main__.__dict__, so that
1921 program variables become visible but user-specific configuration
1922 remains possible.
1923
1924 - stack_depth: specifies how many levels in the stack to go to
1925 looking for namespaces (when local_ns and global_ns are None). This
1926 allows an intermediate caller to make sure that this function gets
1927 the namespace from the intended level in the stack. By default (0)
1928 it will get its locals and globals from the immediate caller.
1929
1930 Warning: it's possible to use this in a program which is being run by
1931 IPython itself (via %run), but some funny things will happen (a few
1932 globals get overwritten). In the future this will be cleaned up, as
1933 there is no fundamental reason why it can't work perfectly."""
1934
1935 # Get locals and globals from caller
1936 if local_ns is None or global_ns is None:
1937 call_frame = sys._getframe(stack_depth).f_back
1938
1939 if local_ns is None:
1940 local_ns = call_frame.f_locals
1941 if global_ns is None:
1942 global_ns = call_frame.f_globals
1943
1944 # Update namespaces and fire up interpreter
1945
1946 # The global one is easy, we can just throw it in
1947 self.user_global_ns = global_ns
1948
1949 # but the user/local one is tricky: ipython needs it to store internal
1950 # data, but we also need the locals. We'll copy locals in the user
1951 # one, but will track what got copied so we can delete them at exit.
1952 # This is so that a later embedded call doesn't see locals from a
1953 # previous call (which most likely existed in a separate scope).
1954 local_varnames = local_ns.keys()
1955 self.user_ns.update(local_ns)
1956 #self.user_ns['local_ns'] = local_ns # dbg
1957
1958 # Patch for global embedding to make sure that things don't overwrite
1959 # user globals accidentally. Thanks to Richard <rxe@renre-europe.com>
1960 # FIXME. Test this a bit more carefully (the if.. is new)
1961 if local_ns is None and global_ns is None:
1962 self.user_global_ns.update(__main__.__dict__)
1963
1964 # make sure the tab-completer has the correct frame information, so it
1965 # actually completes using the frame's locals/globals
1966 self.set_completer_frame()
1967
1968 # before activating the interactive mode, we need to make sure that
1969 # all names in the builtin namespace needed by ipython point to
1970 # ourselves, and not to other instances.
1971 self.add_builtins()
1972
1973 self.interact(header)
1974
1975 # now, purge out the user namespace from anything we might have added
1976 # from the caller's local namespace
1977 delvar = self.user_ns.pop
1978 for var in local_varnames:
1979 delvar(var,None)
1980 # and clean builtins we may have overridden
1981 self.remove_builtins()
1982
1983 def interact_prompt(self):
1844 def interact_prompt(self):
1984 """ Print the prompt (in read-eval-print loop)
1845 """ Print the prompt (in read-eval-print loop)
1985
1846
1986 Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
1847 Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
1987 used in standard IPython flow.
1848 used in standard IPython flow.
1988 """
1849 """
1989 if self.more:
1850 if self.more:
1990 try:
1851 try:
1991 prompt = self.hooks.generate_prompt(True)
1852 prompt = self.hooks.generate_prompt(True)
1992 except:
1853 except:
1993 self.showtraceback()
1854 self.showtraceback()
1994 if self.autoindent:
1855 if self.autoindent:
1995 self.rl_do_indent = True
1856 self.rl_do_indent = True
1996
1857
1997 else:
1858 else:
1998 try:
1859 try:
1999 prompt = self.hooks.generate_prompt(False)
1860 prompt = self.hooks.generate_prompt(False)
2000 except:
1861 except:
2001 self.showtraceback()
1862 self.showtraceback()
2002 self.write(prompt)
1863 self.write(prompt)
2003
1864
2004 def interact_handle_input(self,line):
1865 def interact_handle_input(self,line):
2005 """ Handle the input line (in read-eval-print loop)
1866 """ Handle the input line (in read-eval-print loop)
2006
1867
2007 Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
1868 Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
2008 used in standard IPython flow.
1869 used in standard IPython flow.
2009 """
1870 """
2010 if line.lstrip() == line:
1871 if line.lstrip() == line:
2011 self.shadowhist.add(line.strip())
1872 self.shadowhist.add(line.strip())
2012 lineout = self.prefilter(line,self.more)
1873 lineout = self.prefilter(line,self.more)
2013
1874
2014 if line.strip():
1875 if line.strip():
2015 if self.more:
1876 if self.more:
2016 self.input_hist_raw[-1] += '%s\n' % line
1877 self.input_hist_raw[-1] += '%s\n' % line
2017 else:
1878 else:
2018 self.input_hist_raw.append('%s\n' % line)
1879 self.input_hist_raw.append('%s\n' % line)
2019
1880
2020
1881
2021 self.more = self.push_line(lineout)
1882 self.more = self.push_line(lineout)
2022 if (self.SyntaxTB.last_syntax_error and
1883 if (self.SyntaxTB.last_syntax_error and
2023 self.autoedit_syntax):
1884 self.autoedit_syntax):
2024 self.edit_syntax_error()
1885 self.edit_syntax_error()
2025
1886
2026 def interact_with_readline(self):
1887 def interact_with_readline(self):
2027 """ Demo of using interact_handle_input, interact_prompt
1888 """ Demo of using interact_handle_input, interact_prompt
2028
1889
2029 This is the main read-eval-print loop. If you need to implement your own (e.g. for GUI),
1890 This is the main read-eval-print loop. If you need to implement your own (e.g. for GUI),
2030 it should work like this.
1891 it should work like this.
2031 """
1892 """
2032 self.readline_startup_hook(self.pre_readline)
1893 self.readline_startup_hook(self.pre_readline)
2033 while not self.exit_now:
1894 while not self.exit_now:
2034 self.interact_prompt()
1895 self.interact_prompt()
2035 if self.more:
1896 if self.more:
2036 self.rl_do_indent = True
1897 self.rl_do_indent = True
2037 else:
1898 else:
2038 self.rl_do_indent = False
1899 self.rl_do_indent = False
2039 line = raw_input_original().decode(self.stdin_encoding)
1900 line = raw_input_original().decode(self.stdin_encoding)
2040 self.interact_handle_input(line)
1901 self.interact_handle_input(line)
2041
1902
2042 def interact(self, banner=None):
1903 def interact(self, banner=None):
2043 """Closely emulate the interactive Python console."""
1904 """Closely emulate the interactive Python console."""
2044
1905
2045 # batch run -> do not interact
1906 # batch run -> do not interact
2046 if self.exit_now:
1907 if self.exit_now:
2047 return
1908 return
2048
1909
2049 if self.display_banner:
1910 if self.display_banner:
2050 if banner is None:
1911 if banner is None:
2051 banner = self.banner
1912 banner = self.banner
2052 self.write(banner)
1913 self.write(banner)
2053
1914
2054 more = 0
1915 more = 0
2055
1916
2056 # Mark activity in the builtins
1917 # Mark activity in the builtins
2057 __builtin__.__dict__['__IPYTHON__active'] += 1
1918 __builtin__.__dict__['__IPYTHON__active'] += 1
2058
1919
2059 if self.has_readline:
1920 if self.has_readline:
2060 self.readline_startup_hook(self.pre_readline)
1921 self.readline_startup_hook(self.pre_readline)
2061 # exit_now is set by a call to %Exit or %Quit, through the
1922 # exit_now is set by a call to %Exit or %Quit, through the
2062 # ask_exit callback.
1923 # ask_exit callback.
2063
1924
2064 while not self.exit_now:
1925 while not self.exit_now:
2065 self.hooks.pre_prompt_hook()
1926 self.hooks.pre_prompt_hook()
2066 if more:
1927 if more:
2067 try:
1928 try:
2068 prompt = self.hooks.generate_prompt(True)
1929 prompt = self.hooks.generate_prompt(True)
2069 except:
1930 except:
2070 self.showtraceback()
1931 self.showtraceback()
2071 if self.autoindent:
1932 if self.autoindent:
2072 self.rl_do_indent = True
1933 self.rl_do_indent = True
2073
1934
2074 else:
1935 else:
2075 try:
1936 try:
2076 prompt = self.hooks.generate_prompt(False)
1937 prompt = self.hooks.generate_prompt(False)
2077 except:
1938 except:
2078 self.showtraceback()
1939 self.showtraceback()
2079 try:
1940 try:
2080 line = self.raw_input(prompt, more)
1941 line = self.raw_input(prompt, more)
2081 if self.exit_now:
1942 if self.exit_now:
2082 # quick exit on sys.std[in|out] close
1943 # quick exit on sys.std[in|out] close
2083 break
1944 break
2084 if self.autoindent:
1945 if self.autoindent:
2085 self.rl_do_indent = False
1946 self.rl_do_indent = False
2086
1947
2087 except KeyboardInterrupt:
1948 except KeyboardInterrupt:
2088 #double-guard against keyboardinterrupts during kbdint handling
1949 #double-guard against keyboardinterrupts during kbdint handling
2089 try:
1950 try:
2090 self.write('\nKeyboardInterrupt\n')
1951 self.write('\nKeyboardInterrupt\n')
2091 self.resetbuffer()
1952 self.resetbuffer()
2092 # keep cache in sync with the prompt counter:
1953 # keep cache in sync with the prompt counter:
2093 self.outputcache.prompt_count -= 1
1954 self.outputcache.prompt_count -= 1
2094
1955
2095 if self.autoindent:
1956 if self.autoindent:
2096 self.indent_current_nsp = 0
1957 self.indent_current_nsp = 0
2097 more = 0
1958 more = 0
2098 except KeyboardInterrupt:
1959 except KeyboardInterrupt:
2099 pass
1960 pass
2100 except EOFError:
1961 except EOFError:
2101 if self.autoindent:
1962 if self.autoindent:
2102 self.rl_do_indent = False
1963 self.rl_do_indent = False
2103 self.readline_startup_hook(None)
1964 self.readline_startup_hook(None)
2104 self.write('\n')
1965 self.write('\n')
2105 self.exit()
1966 self.exit()
2106 except bdb.BdbQuit:
1967 except bdb.BdbQuit:
2107 warn('The Python debugger has exited with a BdbQuit exception.\n'
1968 warn('The Python debugger has exited with a BdbQuit exception.\n'
2108 'Because of how pdb handles the stack, it is impossible\n'
1969 'Because of how pdb handles the stack, it is impossible\n'
2109 'for IPython to properly format this particular exception.\n'
1970 'for IPython to properly format this particular exception.\n'
2110 'IPython will resume normal operation.')
1971 'IPython will resume normal operation.')
2111 except:
1972 except:
2112 # exceptions here are VERY RARE, but they can be triggered
1973 # exceptions here are VERY RARE, but they can be triggered
2113 # asynchronously by signal handlers, for example.
1974 # asynchronously by signal handlers, for example.
2114 self.showtraceback()
1975 self.showtraceback()
2115 else:
1976 else:
2116 more = self.push_line(line)
1977 more = self.push_line(line)
2117 if (self.SyntaxTB.last_syntax_error and
1978 if (self.SyntaxTB.last_syntax_error and
2118 self.autoedit_syntax):
1979 self.autoedit_syntax):
2119 self.edit_syntax_error()
1980 self.edit_syntax_error()
2120
1981
2121 # We are off again...
1982 # We are off again...
2122 __builtin__.__dict__['__IPYTHON__active'] -= 1
1983 __builtin__.__dict__['__IPYTHON__active'] -= 1
2123
1984
2124 def excepthook(self, etype, value, tb):
1985 def excepthook(self, etype, value, tb):
2125 """One more defense for GUI apps that call sys.excepthook.
1986 """One more defense for GUI apps that call sys.excepthook.
2126
1987
2127 GUI frameworks like wxPython trap exceptions and call
1988 GUI frameworks like wxPython trap exceptions and call
2128 sys.excepthook themselves. I guess this is a feature that
1989 sys.excepthook themselves. I guess this is a feature that
2129 enables them to keep running after exceptions that would
1990 enables them to keep running after exceptions that would
2130 otherwise kill their mainloop. This is a bother for IPython
1991 otherwise kill their mainloop. This is a bother for IPython
2131 which excepts to catch all of the program exceptions with a try:
1992 which excepts to catch all of the program exceptions with a try:
2132 except: statement.
1993 except: statement.
2133
1994
2134 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1995 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
2135 any app directly invokes sys.excepthook, it will look to the user like
1996 any app directly invokes sys.excepthook, it will look to the user like
2136 IPython crashed. In order to work around this, we can disable the
1997 IPython crashed. In order to work around this, we can disable the
2137 CrashHandler and replace it with this excepthook instead, which prints a
1998 CrashHandler and replace it with this excepthook instead, which prints a
2138 regular traceback using our InteractiveTB. In this fashion, apps which
1999 regular traceback using our InteractiveTB. In this fashion, apps which
2139 call sys.excepthook will generate a regular-looking exception from
2000 call sys.excepthook will generate a regular-looking exception from
2140 IPython, and the CrashHandler will only be triggered by real IPython
2001 IPython, and the CrashHandler will only be triggered by real IPython
2141 crashes.
2002 crashes.
2142
2003
2143 This hook should be used sparingly, only in places which are not likely
2004 This hook should be used sparingly, only in places which are not likely
2144 to be true IPython errors.
2005 to be true IPython errors.
2145 """
2006 """
2146 self.showtraceback((etype,value,tb),tb_offset=0)
2007 self.showtraceback((etype,value,tb),tb_offset=0)
2147
2008
2148 def expand_alias(self, line):
2009 def expand_alias(self, line):
2149 """ Expand an alias in the command line
2010 """ Expand an alias in the command line
2150
2011
2151 Returns the provided command line, possibly with the first word
2012 Returns the provided command line, possibly with the first word
2152 (command) translated according to alias expansion rules.
2013 (command) translated according to alias expansion rules.
2153
2014
2154 [ipython]|16> _ip.expand_aliases("np myfile.txt")
2015 [ipython]|16> _ip.expand_aliases("np myfile.txt")
2155 <16> 'q:/opt/np/notepad++.exe myfile.txt'
2016 <16> 'q:/opt/np/notepad++.exe myfile.txt'
2156 """
2017 """
2157
2018
2158 pre,fn,rest = self.split_user_input(line)
2019 pre,fn,rest = self.split_user_input(line)
2159 res = pre + self.expand_aliases(fn, rest)
2020 res = pre + self.expand_aliases(fn, rest)
2160 return res
2021 return res
2161
2022
2162 def expand_aliases(self, fn, rest):
2023 def expand_aliases(self, fn, rest):
2163 """Expand multiple levels of aliases:
2024 """Expand multiple levels of aliases:
2164
2025
2165 if:
2026 if:
2166
2027
2167 alias foo bar /tmp
2028 alias foo bar /tmp
2168 alias baz foo
2029 alias baz foo
2169
2030
2170 then:
2031 then:
2171
2032
2172 baz huhhahhei -> bar /tmp huhhahhei
2033 baz huhhahhei -> bar /tmp huhhahhei
2173
2034
2174 """
2035 """
2175 line = fn + " " + rest
2036 line = fn + " " + rest
2176
2037
2177 done = set()
2038 done = set()
2178 while 1:
2039 while 1:
2179 pre,fn,rest = prefilter.splitUserInput(line,
2040 pre,fn,rest = prefilter.splitUserInput(line,
2180 prefilter.shell_line_split)
2041 prefilter.shell_line_split)
2181 if fn in self.alias_table:
2042 if fn in self.alias_table:
2182 if fn in done:
2043 if fn in done:
2183 warn("Cyclic alias definition, repeated '%s'" % fn)
2044 warn("Cyclic alias definition, repeated '%s'" % fn)
2184 return ""
2045 return ""
2185 done.add(fn)
2046 done.add(fn)
2186
2047
2187 l2 = self.transform_alias(fn,rest)
2048 l2 = self.transform_alias(fn,rest)
2188 # dir -> dir
2049 # dir -> dir
2189 # print "alias",line, "->",l2 #dbg
2050 # print "alias",line, "->",l2 #dbg
2190 if l2 == line:
2051 if l2 == line:
2191 break
2052 break
2192 # ls -> ls -F should not recurse forever
2053 # ls -> ls -F should not recurse forever
2193 if l2.split(None,1)[0] == line.split(None,1)[0]:
2054 if l2.split(None,1)[0] == line.split(None,1)[0]:
2194 line = l2
2055 line = l2
2195 break
2056 break
2196
2057
2197 line=l2
2058 line=l2
2198
2059
2199
2060
2200 # print "al expand to",line #dbg
2061 # print "al expand to",line #dbg
2201 else:
2062 else:
2202 break
2063 break
2203
2064
2204 return line
2065 return line
2205
2066
2206 def transform_alias(self, alias,rest=''):
2067 def transform_alias(self, alias,rest=''):
2207 """ Transform alias to system command string.
2068 """ Transform alias to system command string.
2208 """
2069 """
2209 trg = self.alias_table[alias]
2070 trg = self.alias_table[alias]
2210
2071
2211 nargs,cmd = trg
2072 nargs,cmd = trg
2212 # print trg #dbg
2073 # print trg #dbg
2213 if ' ' in cmd and os.path.isfile(cmd):
2074 if ' ' in cmd and os.path.isfile(cmd):
2214 cmd = '"%s"' % cmd
2075 cmd = '"%s"' % cmd
2215
2076
2216 # Expand the %l special to be the user's input line
2077 # Expand the %l special to be the user's input line
2217 if cmd.find('%l') >= 0:
2078 if cmd.find('%l') >= 0:
2218 cmd = cmd.replace('%l',rest)
2079 cmd = cmd.replace('%l',rest)
2219 rest = ''
2080 rest = ''
2220 if nargs==0:
2081 if nargs==0:
2221 # Simple, argument-less aliases
2082 # Simple, argument-less aliases
2222 cmd = '%s %s' % (cmd,rest)
2083 cmd = '%s %s' % (cmd,rest)
2223 else:
2084 else:
2224 # Handle aliases with positional arguments
2085 # Handle aliases with positional arguments
2225 args = rest.split(None,nargs)
2086 args = rest.split(None,nargs)
2226 if len(args)< nargs:
2087 if len(args)< nargs:
2227 error('Alias <%s> requires %s arguments, %s given.' %
2088 error('Alias <%s> requires %s arguments, %s given.' %
2228 (alias,nargs,len(args)))
2089 (alias,nargs,len(args)))
2229 return None
2090 return None
2230 cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
2091 cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
2231 # Now call the macro, evaluating in the user's namespace
2092 # Now call the macro, evaluating in the user's namespace
2232 #print 'new command: <%r>' % cmd # dbg
2093 #print 'new command: <%r>' % cmd # dbg
2233 return cmd
2094 return cmd
2234
2095
2235 def call_alias(self,alias,rest=''):
2096 def call_alias(self,alias,rest=''):
2236 """Call an alias given its name and the rest of the line.
2097 """Call an alias given its name and the rest of the line.
2237
2098
2238 This is only used to provide backwards compatibility for users of
2099 This is only used to provide backwards compatibility for users of
2239 ipalias(), use of which is not recommended for anymore."""
2100 ipalias(), use of which is not recommended for anymore."""
2240
2101
2241 # Now call the macro, evaluating in the user's namespace
2102 # Now call the macro, evaluating in the user's namespace
2242 cmd = self.transform_alias(alias, rest)
2103 cmd = self.transform_alias(alias, rest)
2243 try:
2104 try:
2244 self.system(cmd)
2105 self.system(cmd)
2245 except:
2106 except:
2246 self.showtraceback()
2107 self.showtraceback()
2247
2108
2248 def indent_current_str(self):
2109 def indent_current_str(self):
2249 """return the current level of indentation as a string"""
2110 """return the current level of indentation as a string"""
2250 return self.indent_current_nsp * ' '
2111 return self.indent_current_nsp * ' '
2251
2112
2252 def autoindent_update(self,line):
2113 def autoindent_update(self,line):
2253 """Keep track of the indent level."""
2114 """Keep track of the indent level."""
2254
2115
2255 #debugx('line')
2116 #debugx('line')
2256 #debugx('self.indent_current_nsp')
2117 #debugx('self.indent_current_nsp')
2257 if self.autoindent:
2118 if self.autoindent:
2258 if line:
2119 if line:
2259 inisp = num_ini_spaces(line)
2120 inisp = num_ini_spaces(line)
2260 if inisp < self.indent_current_nsp:
2121 if inisp < self.indent_current_nsp:
2261 self.indent_current_nsp = inisp
2122 self.indent_current_nsp = inisp
2262
2123
2263 if line[-1] == ':':
2124 if line[-1] == ':':
2264 self.indent_current_nsp += 4
2125 self.indent_current_nsp += 4
2265 elif dedent_re.match(line):
2126 elif dedent_re.match(line):
2266 self.indent_current_nsp -= 4
2127 self.indent_current_nsp -= 4
2267 else:
2128 else:
2268 self.indent_current_nsp = 0
2129 self.indent_current_nsp = 0
2269
2130
2270 def push(self, variables, interactive=True):
2131 def push(self, variables, interactive=True):
2271 """Inject a group of variables into the IPython user namespace.
2132 """Inject a group of variables into the IPython user namespace.
2272
2133
2273 Parameters
2134 Parameters
2274 ----------
2135 ----------
2275 variables : dict, str or list/tuple of str
2136 variables : dict, str or list/tuple of str
2276 The variables to inject into the user's namespace. If a dict,
2137 The variables to inject into the user's namespace. If a dict,
2277 a simple update is done. If a str, the string is assumed to
2138 a simple update is done. If a str, the string is assumed to
2278 have variable names separated by spaces. A list/tuple of str
2139 have variable names separated by spaces. A list/tuple of str
2279 can also be used to give the variable names. If just the variable
2140 can also be used to give the variable names. If just the variable
2280 names are give (list/tuple/str) then the variable values looked
2141 names are give (list/tuple/str) then the variable values looked
2281 up in the callers frame.
2142 up in the callers frame.
2282 interactive : bool
2143 interactive : bool
2283 If True (default), the variables will be listed with the ``who``
2144 If True (default), the variables will be listed with the ``who``
2284 magic.
2145 magic.
2285 """
2146 """
2286 vdict = None
2147 vdict = None
2287
2148
2288 # We need a dict of name/value pairs to do namespace updates.
2149 # We need a dict of name/value pairs to do namespace updates.
2289 if isinstance(variables, dict):
2150 if isinstance(variables, dict):
2290 vdict = variables
2151 vdict = variables
2291 elif isinstance(variables, (basestring, list, tuple)):
2152 elif isinstance(variables, (basestring, list, tuple)):
2292 if isinstance(variables, basestring):
2153 if isinstance(variables, basestring):
2293 vlist = variables.split()
2154 vlist = variables.split()
2294 else:
2155 else:
2295 vlist = variables
2156 vlist = variables
2296 vdict = {}
2157 vdict = {}
2297 cf = sys._getframe(1)
2158 cf = sys._getframe(1)
2298 for name in vlist:
2159 for name in vlist:
2299 try:
2160 try:
2300 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
2161 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
2301 except:
2162 except:
2302 print ('Could not get variable %s from %s' %
2163 print ('Could not get variable %s from %s' %
2303 (name,cf.f_code.co_name))
2164 (name,cf.f_code.co_name))
2304 else:
2165 else:
2305 raise ValueError('variables must be a dict/str/list/tuple')
2166 raise ValueError('variables must be a dict/str/list/tuple')
2306
2167
2307 # Propagate variables to user namespace
2168 # Propagate variables to user namespace
2308 self.user_ns.update(vdict)
2169 self.user_ns.update(vdict)
2309
2170
2310 # And configure interactive visibility
2171 # And configure interactive visibility
2311 config_ns = self.user_config_ns
2172 config_ns = self.user_config_ns
2312 if interactive:
2173 if interactive:
2313 for name, val in vdict.iteritems():
2174 for name, val in vdict.iteritems():
2314 config_ns.pop(name, None)
2175 config_ns.pop(name, None)
2315 else:
2176 else:
2316 for name,val in vdict.iteritems():
2177 for name,val in vdict.iteritems():
2317 config_ns[name] = val
2178 config_ns[name] = val
2318
2179
2319 def cleanup_ipy_script(self, script):
2180 def cleanup_ipy_script(self, script):
2320 """Make a script safe for self.runlines()
2181 """Make a script safe for self.runlines()
2321
2182
2322 Notes
2183 Notes
2323 -----
2184 -----
2324 This was copied over from the old ipapi and probably can be done
2185 This was copied over from the old ipapi and probably can be done
2325 away with once we move to block based interpreter.
2186 away with once we move to block based interpreter.
2326
2187
2327 - Removes empty lines Suffixes all indented blocks that end with
2188 - Removes empty lines Suffixes all indented blocks that end with
2328 - unindented lines with empty lines
2189 - unindented lines with empty lines
2329 """
2190 """
2330
2191
2331 res = []
2192 res = []
2332 lines = script.splitlines()
2193 lines = script.splitlines()
2333
2194
2334 level = 0
2195 level = 0
2335 for l in lines:
2196 for l in lines:
2336 lstripped = l.lstrip()
2197 lstripped = l.lstrip()
2337 stripped = l.strip()
2198 stripped = l.strip()
2338 if not stripped:
2199 if not stripped:
2339 continue
2200 continue
2340 newlevel = len(l) - len(lstripped)
2201 newlevel = len(l) - len(lstripped)
2341 def is_secondary_block_start(s):
2202 def is_secondary_block_start(s):
2342 if not s.endswith(':'):
2203 if not s.endswith(':'):
2343 return False
2204 return False
2344 if (s.startswith('elif') or
2205 if (s.startswith('elif') or
2345 s.startswith('else') or
2206 s.startswith('else') or
2346 s.startswith('except') or
2207 s.startswith('except') or
2347 s.startswith('finally')):
2208 s.startswith('finally')):
2348 return True
2209 return True
2349
2210
2350 if level > 0 and newlevel == 0 and \
2211 if level > 0 and newlevel == 0 and \
2351 not is_secondary_block_start(stripped):
2212 not is_secondary_block_start(stripped):
2352 # add empty line
2213 # add empty line
2353 res.append('')
2214 res.append('')
2354
2215
2355 res.append(l)
2216 res.append(l)
2356 level = newlevel
2217 level = newlevel
2357 return '\n'.join(res) + '\n'
2218 return '\n'.join(res) + '\n'
2358
2219
2359 def runlines(self, lines, clean=False):
2220 def runlines(self, lines, clean=False):
2360 """Run a string of one or more lines of source.
2221 """Run a string of one or more lines of source.
2361
2222
2362 This method is capable of running a string containing multiple source
2223 This method is capable of running a string containing multiple source
2363 lines, as if they had been entered at the IPython prompt. Since it
2224 lines, as if they had been entered at the IPython prompt. Since it
2364 exposes IPython's processing machinery, the given strings can contain
2225 exposes IPython's processing machinery, the given strings can contain
2365 magic calls (%magic), special shell access (!cmd), etc.
2226 magic calls (%magic), special shell access (!cmd), etc.
2366 """
2227 """
2367
2228
2368 if isinstance(lines, (list, tuple)):
2229 if isinstance(lines, (list, tuple)):
2369 lines = '\n'.join(lines)
2230 lines = '\n'.join(lines)
2370
2231
2371 if clean:
2232 if clean:
2372 lines = self.cleanup_ipy_script(lines)
2233 lines = self.cleanup_ipy_script(lines)
2373
2234
2374 # We must start with a clean buffer, in case this is run from an
2235 # We must start with a clean buffer, in case this is run from an
2375 # interactive IPython session (via a magic, for example).
2236 # interactive IPython session (via a magic, for example).
2376 self.resetbuffer()
2237 self.resetbuffer()
2377 lines = lines.splitlines()
2238 lines = lines.splitlines()
2378 more = 0
2239 more = 0
2379
2240
2380 for line in lines:
2241 with self.builtin_trap:
2381 # skip blank lines so we don't mess up the prompt counter, but do
2242 for line in lines:
2382 # NOT skip even a blank line if we are in a code block (more is
2243 # skip blank lines so we don't mess up the prompt counter, but do
2383 # true)
2244 # NOT skip even a blank line if we are in a code block (more is
2245 # true)
2384
2246
2385 if line or more:
2247 if line or more:
2386 # push to raw history, so hist line numbers stay in sync
2248 # push to raw history, so hist line numbers stay in sync
2387 self.input_hist_raw.append("# " + line + "\n")
2249 self.input_hist_raw.append("# " + line + "\n")
2388 more = self.push_line(self.prefilter(line,more))
2250 more = self.push_line(self.prefilter(line,more))
2389 # IPython's runsource returns None if there was an error
2251 # IPython's runsource returns None if there was an error
2390 # compiling the code. This allows us to stop processing right
2252 # compiling the code. This allows us to stop processing right
2391 # away, so the user gets the error message at the right place.
2253 # away, so the user gets the error message at the right place.
2392 if more is None:
2254 if more is None:
2393 break
2255 break
2394 else:
2256 else:
2395 self.input_hist_raw.append("\n")
2257 self.input_hist_raw.append("\n")
2396 # final newline in case the input didn't have it, so that the code
2258 # final newline in case the input didn't have it, so that the code
2397 # actually does get executed
2259 # actually does get executed
2398 if more:
2260 if more:
2399 self.push_line('\n')
2261 self.push_line('\n')
2400
2262
2401 def runsource(self, source, filename='<input>', symbol='single'):
2263 def runsource(self, source, filename='<input>', symbol='single'):
2402 """Compile and run some source in the interpreter.
2264 """Compile and run some source in the interpreter.
2403
2265
2404 Arguments are as for compile_command().
2266 Arguments are as for compile_command().
2405
2267
2406 One several things can happen:
2268 One several things can happen:
2407
2269
2408 1) The input is incorrect; compile_command() raised an
2270 1) The input is incorrect; compile_command() raised an
2409 exception (SyntaxError or OverflowError). A syntax traceback
2271 exception (SyntaxError or OverflowError). A syntax traceback
2410 will be printed by calling the showsyntaxerror() method.
2272 will be printed by calling the showsyntaxerror() method.
2411
2273
2412 2) The input is incomplete, and more input is required;
2274 2) The input is incomplete, and more input is required;
2413 compile_command() returned None. Nothing happens.
2275 compile_command() returned None. Nothing happens.
2414
2276
2415 3) The input is complete; compile_command() returned a code
2277 3) The input is complete; compile_command() returned a code
2416 object. The code is executed by calling self.runcode() (which
2278 object. The code is executed by calling self.runcode() (which
2417 also handles run-time exceptions, except for SystemExit).
2279 also handles run-time exceptions, except for SystemExit).
2418
2280
2419 The return value is:
2281 The return value is:
2420
2282
2421 - True in case 2
2283 - True in case 2
2422
2284
2423 - False in the other cases, unless an exception is raised, where
2285 - False in the other cases, unless an exception is raised, where
2424 None is returned instead. This can be used by external callers to
2286 None is returned instead. This can be used by external callers to
2425 know whether to continue feeding input or not.
2287 know whether to continue feeding input or not.
2426
2288
2427 The return value can be used to decide whether to use sys.ps1 or
2289 The return value can be used to decide whether to use sys.ps1 or
2428 sys.ps2 to prompt the next line."""
2290 sys.ps2 to prompt the next line."""
2429
2291
2430 # if the source code has leading blanks, add 'if 1:\n' to it
2292 # if the source code has leading blanks, add 'if 1:\n' to it
2431 # this allows execution of indented pasted code. It is tempting
2293 # this allows execution of indented pasted code. It is tempting
2432 # to add '\n' at the end of source to run commands like ' a=1'
2294 # to add '\n' at the end of source to run commands like ' a=1'
2433 # directly, but this fails for more complicated scenarios
2295 # directly, but this fails for more complicated scenarios
2434 source=source.encode(self.stdin_encoding)
2296 source=source.encode(self.stdin_encoding)
2435 if source[:1] in [' ', '\t']:
2297 if source[:1] in [' ', '\t']:
2436 source = 'if 1:\n%s' % source
2298 source = 'if 1:\n%s' % source
2437
2299
2438 try:
2300 try:
2439 code = self.compile(source,filename,symbol)
2301 code = self.compile(source,filename,symbol)
2440 except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError):
2302 except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError):
2441 # Case 1
2303 # Case 1
2442 self.showsyntaxerror(filename)
2304 self.showsyntaxerror(filename)
2443 return None
2305 return None
2444
2306
2445 if code is None:
2307 if code is None:
2446 # Case 2
2308 # Case 2
2447 return True
2309 return True
2448
2310
2449 # Case 3
2311 # Case 3
2450 # We store the code object so that threaded shells and
2312 # We store the code object so that threaded shells and
2451 # custom exception handlers can access all this info if needed.
2313 # custom exception handlers can access all this info if needed.
2452 # The source corresponding to this can be obtained from the
2314 # The source corresponding to this can be obtained from the
2453 # buffer attribute as '\n'.join(self.buffer).
2315 # buffer attribute as '\n'.join(self.buffer).
2454 self.code_to_run = code
2316 self.code_to_run = code
2455 # now actually execute the code object
2317 # now actually execute the code object
2456 if self.runcode(code) == 0:
2318 if self.runcode(code) == 0:
2457 return False
2319 return False
2458 else:
2320 else:
2459 return None
2321 return None
2460
2322
2461 def runcode(self,code_obj):
2323 def runcode(self,code_obj):
2462 """Execute a code object.
2324 """Execute a code object.
2463
2325
2464 When an exception occurs, self.showtraceback() is called to display a
2326 When an exception occurs, self.showtraceback() is called to display a
2465 traceback.
2327 traceback.
2466
2328
2467 Return value: a flag indicating whether the code to be run completed
2329 Return value: a flag indicating whether the code to be run completed
2468 successfully:
2330 successfully:
2469
2331
2470 - 0: successful execution.
2332 - 0: successful execution.
2471 - 1: an error occurred.
2333 - 1: an error occurred.
2472 """
2334 """
2473
2335
2474 # Set our own excepthook in case the user code tries to call it
2336 # Set our own excepthook in case the user code tries to call it
2475 # directly, so that the IPython crash handler doesn't get triggered
2337 # directly, so that the IPython crash handler doesn't get triggered
2476 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
2338 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
2477
2339
2478 # we save the original sys.excepthook in the instance, in case config
2340 # we save the original sys.excepthook in the instance, in case config
2479 # code (such as magics) needs access to it.
2341 # code (such as magics) needs access to it.
2480 self.sys_excepthook = old_excepthook
2342 self.sys_excepthook = old_excepthook
2481 outflag = 1 # happens in more places, so it's easier as default
2343 outflag = 1 # happens in more places, so it's easier as default
2482 try:
2344 try:
2483 try:
2345 try:
2484 self.hooks.pre_runcode_hook()
2346 self.hooks.pre_runcode_hook()
2485 exec code_obj in self.user_global_ns, self.user_ns
2347 exec code_obj in self.user_global_ns, self.user_ns
2486 finally:
2348 finally:
2487 # Reset our crash handler in place
2349 # Reset our crash handler in place
2488 sys.excepthook = old_excepthook
2350 sys.excepthook = old_excepthook
2489 except SystemExit:
2351 except SystemExit:
2490 self.resetbuffer()
2352 self.resetbuffer()
2491 self.showtraceback()
2353 self.showtraceback()
2492 warn("Type %exit or %quit to exit IPython "
2354 warn("Type %exit or %quit to exit IPython "
2493 "(%Exit or %Quit do so unconditionally).",level=1)
2355 "(%Exit or %Quit do so unconditionally).",level=1)
2494 except self.custom_exceptions:
2356 except self.custom_exceptions:
2495 etype,value,tb = sys.exc_info()
2357 etype,value,tb = sys.exc_info()
2496 self.CustomTB(etype,value,tb)
2358 self.CustomTB(etype,value,tb)
2497 except:
2359 except:
2498 self.showtraceback()
2360 self.showtraceback()
2499 else:
2361 else:
2500 outflag = 0
2362 outflag = 0
2501 if softspace(sys.stdout, 0):
2363 if softspace(sys.stdout, 0):
2502 print
2364 print
2503 # Flush out code object which has been run (and source)
2365 # Flush out code object which has been run (and source)
2504 self.code_to_run = None
2366 self.code_to_run = None
2505 return outflag
2367 return outflag
2506
2368
2507 def push_line(self, line):
2369 def push_line(self, line):
2508 """Push a line to the interpreter.
2370 """Push a line to the interpreter.
2509
2371
2510 The line should not have a trailing newline; it may have
2372 The line should not have a trailing newline; it may have
2511 internal newlines. The line is appended to a buffer and the
2373 internal newlines. The line is appended to a buffer and the
2512 interpreter's runsource() method is called with the
2374 interpreter's runsource() method is called with the
2513 concatenated contents of the buffer as source. If this
2375 concatenated contents of the buffer as source. If this
2514 indicates that the command was executed or invalid, the buffer
2376 indicates that the command was executed or invalid, the buffer
2515 is reset; otherwise, the command is incomplete, and the buffer
2377 is reset; otherwise, the command is incomplete, and the buffer
2516 is left as it was after the line was appended. The return
2378 is left as it was after the line was appended. The return
2517 value is 1 if more input is required, 0 if the line was dealt
2379 value is 1 if more input is required, 0 if the line was dealt
2518 with in some way (this is the same as runsource()).
2380 with in some way (this is the same as runsource()).
2519 """
2381 """
2520
2382
2521 # autoindent management should be done here, and not in the
2383 # autoindent management should be done here, and not in the
2522 # interactive loop, since that one is only seen by keyboard input. We
2384 # interactive loop, since that one is only seen by keyboard input. We
2523 # need this done correctly even for code run via runlines (which uses
2385 # need this done correctly even for code run via runlines (which uses
2524 # push).
2386 # push).
2525
2387
2526 #print 'push line: <%s>' % line # dbg
2388 #print 'push line: <%s>' % line # dbg
2527 for subline in line.splitlines():
2389 for subline in line.splitlines():
2528 self.autoindent_update(subline)
2390 self.autoindent_update(subline)
2529 self.buffer.append(line)
2391 self.buffer.append(line)
2530 more = self.runsource('\n'.join(self.buffer), self.filename)
2392 more = self.runsource('\n'.join(self.buffer), self.filename)
2531 if not more:
2393 if not more:
2532 self.resetbuffer()
2394 self.resetbuffer()
2533 return more
2395 return more
2534
2396
2535 def split_user_input(self, line):
2397 def split_user_input(self, line):
2536 # This is really a hold-over to support ipapi and some extensions
2398 # This is really a hold-over to support ipapi and some extensions
2537 return prefilter.splitUserInput(line)
2399 return prefilter.splitUserInput(line)
2538
2400
2539 def resetbuffer(self):
2401 def resetbuffer(self):
2540 """Reset the input buffer."""
2402 """Reset the input buffer."""
2541 self.buffer[:] = []
2403 self.buffer[:] = []
2542
2404
2543 def raw_input(self,prompt='',continue_prompt=False):
2405 def raw_input(self,prompt='',continue_prompt=False):
2544 """Write a prompt and read a line.
2406 """Write a prompt and read a line.
2545
2407
2546 The returned line does not include the trailing newline.
2408 The returned line does not include the trailing newline.
2547 When the user enters the EOF key sequence, EOFError is raised.
2409 When the user enters the EOF key sequence, EOFError is raised.
2548
2410
2549 Optional inputs:
2411 Optional inputs:
2550
2412
2551 - prompt(''): a string to be printed to prompt the user.
2413 - prompt(''): a string to be printed to prompt the user.
2552
2414
2553 - continue_prompt(False): whether this line is the first one or a
2415 - continue_prompt(False): whether this line is the first one or a
2554 continuation in a sequence of inputs.
2416 continuation in a sequence of inputs.
2555 """
2417 """
2556
2418
2557 # Code run by the user may have modified the readline completer state.
2419 # Code run by the user may have modified the readline completer state.
2558 # We must ensure that our completer is back in place.
2420 # We must ensure that our completer is back in place.
2559 if self.has_readline:
2421 if self.has_readline:
2560 self.set_completer()
2422 self.set_completer()
2561
2423
2562 try:
2424 try:
2563 line = raw_input_original(prompt).decode(self.stdin_encoding)
2425 line = raw_input_original(prompt).decode(self.stdin_encoding)
2564 except ValueError:
2426 except ValueError:
2565 warn("\n********\nYou or a %run:ed script called sys.stdin.close()"
2427 warn("\n********\nYou or a %run:ed script called sys.stdin.close()"
2566 " or sys.stdout.close()!\nExiting IPython!")
2428 " or sys.stdout.close()!\nExiting IPython!")
2567 self.ask_exit()
2429 self.ask_exit()
2568 return ""
2430 return ""
2569
2431
2570 # Try to be reasonably smart about not re-indenting pasted input more
2432 # Try to be reasonably smart about not re-indenting pasted input more
2571 # than necessary. We do this by trimming out the auto-indent initial
2433 # than necessary. We do this by trimming out the auto-indent initial
2572 # spaces, if the user's actual input started itself with whitespace.
2434 # spaces, if the user's actual input started itself with whitespace.
2573 #debugx('self.buffer[-1]')
2435 #debugx('self.buffer[-1]')
2574
2436
2575 if self.autoindent:
2437 if self.autoindent:
2576 if num_ini_spaces(line) > self.indent_current_nsp:
2438 if num_ini_spaces(line) > self.indent_current_nsp:
2577 line = line[self.indent_current_nsp:]
2439 line = line[self.indent_current_nsp:]
2578 self.indent_current_nsp = 0
2440 self.indent_current_nsp = 0
2579
2441
2580 # store the unfiltered input before the user has any chance to modify
2442 # store the unfiltered input before the user has any chance to modify
2581 # it.
2443 # it.
2582 if line.strip():
2444 if line.strip():
2583 if continue_prompt:
2445 if continue_prompt:
2584 self.input_hist_raw[-1] += '%s\n' % line
2446 self.input_hist_raw[-1] += '%s\n' % line
2585 if self.has_readline: # and some config option is set?
2447 if self.has_readline: # and some config option is set?
2586 try:
2448 try:
2587 histlen = self.readline.get_current_history_length()
2449 histlen = self.readline.get_current_history_length()
2588 if histlen > 1:
2450 if histlen > 1:
2589 newhist = self.input_hist_raw[-1].rstrip()
2451 newhist = self.input_hist_raw[-1].rstrip()
2590 self.readline.remove_history_item(histlen-1)
2452 self.readline.remove_history_item(histlen-1)
2591 self.readline.replace_history_item(histlen-2,
2453 self.readline.replace_history_item(histlen-2,
2592 newhist.encode(self.stdin_encoding))
2454 newhist.encode(self.stdin_encoding))
2593 except AttributeError:
2455 except AttributeError:
2594 pass # re{move,place}_history_item are new in 2.4.
2456 pass # re{move,place}_history_item are new in 2.4.
2595 else:
2457 else:
2596 self.input_hist_raw.append('%s\n' % line)
2458 self.input_hist_raw.append('%s\n' % line)
2597 # only entries starting at first column go to shadow history
2459 # only entries starting at first column go to shadow history
2598 if line.lstrip() == line:
2460 if line.lstrip() == line:
2599 self.shadowhist.add(line.strip())
2461 self.shadowhist.add(line.strip())
2600 elif not continue_prompt:
2462 elif not continue_prompt:
2601 self.input_hist_raw.append('\n')
2463 self.input_hist_raw.append('\n')
2602 try:
2464 try:
2603 lineout = self.prefilter(line,continue_prompt)
2465 lineout = self.prefilter(line,continue_prompt)
2604 except:
2466 except:
2605 # blanket except, in case a user-defined prefilter crashes, so it
2467 # blanket except, in case a user-defined prefilter crashes, so it
2606 # can't take all of ipython with it.
2468 # can't take all of ipython with it.
2607 self.showtraceback()
2469 self.showtraceback()
2608 return ''
2470 return ''
2609 else:
2471 else:
2610 return lineout
2472 return lineout
2611
2473
2612 def _prefilter(self, line, continue_prompt):
2474 def _prefilter(self, line, continue_prompt):
2613 """Calls different preprocessors, depending on the form of line."""
2475 """Calls different preprocessors, depending on the form of line."""
2614
2476
2615 # All handlers *must* return a value, even if it's blank ('').
2477 # All handlers *must* return a value, even if it's blank ('').
2616
2478
2617 # Lines are NOT logged here. Handlers should process the line as
2479 # Lines are NOT logged here. Handlers should process the line as
2618 # needed, update the cache AND log it (so that the input cache array
2480 # needed, update the cache AND log it (so that the input cache array
2619 # stays synced).
2481 # stays synced).
2620
2482
2621 #.....................................................................
2483 #.....................................................................
2622 # Code begins
2484 # Code begins
2623
2485
2624 #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg
2486 #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg
2625
2487
2626 # save the line away in case we crash, so the post-mortem handler can
2488 # save the line away in case we crash, so the post-mortem handler can
2627 # record it
2489 # record it
2628 self._last_input_line = line
2490 self._last_input_line = line
2629
2491
2630 #print '***line: <%s>' % line # dbg
2492 #print '***line: <%s>' % line # dbg
2631
2493
2632 if not line:
2494 if not line:
2633 # Return immediately on purely empty lines, so that if the user
2495 # Return immediately on purely empty lines, so that if the user
2634 # previously typed some whitespace that started a continuation
2496 # previously typed some whitespace that started a continuation
2635 # prompt, he can break out of that loop with just an empty line.
2497 # prompt, he can break out of that loop with just an empty line.
2636 # This is how the default python prompt works.
2498 # This is how the default python prompt works.
2637
2499
2638 # Only return if the accumulated input buffer was just whitespace!
2500 # Only return if the accumulated input buffer was just whitespace!
2639 if ''.join(self.buffer).isspace():
2501 if ''.join(self.buffer).isspace():
2640 self.buffer[:] = []
2502 self.buffer[:] = []
2641 return ''
2503 return ''
2642
2504
2643 line_info = prefilter.LineInfo(line, continue_prompt)
2505 line_info = prefilter.LineInfo(line, continue_prompt)
2644
2506
2645 # the input history needs to track even empty lines
2507 # the input history needs to track even empty lines
2646 stripped = line.strip()
2508 stripped = line.strip()
2647
2509
2648 if not stripped:
2510 if not stripped:
2649 if not continue_prompt:
2511 if not continue_prompt:
2650 self.outputcache.prompt_count -= 1
2512 self.outputcache.prompt_count -= 1
2651 return self.handle_normal(line_info)
2513 return self.handle_normal(line_info)
2652
2514
2653 # print '***cont',continue_prompt # dbg
2515 # print '***cont',continue_prompt # dbg
2654 # special handlers are only allowed for single line statements
2516 # special handlers are only allowed for single line statements
2655 if continue_prompt and not self.multi_line_specials:
2517 if continue_prompt and not self.multi_line_specials:
2656 return self.handle_normal(line_info)
2518 return self.handle_normal(line_info)
2657
2519
2658
2520
2659 # See whether any pre-existing handler can take care of it
2521 # See whether any pre-existing handler can take care of it
2660 rewritten = self.hooks.input_prefilter(stripped)
2522 rewritten = self.hooks.input_prefilter(stripped)
2661 if rewritten != stripped: # ok, some prefilter did something
2523 if rewritten != stripped: # ok, some prefilter did something
2662 rewritten = line_info.pre + rewritten # add indentation
2524 rewritten = line_info.pre + rewritten # add indentation
2663 return self.handle_normal(prefilter.LineInfo(rewritten,
2525 return self.handle_normal(prefilter.LineInfo(rewritten,
2664 continue_prompt))
2526 continue_prompt))
2665
2527
2666 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
2528 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
2667
2529
2668 return prefilter.prefilter(line_info, self)
2530 return prefilter.prefilter(line_info, self)
2669
2531
2670
2532
2671 def _prefilter_dumb(self, line, continue_prompt):
2533 def _prefilter_dumb(self, line, continue_prompt):
2672 """simple prefilter function, for debugging"""
2534 """simple prefilter function, for debugging"""
2673 return self.handle_normal(line,continue_prompt)
2535 return self.handle_normal(line,continue_prompt)
2674
2536
2675
2537
2676 def multiline_prefilter(self, line, continue_prompt):
2538 def multiline_prefilter(self, line, continue_prompt):
2677 """ Run _prefilter for each line of input
2539 """ Run _prefilter for each line of input
2678
2540
2679 Covers cases where there are multiple lines in the user entry,
2541 Covers cases where there are multiple lines in the user entry,
2680 which is the case when the user goes back to a multiline history
2542 which is the case when the user goes back to a multiline history
2681 entry and presses enter.
2543 entry and presses enter.
2682
2544
2683 """
2545 """
2684 out = []
2546 out = []
2685 for l in line.rstrip('\n').split('\n'):
2547 for l in line.rstrip('\n').split('\n'):
2686 out.append(self._prefilter(l, continue_prompt))
2548 out.append(self._prefilter(l, continue_prompt))
2687 return '\n'.join(out)
2549 return '\n'.join(out)
2688
2550
2689 # Set the default prefilter() function (this can be user-overridden)
2551 # Set the default prefilter() function (this can be user-overridden)
2690 prefilter = multiline_prefilter
2552 prefilter = multiline_prefilter
2691
2553
2692 def handle_normal(self,line_info):
2554 def handle_normal(self,line_info):
2693 """Handle normal input lines. Use as a template for handlers."""
2555 """Handle normal input lines. Use as a template for handlers."""
2694
2556
2695 # With autoindent on, we need some way to exit the input loop, and I
2557 # With autoindent on, we need some way to exit the input loop, and I
2696 # don't want to force the user to have to backspace all the way to
2558 # don't want to force the user to have to backspace all the way to
2697 # clear the line. The rule will be in this case, that either two
2559 # clear the line. The rule will be in this case, that either two
2698 # lines of pure whitespace in a row, or a line of pure whitespace but
2560 # lines of pure whitespace in a row, or a line of pure whitespace but
2699 # of a size different to the indent level, will exit the input loop.
2561 # of a size different to the indent level, will exit the input loop.
2700 line = line_info.line
2562 line = line_info.line
2701 continue_prompt = line_info.continue_prompt
2563 continue_prompt = line_info.continue_prompt
2702
2564
2703 if (continue_prompt and self.autoindent and line.isspace() and
2565 if (continue_prompt and self.autoindent and line.isspace() and
2704 (0 < abs(len(line) - self.indent_current_nsp) <= 2 or
2566 (0 < abs(len(line) - self.indent_current_nsp) <= 2 or
2705 (self.buffer[-1]).isspace() )):
2567 (self.buffer[-1]).isspace() )):
2706 line = ''
2568 line = ''
2707
2569
2708 self.log(line,line,continue_prompt)
2570 self.log(line,line,continue_prompt)
2709 return line
2571 return line
2710
2572
2711 def handle_alias(self,line_info):
2573 def handle_alias(self,line_info):
2712 """Handle alias input lines. """
2574 """Handle alias input lines. """
2713 tgt = self.alias_table[line_info.iFun]
2575 tgt = self.alias_table[line_info.iFun]
2714 # print "=>",tgt #dbg
2576 # print "=>",tgt #dbg
2715 if callable(tgt):
2577 if callable(tgt):
2716 if '$' in line_info.line:
2578 if '$' in line_info.line:
2717 call_meth = '(_ip, _ip.var_expand(%s))'
2579 call_meth = '(_ip, _ip.var_expand(%s))'
2718 else:
2580 else:
2719 call_meth = '(_ip,%s)'
2581 call_meth = '(_ip,%s)'
2720 line_out = ("%s_sh.%s" + call_meth) % (line_info.preWhitespace,
2582 line_out = ("%s_sh.%s" + call_meth) % (line_info.preWhitespace,
2721 line_info.iFun,
2583 line_info.iFun,
2722 make_quoted_expr(line_info.line))
2584 make_quoted_expr(line_info.line))
2723 else:
2585 else:
2724 transformed = self.expand_aliases(line_info.iFun,line_info.theRest)
2586 transformed = self.expand_aliases(line_info.iFun,line_info.theRest)
2725
2587
2726 # pre is needed, because it carries the leading whitespace. Otherwise
2588 # pre is needed, because it carries the leading whitespace. Otherwise
2727 # aliases won't work in indented sections.
2589 # aliases won't work in indented sections.
2728 line_out = '%s_ip.system(%s)' % (line_info.preWhitespace,
2590 line_out = '%s_ip.system(%s)' % (line_info.preWhitespace,
2729 make_quoted_expr( transformed ))
2591 make_quoted_expr( transformed ))
2730
2592
2731 self.log(line_info.line,line_out,line_info.continue_prompt)
2593 self.log(line_info.line,line_out,line_info.continue_prompt)
2732 #print 'line out:',line_out # dbg
2594 #print 'line out:',line_out # dbg
2733 return line_out
2595 return line_out
2734
2596
2735 def handle_shell_escape(self, line_info):
2597 def handle_shell_escape(self, line_info):
2736 """Execute the line in a shell, empty return value"""
2598 """Execute the line in a shell, empty return value"""
2737 #print 'line in :', `line` # dbg
2599 #print 'line in :', `line` # dbg
2738 line = line_info.line
2600 line = line_info.line
2739 if line.lstrip().startswith('!!'):
2601 if line.lstrip().startswith('!!'):
2740 # rewrite LineInfo's line, iFun and theRest to properly hold the
2602 # rewrite LineInfo's line, iFun and theRest to properly hold the
2741 # call to %sx and the actual command to be executed, so
2603 # call to %sx and the actual command to be executed, so
2742 # handle_magic can work correctly. Note that this works even if
2604 # handle_magic can work correctly. Note that this works even if
2743 # the line is indented, so it handles multi_line_specials
2605 # the line is indented, so it handles multi_line_specials
2744 # properly.
2606 # properly.
2745 new_rest = line.lstrip()[2:]
2607 new_rest = line.lstrip()[2:]
2746 line_info.line = '%ssx %s' % (self.ESC_MAGIC,new_rest)
2608 line_info.line = '%ssx %s' % (self.ESC_MAGIC,new_rest)
2747 line_info.iFun = 'sx'
2609 line_info.iFun = 'sx'
2748 line_info.theRest = new_rest
2610 line_info.theRest = new_rest
2749 return self.handle_magic(line_info)
2611 return self.handle_magic(line_info)
2750 else:
2612 else:
2751 cmd = line.lstrip().lstrip('!')
2613 cmd = line.lstrip().lstrip('!')
2752 line_out = '%s_ip.system(%s)' % (line_info.preWhitespace,
2614 line_out = '%s_ip.system(%s)' % (line_info.preWhitespace,
2753 make_quoted_expr(cmd))
2615 make_quoted_expr(cmd))
2754 # update cache/log and return
2616 # update cache/log and return
2755 self.log(line,line_out,line_info.continue_prompt)
2617 self.log(line,line_out,line_info.continue_prompt)
2756 return line_out
2618 return line_out
2757
2619
2758 def handle_magic(self, line_info):
2620 def handle_magic(self, line_info):
2759 """Execute magic functions."""
2621 """Execute magic functions."""
2760 iFun = line_info.iFun
2622 iFun = line_info.iFun
2761 theRest = line_info.theRest
2623 theRest = line_info.theRest
2762 cmd = '%s_ip.magic(%s)' % (line_info.preWhitespace,
2624 cmd = '%s_ip.magic(%s)' % (line_info.preWhitespace,
2763 make_quoted_expr(iFun + " " + theRest))
2625 make_quoted_expr(iFun + " " + theRest))
2764 self.log(line_info.line,cmd,line_info.continue_prompt)
2626 self.log(line_info.line,cmd,line_info.continue_prompt)
2765 #print 'in handle_magic, cmd=<%s>' % cmd # dbg
2627 #print 'in handle_magic, cmd=<%s>' % cmd # dbg
2766 return cmd
2628 return cmd
2767
2629
2768 def handle_auto(self, line_info):
2630 def handle_auto(self, line_info):
2769 """Hande lines which can be auto-executed, quoting if requested."""
2631 """Hande lines which can be auto-executed, quoting if requested."""
2770
2632
2771 line = line_info.line
2633 line = line_info.line
2772 iFun = line_info.iFun
2634 iFun = line_info.iFun
2773 theRest = line_info.theRest
2635 theRest = line_info.theRest
2774 pre = line_info.pre
2636 pre = line_info.pre
2775 continue_prompt = line_info.continue_prompt
2637 continue_prompt = line_info.continue_prompt
2776 obj = line_info.ofind(self)['obj']
2638 obj = line_info.ofind(self)['obj']
2777
2639
2778 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
2640 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
2779
2641
2780 # This should only be active for single-line input!
2642 # This should only be active for single-line input!
2781 if continue_prompt:
2643 if continue_prompt:
2782 self.log(line,line,continue_prompt)
2644 self.log(line,line,continue_prompt)
2783 return line
2645 return line
2784
2646
2785 force_auto = isinstance(obj, IPyAutocall)
2647 force_auto = isinstance(obj, IPyAutocall)
2786 auto_rewrite = True
2648 auto_rewrite = True
2787
2649
2788 if pre == self.ESC_QUOTE:
2650 if pre == self.ESC_QUOTE:
2789 # Auto-quote splitting on whitespace
2651 # Auto-quote splitting on whitespace
2790 newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) )
2652 newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) )
2791 elif pre == self.ESC_QUOTE2:
2653 elif pre == self.ESC_QUOTE2:
2792 # Auto-quote whole string
2654 # Auto-quote whole string
2793 newcmd = '%s("%s")' % (iFun,theRest)
2655 newcmd = '%s("%s")' % (iFun,theRest)
2794 elif pre == self.ESC_PAREN:
2656 elif pre == self.ESC_PAREN:
2795 newcmd = '%s(%s)' % (iFun,",".join(theRest.split()))
2657 newcmd = '%s(%s)' % (iFun,",".join(theRest.split()))
2796 else:
2658 else:
2797 # Auto-paren.
2659 # Auto-paren.
2798 # We only apply it to argument-less calls if the autocall
2660 # We only apply it to argument-less calls if the autocall
2799 # parameter is set to 2. We only need to check that autocall is <
2661 # parameter is set to 2. We only need to check that autocall is <
2800 # 2, since this function isn't called unless it's at least 1.
2662 # 2, since this function isn't called unless it's at least 1.
2801 if not theRest and (self.autocall < 2) and not force_auto:
2663 if not theRest and (self.autocall < 2) and not force_auto:
2802 newcmd = '%s %s' % (iFun,theRest)
2664 newcmd = '%s %s' % (iFun,theRest)
2803 auto_rewrite = False
2665 auto_rewrite = False
2804 else:
2666 else:
2805 if not force_auto and theRest.startswith('['):
2667 if not force_auto and theRest.startswith('['):
2806 if hasattr(obj,'__getitem__'):
2668 if hasattr(obj,'__getitem__'):
2807 # Don't autocall in this case: item access for an object
2669 # Don't autocall in this case: item access for an object
2808 # which is BOTH callable and implements __getitem__.
2670 # which is BOTH callable and implements __getitem__.
2809 newcmd = '%s %s' % (iFun,theRest)
2671 newcmd = '%s %s' % (iFun,theRest)
2810 auto_rewrite = False
2672 auto_rewrite = False
2811 else:
2673 else:
2812 # if the object doesn't support [] access, go ahead and
2674 # if the object doesn't support [] access, go ahead and
2813 # autocall
2675 # autocall
2814 newcmd = '%s(%s)' % (iFun.rstrip(),theRest)
2676 newcmd = '%s(%s)' % (iFun.rstrip(),theRest)
2815 elif theRest.endswith(';'):
2677 elif theRest.endswith(';'):
2816 newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1])
2678 newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1])
2817 else:
2679 else:
2818 newcmd = '%s(%s)' % (iFun.rstrip(), theRest)
2680 newcmd = '%s(%s)' % (iFun.rstrip(), theRest)
2819
2681
2820 if auto_rewrite:
2682 if auto_rewrite:
2821 rw = self.outputcache.prompt1.auto_rewrite() + newcmd
2683 rw = self.outputcache.prompt1.auto_rewrite() + newcmd
2822
2684
2823 try:
2685 try:
2824 # plain ascii works better w/ pyreadline, on some machines, so
2686 # plain ascii works better w/ pyreadline, on some machines, so
2825 # we use it and only print uncolored rewrite if we have unicode
2687 # we use it and only print uncolored rewrite if we have unicode
2826 rw = str(rw)
2688 rw = str(rw)
2827 print >>Term.cout, rw
2689 print >>Term.cout, rw
2828 except UnicodeEncodeError:
2690 except UnicodeEncodeError:
2829 print "-------------->" + newcmd
2691 print "-------------->" + newcmd
2830
2692
2831 # log what is now valid Python, not the actual user input (without the
2693 # log what is now valid Python, not the actual user input (without the
2832 # final newline)
2694 # final newline)
2833 self.log(line,newcmd,continue_prompt)
2695 self.log(line,newcmd,continue_prompt)
2834 return newcmd
2696 return newcmd
2835
2697
2836 def handle_help(self, line_info):
2698 def handle_help(self, line_info):
2837 """Try to get some help for the object.
2699 """Try to get some help for the object.
2838
2700
2839 obj? or ?obj -> basic information.
2701 obj? or ?obj -> basic information.
2840 obj?? or ??obj -> more details.
2702 obj?? or ??obj -> more details.
2841 """
2703 """
2842
2704
2843 line = line_info.line
2705 line = line_info.line
2844 # We need to make sure that we don't process lines which would be
2706 # We need to make sure that we don't process lines which would be
2845 # otherwise valid python, such as "x=1 # what?"
2707 # otherwise valid python, such as "x=1 # what?"
2846 try:
2708 try:
2847 codeop.compile_command(line)
2709 codeop.compile_command(line)
2848 except SyntaxError:
2710 except SyntaxError:
2849 # We should only handle as help stuff which is NOT valid syntax
2711 # We should only handle as help stuff which is NOT valid syntax
2850 if line[0]==self.ESC_HELP:
2712 if line[0]==self.ESC_HELP:
2851 line = line[1:]
2713 line = line[1:]
2852 elif line[-1]==self.ESC_HELP:
2714 elif line[-1]==self.ESC_HELP:
2853 line = line[:-1]
2715 line = line[:-1]
2854 self.log(line,'#?'+line,line_info.continue_prompt)
2716 self.log(line,'#?'+line,line_info.continue_prompt)
2855 if line:
2717 if line:
2856 #print 'line:<%r>' % line # dbg
2718 #print 'line:<%r>' % line # dbg
2857 self.magic_pinfo(line)
2719 self.magic_pinfo(line)
2858 else:
2720 else:
2859 page(self.usage,screen_lines=self.usable_screen_length)
2721 page(self.usage,screen_lines=self.usable_screen_length)
2860 return '' # Empty string is needed here!
2722 return '' # Empty string is needed here!
2861 except:
2723 except:
2862 # Pass any other exceptions through to the normal handler
2724 # Pass any other exceptions through to the normal handler
2863 return self.handle_normal(line_info)
2725 return self.handle_normal(line_info)
2864 else:
2726 else:
2865 # If the code compiles ok, we should handle it normally
2727 # If the code compiles ok, we should handle it normally
2866 return self.handle_normal(line_info)
2728 return self.handle_normal(line_info)
2867
2729
2868 def handle_emacs(self, line_info):
2730 def handle_emacs(self, line_info):
2869 """Handle input lines marked by python-mode."""
2731 """Handle input lines marked by python-mode."""
2870
2732
2871 # Currently, nothing is done. Later more functionality can be added
2733 # Currently, nothing is done. Later more functionality can be added
2872 # here if needed.
2734 # here if needed.
2873
2735
2874 # The input cache shouldn't be updated
2736 # The input cache shouldn't be updated
2875 return line_info.line
2737 return line_info.line
2876
2738
2877 def var_expand(self,cmd,depth=0):
2739 def var_expand(self,cmd,depth=0):
2878 """Expand python variables in a string.
2740 """Expand python variables in a string.
2879
2741
2880 The depth argument indicates how many frames above the caller should
2742 The depth argument indicates how many frames above the caller should
2881 be walked to look for the local namespace where to expand variables.
2743 be walked to look for the local namespace where to expand variables.
2882
2744
2883 The global namespace for expansion is always the user's interactive
2745 The global namespace for expansion is always the user's interactive
2884 namespace.
2746 namespace.
2885 """
2747 """
2886
2748
2887 return str(ItplNS(cmd,
2749 return str(ItplNS(cmd,
2888 self.user_ns, # globals
2750 self.user_ns, # globals
2889 # Skip our own frame in searching for locals:
2751 # Skip our own frame in searching for locals:
2890 sys._getframe(depth+1).f_locals # locals
2752 sys._getframe(depth+1).f_locals # locals
2891 ))
2753 ))
2892
2754
2893 def mktempfile(self,data=None):
2755 def mktempfile(self,data=None):
2894 """Make a new tempfile and return its filename.
2756 """Make a new tempfile and return its filename.
2895
2757
2896 This makes a call to tempfile.mktemp, but it registers the created
2758 This makes a call to tempfile.mktemp, but it registers the created
2897 filename internally so ipython cleans it up at exit time.
2759 filename internally so ipython cleans it up at exit time.
2898
2760
2899 Optional inputs:
2761 Optional inputs:
2900
2762
2901 - data(None): if data is given, it gets written out to the temp file
2763 - data(None): if data is given, it gets written out to the temp file
2902 immediately, and the file is closed again."""
2764 immediately, and the file is closed again."""
2903
2765
2904 filename = tempfile.mktemp('.py','ipython_edit_')
2766 filename = tempfile.mktemp('.py','ipython_edit_')
2905 self.tempfiles.append(filename)
2767 self.tempfiles.append(filename)
2906
2768
2907 if data:
2769 if data:
2908 tmp_file = open(filename,'w')
2770 tmp_file = open(filename,'w')
2909 tmp_file.write(data)
2771 tmp_file.write(data)
2910 tmp_file.close()
2772 tmp_file.close()
2911 return filename
2773 return filename
2912
2774
2913 def write(self,data):
2775 def write(self,data):
2914 """Write a string to the default output"""
2776 """Write a string to the default output"""
2915 Term.cout.write(data)
2777 Term.cout.write(data)
2916
2778
2917 def write_err(self,data):
2779 def write_err(self,data):
2918 """Write a string to the default error output"""
2780 """Write a string to the default error output"""
2919 Term.cerr.write(data)
2781 Term.cerr.write(data)
2920
2782
2921 def ask_exit(self):
2783 def ask_exit(self):
2922 """ Call for exiting. Can be overiden and used as a callback. """
2784 """ Call for exiting. Can be overiden and used as a callback. """
2923 self.exit_now = True
2785 self.exit_now = True
2924
2786
2925 def exit(self):
2787 def exit(self):
2926 """Handle interactive exit.
2788 """Handle interactive exit.
2927
2789
2928 This method calls the ask_exit callback."""
2790 This method calls the ask_exit callback."""
2929 if self.confirm_exit:
2791 if self.confirm_exit:
2930 if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'):
2792 if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'):
2931 self.ask_exit()
2793 self.ask_exit()
2932 else:
2794 else:
2933 self.ask_exit()
2795 self.ask_exit()
2934
2796
2935 def safe_execfile(self,fname,*where,**kw):
2797 def safe_execfile(self,fname,*where,**kw):
2936 """A safe version of the builtin execfile().
2798 """A safe version of the builtin execfile().
2937
2799
2938 This version will never throw an exception, and knows how to handle
2800 This version will never throw an exception, and knows how to handle
2939 ipython logs as well.
2801 ipython logs as well.
2940
2802
2941 :Parameters:
2803 :Parameters:
2942 fname : string
2804 fname : string
2943 Name of the file to be executed.
2805 Name of the file to be executed.
2944
2806
2945 where : tuple
2807 where : tuple
2946 One or two namespaces, passed to execfile() as (globals,locals).
2808 One or two namespaces, passed to execfile() as (globals,locals).
2947 If only one is given, it is passed as both.
2809 If only one is given, it is passed as both.
2948
2810
2949 :Keywords:
2811 :Keywords:
2950 islog : boolean (False)
2812 islog : boolean (False)
2951
2813
2952 quiet : boolean (True)
2814 quiet : boolean (True)
2953
2815
2954 exit_ignore : boolean (False)
2816 exit_ignore : boolean (False)
2955 """
2817 """
2956
2818
2957 def syspath_cleanup():
2819 def syspath_cleanup():
2958 """Internal cleanup routine for sys.path."""
2820 """Internal cleanup routine for sys.path."""
2959 if add_dname:
2821 if add_dname:
2960 try:
2822 try:
2961 sys.path.remove(dname)
2823 sys.path.remove(dname)
2962 except ValueError:
2824 except ValueError:
2963 # For some reason the user has already removed it, ignore.
2825 # For some reason the user has already removed it, ignore.
2964 pass
2826 pass
2965
2827
2966 fname = os.path.expanduser(fname)
2828 fname = os.path.expanduser(fname)
2967
2829
2968 # Find things also in current directory. This is needed to mimic the
2830 # Find things also in current directory. This is needed to mimic the
2969 # behavior of running a script from the system command line, where
2831 # behavior of running a script from the system command line, where
2970 # Python inserts the script's directory into sys.path
2832 # Python inserts the script's directory into sys.path
2971 dname = os.path.dirname(os.path.abspath(fname))
2833 dname = os.path.dirname(os.path.abspath(fname))
2972 add_dname = False
2834 add_dname = False
2973 if dname not in sys.path:
2835 if dname not in sys.path:
2974 sys.path.insert(0,dname)
2836 sys.path.insert(0,dname)
2975 add_dname = True
2837 add_dname = True
2976
2838
2977 try:
2839 try:
2978 xfile = open(fname)
2840 xfile = open(fname)
2979 except:
2841 except:
2980 print >> Term.cerr, \
2842 print >> Term.cerr, \
2981 'Could not open file <%s> for safe execution.' % fname
2843 'Could not open file <%s> for safe execution.' % fname
2982 syspath_cleanup()
2844 syspath_cleanup()
2983 return None
2845 return None
2984
2846
2985 kw.setdefault('islog',0)
2847 kw.setdefault('islog',0)
2986 kw.setdefault('quiet',1)
2848 kw.setdefault('quiet',1)
2987 kw.setdefault('exit_ignore',0)
2849 kw.setdefault('exit_ignore',0)
2988
2850
2989 first = xfile.readline()
2851 first = xfile.readline()
2990 loghead = str(self.loghead_tpl).split('\n',1)[0].strip()
2852 loghead = str(self.loghead_tpl).split('\n',1)[0].strip()
2991 xfile.close()
2853 xfile.close()
2992 # line by line execution
2854 # line by line execution
2993 if first.startswith(loghead) or kw['islog']:
2855 if first.startswith(loghead) or kw['islog']:
2994 print 'Loading log file <%s> one line at a time...' % fname
2856 print 'Loading log file <%s> one line at a time...' % fname
2995 if kw['quiet']:
2857 if kw['quiet']:
2996 stdout_save = sys.stdout
2858 stdout_save = sys.stdout
2997 sys.stdout = StringIO.StringIO()
2859 sys.stdout = StringIO.StringIO()
2998 try:
2860 try:
2999 globs,locs = where[0:2]
2861 globs,locs = where[0:2]
3000 except:
2862 except:
3001 try:
2863 try:
3002 globs = locs = where[0]
2864 globs = locs = where[0]
3003 except:
2865 except:
3004 globs = locs = globals()
2866 globs = locs = globals()
3005 badblocks = []
2867 badblocks = []
3006
2868
3007 # we also need to identify indented blocks of code when replaying
2869 # we also need to identify indented blocks of code when replaying
3008 # logs and put them together before passing them to an exec
2870 # logs and put them together before passing them to an exec
3009 # statement. This takes a bit of regexp and look-ahead work in the
2871 # statement. This takes a bit of regexp and look-ahead work in the
3010 # file. It's easiest if we swallow the whole thing in memory
2872 # file. It's easiest if we swallow the whole thing in memory
3011 # first, and manually walk through the lines list moving the
2873 # first, and manually walk through the lines list moving the
3012 # counter ourselves.
2874 # counter ourselves.
3013 indent_re = re.compile('\s+\S')
2875 indent_re = re.compile('\s+\S')
3014 xfile = open(fname)
2876 xfile = open(fname)
3015 filelines = xfile.readlines()
2877 filelines = xfile.readlines()
3016 xfile.close()
2878 xfile.close()
3017 nlines = len(filelines)
2879 nlines = len(filelines)
3018 lnum = 0
2880 lnum = 0
3019 while lnum < nlines:
2881 while lnum < nlines:
3020 line = filelines[lnum]
2882 line = filelines[lnum]
3021 lnum += 1
2883 lnum += 1
3022 # don't re-insert logger status info into cache
2884 # don't re-insert logger status info into cache
3023 if line.startswith('#log#'):
2885 if line.startswith('#log#'):
3024 continue
2886 continue
3025 else:
2887 else:
3026 # build a block of code (maybe a single line) for execution
2888 # build a block of code (maybe a single line) for execution
3027 block = line
2889 block = line
3028 try:
2890 try:
3029 next = filelines[lnum] # lnum has already incremented
2891 next = filelines[lnum] # lnum has already incremented
3030 except:
2892 except:
3031 next = None
2893 next = None
3032 while next and indent_re.match(next):
2894 while next and indent_re.match(next):
3033 block += next
2895 block += next
3034 lnum += 1
2896 lnum += 1
3035 try:
2897 try:
3036 next = filelines[lnum]
2898 next = filelines[lnum]
3037 except:
2899 except:
3038 next = None
2900 next = None
3039 # now execute the block of one or more lines
2901 # now execute the block of one or more lines
3040 try:
2902 try:
3041 exec block in globs,locs
2903 exec block in globs,locs
3042 except SystemExit:
2904 except SystemExit:
3043 pass
2905 pass
3044 except:
2906 except:
3045 badblocks.append(block.rstrip())
2907 badblocks.append(block.rstrip())
3046 if kw['quiet']: # restore stdout
2908 if kw['quiet']: # restore stdout
3047 sys.stdout.close()
2909 sys.stdout.close()
3048 sys.stdout = stdout_save
2910 sys.stdout = stdout_save
3049 print 'Finished replaying log file <%s>' % fname
2911 print 'Finished replaying log file <%s>' % fname
3050 if badblocks:
2912 if badblocks:
3051 print >> sys.stderr, ('\nThe following lines/blocks in file '
2913 print >> sys.stderr, ('\nThe following lines/blocks in file '
3052 '<%s> reported errors:' % fname)
2914 '<%s> reported errors:' % fname)
3053
2915
3054 for badline in badblocks:
2916 for badline in badblocks:
3055 print >> sys.stderr, badline
2917 print >> sys.stderr, badline
3056 else: # regular file execution
2918 else: # regular file execution
3057 try:
2919 try:
3058 if sys.platform == 'win32' and sys.version_info < (2,5,1):
2920 if sys.platform == 'win32' and sys.version_info < (2,5,1):
3059 # Work around a bug in Python for Windows. The bug was
2921 # Work around a bug in Python for Windows. The bug was
3060 # fixed in in Python 2.5 r54159 and 54158, but that's still
2922 # fixed in in Python 2.5 r54159 and 54158, but that's still
3061 # SVN Python as of March/07. For details, see:
2923 # SVN Python as of March/07. For details, see:
3062 # http://projects.scipy.org/ipython/ipython/ticket/123
2924 # http://projects.scipy.org/ipython/ipython/ticket/123
3063 try:
2925 try:
3064 globs,locs = where[0:2]
2926 globs,locs = where[0:2]
3065 except:
2927 except:
3066 try:
2928 try:
3067 globs = locs = where[0]
2929 globs = locs = where[0]
3068 except:
2930 except:
3069 globs = locs = globals()
2931 globs = locs = globals()
3070 exec file(fname) in globs,locs
2932 exec file(fname) in globs,locs
3071 else:
2933 else:
3072 execfile(fname,*where)
2934 execfile(fname,*where)
3073 except SyntaxError:
2935 except SyntaxError:
3074 self.showsyntaxerror()
2936 self.showsyntaxerror()
3075 warn('Failure executing file: <%s>' % fname)
2937 warn('Failure executing file: <%s>' % fname)
3076 except SystemExit,status:
2938 except SystemExit,status:
3077 # Code that correctly sets the exit status flag to success (0)
2939 # Code that correctly sets the exit status flag to success (0)
3078 # shouldn't be bothered with a traceback. Note that a plain
2940 # shouldn't be bothered with a traceback. Note that a plain
3079 # sys.exit() does NOT set the message to 0 (it's empty) so that
2941 # sys.exit() does NOT set the message to 0 (it's empty) so that
3080 # will still get a traceback. Note that the structure of the
2942 # will still get a traceback. Note that the structure of the
3081 # SystemExit exception changed between Python 2.4 and 2.5, so
2943 # SystemExit exception changed between Python 2.4 and 2.5, so
3082 # the checks must be done in a version-dependent way.
2944 # the checks must be done in a version-dependent way.
3083 show = False
2945 show = False
3084
2946
3085 if sys.version_info[:2] > (2,5):
2947 if sys.version_info[:2] > (2,5):
3086 if status.message!=0 and not kw['exit_ignore']:
2948 if status.message!=0 and not kw['exit_ignore']:
3087 show = True
2949 show = True
3088 else:
2950 else:
3089 if status.code and not kw['exit_ignore']:
2951 if status.code and not kw['exit_ignore']:
3090 show = True
2952 show = True
3091 if show:
2953 if show:
3092 self.showtraceback()
2954 self.showtraceback()
3093 warn('Failure executing file: <%s>' % fname)
2955 warn('Failure executing file: <%s>' % fname)
3094 except:
2956 except:
3095 self.showtraceback()
2957 self.showtraceback()
3096 warn('Failure executing file: <%s>' % fname)
2958 warn('Failure executing file: <%s>' % fname)
3097
2959
3098 syspath_cleanup()
2960 syspath_cleanup()
3099
2961
3100 #************************* end of file <iplib.py> *****************************
2962 #************************* end of file <iplib.py> *****************************
General Comments 0
You need to be logged in to leave comments. Login now