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