##// END OF EJS Templates
Merge branch 'cleanup-old-code' of http://github.com/takowl/ipython into takowl-cleanup-old-code...
Fernando Perez -
r3180:59ccc837 merge
parent child Browse files
Show More
@@ -1,2542 +1,2537 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Main IPython class."""
2 """Main IPython class."""
3
3
4 #-----------------------------------------------------------------------------
4 #-----------------------------------------------------------------------------
5 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
5 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
6 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
6 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
7 # Copyright (C) 2008-2010 The IPython Development Team
7 # Copyright (C) 2008-2010 The IPython Development Team
8 #
8 #
9 # Distributed under the terms of the BSD License. The full license is in
9 # Distributed under the terms of the BSD License. The full license is in
10 # the file COPYING, distributed as part of this software.
10 # the file COPYING, distributed as part of this software.
11 #-----------------------------------------------------------------------------
11 #-----------------------------------------------------------------------------
12
12
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14 # Imports
14 # Imports
15 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
16
16
17 from __future__ import with_statement
17 from __future__ import with_statement
18 from __future__ import absolute_import
18 from __future__ import absolute_import
19
19
20 import __builtin__
20 import __builtin__
21 import __future__
21 import __future__
22 import abc
22 import abc
23 import atexit
23 import atexit
24 import codeop
24 import codeop
25 import exceptions
26 import new
27 import os
25 import os
28 import re
26 import re
29 import string
30 import sys
27 import sys
31 import tempfile
28 import tempfile
29 import types
32 from contextlib import nested
30 from contextlib import nested
33
31
34 from IPython.config.configurable import Configurable
32 from IPython.config.configurable import Configurable
35 from IPython.core import debugger, oinspect
33 from IPython.core import debugger, oinspect
36 from IPython.core import history as ipcorehist
34 from IPython.core import history as ipcorehist
37 from IPython.core import page
35 from IPython.core import page
38 from IPython.core import prefilter
36 from IPython.core import prefilter
39 from IPython.core import shadowns
37 from IPython.core import shadowns
40 from IPython.core import ultratb
38 from IPython.core import ultratb
41 from IPython.core.alias import AliasManager
39 from IPython.core.alias import AliasManager
42 from IPython.core.builtin_trap import BuiltinTrap
40 from IPython.core.builtin_trap import BuiltinTrap
43 from IPython.core.compilerop import CachingCompiler
41 from IPython.core.compilerop import CachingCompiler
44 from IPython.core.display_trap import DisplayTrap
42 from IPython.core.display_trap import DisplayTrap
45 from IPython.core.displayhook import DisplayHook
43 from IPython.core.displayhook import DisplayHook
46 from IPython.core.error import TryNext, UsageError
44 from IPython.core.error import TryNext, UsageError
47 from IPython.core.extensions import ExtensionManager
45 from IPython.core.extensions import ExtensionManager
48 from IPython.core.fakemodule import FakeModule, init_fakemod_dict
46 from IPython.core.fakemodule import FakeModule, init_fakemod_dict
49 from IPython.core.history import HistoryManager
47 from IPython.core.history import HistoryManager
50 from IPython.core.inputlist import InputList
48 from IPython.core.inputlist import InputList
51 from IPython.core.inputsplitter import IPythonInputSplitter
49 from IPython.core.inputsplitter import IPythonInputSplitter
52 from IPython.core.logger import Logger
50 from IPython.core.logger import Logger
53 from IPython.core.magic import Magic
51 from IPython.core.magic import Magic
54 from IPython.core.payload import PayloadManager
52 from IPython.core.payload import PayloadManager
55 from IPython.core.plugin import PluginManager
53 from IPython.core.plugin import PluginManager
56 from IPython.core.prefilter import PrefilterManager, ESC_MAGIC
54 from IPython.core.prefilter import PrefilterManager, ESC_MAGIC
57 from IPython.external.Itpl import ItplNS
55 from IPython.external.Itpl import ItplNS
58 from IPython.utils import PyColorize
56 from IPython.utils import PyColorize
59 from IPython.utils import io
57 from IPython.utils import io
60 from IPython.utils import pickleshare
58 from IPython.utils import pickleshare
61 from IPython.utils.doctestreload import doctest_reload
59 from IPython.utils.doctestreload import doctest_reload
62 from IPython.utils.io import ask_yes_no, rprint
60 from IPython.utils.io import ask_yes_no, rprint
63 from IPython.utils.ipstruct import Struct
61 from IPython.utils.ipstruct import Struct
64 from IPython.utils.path import get_home_dir, get_ipython_dir, HomeDirError
62 from IPython.utils.path import get_home_dir, get_ipython_dir, HomeDirError
65 from IPython.utils.process import system, getoutput
63 from IPython.utils.process import system, getoutput
66 from IPython.utils.strdispatch import StrDispatch
64 from IPython.utils.strdispatch import StrDispatch
67 from IPython.utils.syspathcontext import prepended_to_syspath
65 from IPython.utils.syspathcontext import prepended_to_syspath
68 from IPython.utils.text import num_ini_spaces, format_screen, LSString, SList
66 from IPython.utils.text import num_ini_spaces, format_screen, LSString, SList
69 from IPython.utils.traitlets import (Int, Str, CBool, CaselessStrEnum, Enum,
67 from IPython.utils.traitlets import (Int, Str, CBool, CaselessStrEnum, Enum,
70 List, Unicode, Instance, Type)
68 List, Unicode, Instance, Type)
71 from IPython.utils.warn import warn, error, fatal
69 from IPython.utils.warn import warn, error, fatal
72 import IPython.core.hooks
70 import IPython.core.hooks
73
71
74 #-----------------------------------------------------------------------------
72 #-----------------------------------------------------------------------------
75 # Globals
73 # Globals
76 #-----------------------------------------------------------------------------
74 #-----------------------------------------------------------------------------
77
75
78 # compiled regexps for autoindent management
76 # compiled regexps for autoindent management
79 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
77 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
80
78
81 #-----------------------------------------------------------------------------
79 #-----------------------------------------------------------------------------
82 # Utilities
80 # Utilities
83 #-----------------------------------------------------------------------------
81 #-----------------------------------------------------------------------------
84
82
85 # store the builtin raw_input globally, and use this always, in case user code
83 # store the builtin raw_input globally, and use this always, in case user code
86 # overwrites it (like wx.py.PyShell does)
84 # overwrites it (like wx.py.PyShell does)
87 raw_input_original = raw_input
85 raw_input_original = raw_input
88
86
89 def softspace(file, newvalue):
87 def softspace(file, newvalue):
90 """Copied from code.py, to remove the dependency"""
88 """Copied from code.py, to remove the dependency"""
91
89
92 oldvalue = 0
90 oldvalue = 0
93 try:
91 try:
94 oldvalue = file.softspace
92 oldvalue = file.softspace
95 except AttributeError:
93 except AttributeError:
96 pass
94 pass
97 try:
95 try:
98 file.softspace = newvalue
96 file.softspace = newvalue
99 except (AttributeError, TypeError):
97 except (AttributeError, TypeError):
100 # "attribute-less object" or "read-only attributes"
98 # "attribute-less object" or "read-only attributes"
101 pass
99 pass
102 return oldvalue
100 return oldvalue
103
101
104
102
105 def no_op(*a, **kw): pass
103 def no_op(*a, **kw): pass
106
104
107 class SpaceInInput(exceptions.Exception): pass
105 class SpaceInInput(Exception): pass
108
106
109 class Bunch: pass
107 class Bunch: pass
110
108
111
109
112 def get_default_colors():
110 def get_default_colors():
113 if sys.platform=='darwin':
111 if sys.platform=='darwin':
114 return "LightBG"
112 return "LightBG"
115 elif os.name=='nt':
113 elif os.name=='nt':
116 return 'Linux'
114 return 'Linux'
117 else:
115 else:
118 return 'Linux'
116 return 'Linux'
119
117
120
118
121 class SeparateStr(Str):
119 class SeparateStr(Str):
122 """A Str subclass to validate separate_in, separate_out, etc.
120 """A Str subclass to validate separate_in, separate_out, etc.
123
121
124 This is a Str based trait that converts '0'->'' and '\\n'->'\n'.
122 This is a Str based trait that converts '0'->'' and '\\n'->'\n'.
125 """
123 """
126
124
127 def validate(self, obj, value):
125 def validate(self, obj, value):
128 if value == '0': value = ''
126 if value == '0': value = ''
129 value = value.replace('\\n','\n')
127 value = value.replace('\\n','\n')
130 return super(SeparateStr, self).validate(obj, value)
128 return super(SeparateStr, self).validate(obj, value)
131
129
132 class MultipleInstanceError(Exception):
130 class MultipleInstanceError(Exception):
133 pass
131 pass
134
132
135
133
136 #-----------------------------------------------------------------------------
134 #-----------------------------------------------------------------------------
137 # Main IPython class
135 # Main IPython class
138 #-----------------------------------------------------------------------------
136 #-----------------------------------------------------------------------------
139
137
140 class InteractiveShell(Configurable, Magic):
138 class InteractiveShell(Configurable, Magic):
141 """An enhanced, interactive shell for Python."""
139 """An enhanced, interactive shell for Python."""
142
140
143 _instance = None
141 _instance = None
144 autocall = Enum((0,1,2), default_value=1, config=True)
142 autocall = Enum((0,1,2), default_value=1, config=True)
145 # TODO: remove all autoindent logic and put into frontends.
143 # TODO: remove all autoindent logic and put into frontends.
146 # We can't do this yet because even runlines uses the autoindent.
144 # We can't do this yet because even runlines uses the autoindent.
147 autoindent = CBool(True, config=True)
145 autoindent = CBool(True, config=True)
148 automagic = CBool(True, config=True)
146 automagic = CBool(True, config=True)
149 cache_size = Int(1000, config=True)
147 cache_size = Int(1000, config=True)
150 color_info = CBool(True, config=True)
148 color_info = CBool(True, config=True)
151 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
149 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
152 default_value=get_default_colors(), config=True)
150 default_value=get_default_colors(), config=True)
153 debug = CBool(False, config=True)
151 debug = CBool(False, config=True)
154 deep_reload = CBool(False, config=True)
152 deep_reload = CBool(False, config=True)
155 displayhook_class = Type(DisplayHook)
153 displayhook_class = Type(DisplayHook)
156 exit_now = CBool(False)
154 exit_now = CBool(False)
157 # Monotonically increasing execution counter
155 # Monotonically increasing execution counter
158 execution_count = Int(1)
156 execution_count = Int(1)
159 filename = Str("<ipython console>")
157 filename = Str("<ipython console>")
160 ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__
158 ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__
161
159
162 # Input splitter, to split entire cells of input into either individual
160 # Input splitter, to split entire cells of input into either individual
163 # interactive statements or whole blocks.
161 # interactive statements or whole blocks.
164 input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
162 input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
165 (), {})
163 (), {})
166 logstart = CBool(False, config=True)
164 logstart = CBool(False, config=True)
167 logfile = Str('', config=True)
165 logfile = Str('', config=True)
168 logappend = Str('', config=True)
166 logappend = Str('', config=True)
169 object_info_string_level = Enum((0,1,2), default_value=0,
167 object_info_string_level = Enum((0,1,2), default_value=0,
170 config=True)
168 config=True)
171 pdb = CBool(False, config=True)
169 pdb = CBool(False, config=True)
172
170
173 pprint = CBool(True, config=True)
171 pprint = CBool(True, config=True)
174 profile = Str('', config=True)
172 profile = Str('', config=True)
175 prompt_in1 = Str('In [\\#]: ', config=True)
173 prompt_in1 = Str('In [\\#]: ', config=True)
176 prompt_in2 = Str(' .\\D.: ', config=True)
174 prompt_in2 = Str(' .\\D.: ', config=True)
177 prompt_out = Str('Out[\\#]: ', config=True)
175 prompt_out = Str('Out[\\#]: ', config=True)
178 prompts_pad_left = CBool(True, config=True)
176 prompts_pad_left = CBool(True, config=True)
179 quiet = CBool(False, config=True)
177 quiet = CBool(False, config=True)
180
178
181 # The readline stuff will eventually be moved to the terminal subclass
179 # The readline stuff will eventually be moved to the terminal subclass
182 # but for now, we can't do that as readline is welded in everywhere.
180 # but for now, we can't do that as readline is welded in everywhere.
183 readline_use = CBool(True, config=True)
181 readline_use = CBool(True, config=True)
184 readline_merge_completions = CBool(True, config=True)
182 readline_merge_completions = CBool(True, config=True)
185 readline_omit__names = Enum((0,1,2), default_value=0, config=True)
183 readline_omit__names = Enum((0,1,2), default_value=0, config=True)
186 readline_remove_delims = Str('-/~', config=True)
184 readline_remove_delims = Str('-/~', config=True)
187 readline_parse_and_bind = List([
185 readline_parse_and_bind = List([
188 'tab: complete',
186 'tab: complete',
189 '"\C-l": clear-screen',
187 '"\C-l": clear-screen',
190 'set show-all-if-ambiguous on',
188 'set show-all-if-ambiguous on',
191 '"\C-o": tab-insert',
189 '"\C-o": tab-insert',
192 '"\M-i": " "',
190 '"\M-i": " "',
193 '"\M-o": "\d\d\d\d"',
191 '"\M-o": "\d\d\d\d"',
194 '"\M-I": "\d\d\d\d"',
192 '"\M-I": "\d\d\d\d"',
195 '"\C-r": reverse-search-history',
193 '"\C-r": reverse-search-history',
196 '"\C-s": forward-search-history',
194 '"\C-s": forward-search-history',
197 '"\C-p": history-search-backward',
195 '"\C-p": history-search-backward',
198 '"\C-n": history-search-forward',
196 '"\C-n": history-search-forward',
199 '"\e[A": history-search-backward',
197 '"\e[A": history-search-backward',
200 '"\e[B": history-search-forward',
198 '"\e[B": history-search-forward',
201 '"\C-k": kill-line',
199 '"\C-k": kill-line',
202 '"\C-u": unix-line-discard',
200 '"\C-u": unix-line-discard',
203 ], allow_none=False, config=True)
201 ], allow_none=False, config=True)
204
202
205 # TODO: this part of prompt management should be moved to the frontends.
203 # TODO: this part of prompt management should be moved to the frontends.
206 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
204 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
207 separate_in = SeparateStr('\n', config=True)
205 separate_in = SeparateStr('\n', config=True)
208 separate_out = SeparateStr('', config=True)
206 separate_out = SeparateStr('', config=True)
209 separate_out2 = SeparateStr('', config=True)
207 separate_out2 = SeparateStr('', config=True)
210 wildcards_case_sensitive = CBool(True, config=True)
208 wildcards_case_sensitive = CBool(True, config=True)
211 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
209 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
212 default_value='Context', config=True)
210 default_value='Context', config=True)
213
211
214 # Subcomponents of InteractiveShell
212 # Subcomponents of InteractiveShell
215 alias_manager = Instance('IPython.core.alias.AliasManager')
213 alias_manager = Instance('IPython.core.alias.AliasManager')
216 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
214 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
217 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap')
215 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap')
218 display_trap = Instance('IPython.core.display_trap.DisplayTrap')
216 display_trap = Instance('IPython.core.display_trap.DisplayTrap')
219 extension_manager = Instance('IPython.core.extensions.ExtensionManager')
217 extension_manager = Instance('IPython.core.extensions.ExtensionManager')
220 plugin_manager = Instance('IPython.core.plugin.PluginManager')
218 plugin_manager = Instance('IPython.core.plugin.PluginManager')
221 payload_manager = Instance('IPython.core.payload.PayloadManager')
219 payload_manager = Instance('IPython.core.payload.PayloadManager')
222 history_manager = Instance('IPython.core.history.HistoryManager')
220 history_manager = Instance('IPython.core.history.HistoryManager')
223
221
224 # Private interface
222 # Private interface
225 _post_execute = set()
223 _post_execute = set()
226
224
227 def __init__(self, config=None, ipython_dir=None,
225 def __init__(self, config=None, ipython_dir=None,
228 user_ns=None, user_global_ns=None,
226 user_ns=None, user_global_ns=None,
229 custom_exceptions=((), None)):
227 custom_exceptions=((), None)):
230
228
231 # This is where traits with a config_key argument are updated
229 # This is where traits with a config_key argument are updated
232 # from the values on config.
230 # from the values on config.
233 super(InteractiveShell, self).__init__(config=config)
231 super(InteractiveShell, self).__init__(config=config)
234
232
235 # These are relatively independent and stateless
233 # These are relatively independent and stateless
236 self.init_ipython_dir(ipython_dir)
234 self.init_ipython_dir(ipython_dir)
237 self.init_instance_attrs()
235 self.init_instance_attrs()
238 self.init_environment()
236 self.init_environment()
239
237
240 # Create namespaces (user_ns, user_global_ns, etc.)
238 # Create namespaces (user_ns, user_global_ns, etc.)
241 self.init_create_namespaces(user_ns, user_global_ns)
239 self.init_create_namespaces(user_ns, user_global_ns)
242 # This has to be done after init_create_namespaces because it uses
240 # This has to be done after init_create_namespaces because it uses
243 # something in self.user_ns, but before init_sys_modules, which
241 # something in self.user_ns, but before init_sys_modules, which
244 # is the first thing to modify sys.
242 # is the first thing to modify sys.
245 # TODO: When we override sys.stdout and sys.stderr before this class
243 # TODO: When we override sys.stdout and sys.stderr before this class
246 # is created, we are saving the overridden ones here. Not sure if this
244 # is created, we are saving the overridden ones here. Not sure if this
247 # is what we want to do.
245 # is what we want to do.
248 self.save_sys_module_state()
246 self.save_sys_module_state()
249 self.init_sys_modules()
247 self.init_sys_modules()
250
248
251 self.init_history()
249 self.init_history()
252 self.init_encoding()
250 self.init_encoding()
253 self.init_prefilter()
251 self.init_prefilter()
254
252
255 Magic.__init__(self, self)
253 Magic.__init__(self, self)
256
254
257 self.init_syntax_highlighting()
255 self.init_syntax_highlighting()
258 self.init_hooks()
256 self.init_hooks()
259 self.init_pushd_popd_magic()
257 self.init_pushd_popd_magic()
260 # self.init_traceback_handlers use to be here, but we moved it below
258 # self.init_traceback_handlers use to be here, but we moved it below
261 # because it and init_io have to come after init_readline.
259 # because it and init_io have to come after init_readline.
262 self.init_user_ns()
260 self.init_user_ns()
263 self.init_logger()
261 self.init_logger()
264 self.init_alias()
262 self.init_alias()
265 self.init_builtins()
263 self.init_builtins()
266
264
267 # pre_config_initialization
265 # pre_config_initialization
268
266
269 # The next section should contain everything that was in ipmaker.
267 # The next section should contain everything that was in ipmaker.
270 self.init_logstart()
268 self.init_logstart()
271
269
272 # The following was in post_config_initialization
270 # The following was in post_config_initialization
273 self.init_inspector()
271 self.init_inspector()
274 # init_readline() must come before init_io(), because init_io uses
272 # init_readline() must come before init_io(), because init_io uses
275 # readline related things.
273 # readline related things.
276 self.init_readline()
274 self.init_readline()
277 # init_completer must come after init_readline, because it needs to
275 # init_completer must come after init_readline, because it needs to
278 # know whether readline is present or not system-wide to configure the
276 # know whether readline is present or not system-wide to configure the
279 # completers, since the completion machinery can now operate
277 # completers, since the completion machinery can now operate
280 # independently of readline (e.g. over the network)
278 # independently of readline (e.g. over the network)
281 self.init_completer()
279 self.init_completer()
282 # TODO: init_io() needs to happen before init_traceback handlers
280 # TODO: init_io() needs to happen before init_traceback handlers
283 # because the traceback handlers hardcode the stdout/stderr streams.
281 # because the traceback handlers hardcode the stdout/stderr streams.
284 # This logic in in debugger.Pdb and should eventually be changed.
282 # This logic in in debugger.Pdb and should eventually be changed.
285 self.init_io()
283 self.init_io()
286 self.init_traceback_handlers(custom_exceptions)
284 self.init_traceback_handlers(custom_exceptions)
287 self.init_prompts()
285 self.init_prompts()
288 self.init_displayhook()
286 self.init_displayhook()
289 self.init_reload_doctest()
287 self.init_reload_doctest()
290 self.init_magics()
288 self.init_magics()
291 self.init_pdb()
289 self.init_pdb()
292 self.init_extension_manager()
290 self.init_extension_manager()
293 self.init_plugin_manager()
291 self.init_plugin_manager()
294 self.init_payload()
292 self.init_payload()
295 self.hooks.late_startup_hook()
293 self.hooks.late_startup_hook()
296 atexit.register(self.atexit_operations)
294 atexit.register(self.atexit_operations)
297
295
298 @classmethod
296 @classmethod
299 def instance(cls, *args, **kwargs):
297 def instance(cls, *args, **kwargs):
300 """Returns a global InteractiveShell instance."""
298 """Returns a global InteractiveShell instance."""
301 if cls._instance is None:
299 if cls._instance is None:
302 inst = cls(*args, **kwargs)
300 inst = cls(*args, **kwargs)
303 # Now make sure that the instance will also be returned by
301 # Now make sure that the instance will also be returned by
304 # the subclasses instance attribute.
302 # the subclasses instance attribute.
305 for subclass in cls.mro():
303 for subclass in cls.mro():
306 if issubclass(cls, subclass) and \
304 if issubclass(cls, subclass) and \
307 issubclass(subclass, InteractiveShell):
305 issubclass(subclass, InteractiveShell):
308 subclass._instance = inst
306 subclass._instance = inst
309 else:
307 else:
310 break
308 break
311 if isinstance(cls._instance, cls):
309 if isinstance(cls._instance, cls):
312 return cls._instance
310 return cls._instance
313 else:
311 else:
314 raise MultipleInstanceError(
312 raise MultipleInstanceError(
315 'Multiple incompatible subclass instances of '
313 'Multiple incompatible subclass instances of '
316 'InteractiveShell are being created.'
314 'InteractiveShell are being created.'
317 )
315 )
318
316
319 @classmethod
317 @classmethod
320 def initialized(cls):
318 def initialized(cls):
321 return hasattr(cls, "_instance")
319 return hasattr(cls, "_instance")
322
320
323 def get_ipython(self):
321 def get_ipython(self):
324 """Return the currently running IPython instance."""
322 """Return the currently running IPython instance."""
325 return self
323 return self
326
324
327 #-------------------------------------------------------------------------
325 #-------------------------------------------------------------------------
328 # Trait changed handlers
326 # Trait changed handlers
329 #-------------------------------------------------------------------------
327 #-------------------------------------------------------------------------
330
328
331 def _ipython_dir_changed(self, name, new):
329 def _ipython_dir_changed(self, name, new):
332 if not os.path.isdir(new):
330 if not os.path.isdir(new):
333 os.makedirs(new, mode = 0777)
331 os.makedirs(new, mode = 0777)
334
332
335 def set_autoindent(self,value=None):
333 def set_autoindent(self,value=None):
336 """Set the autoindent flag, checking for readline support.
334 """Set the autoindent flag, checking for readline support.
337
335
338 If called with no arguments, it acts as a toggle."""
336 If called with no arguments, it acts as a toggle."""
339
337
340 if not self.has_readline:
338 if not self.has_readline:
341 if os.name == 'posix':
339 if os.name == 'posix':
342 warn("The auto-indent feature requires the readline library")
340 warn("The auto-indent feature requires the readline library")
343 self.autoindent = 0
341 self.autoindent = 0
344 return
342 return
345 if value is None:
343 if value is None:
346 self.autoindent = not self.autoindent
344 self.autoindent = not self.autoindent
347 else:
345 else:
348 self.autoindent = value
346 self.autoindent = value
349
347
350 #-------------------------------------------------------------------------
348 #-------------------------------------------------------------------------
351 # init_* methods called by __init__
349 # init_* methods called by __init__
352 #-------------------------------------------------------------------------
350 #-------------------------------------------------------------------------
353
351
354 def init_ipython_dir(self, ipython_dir):
352 def init_ipython_dir(self, ipython_dir):
355 if ipython_dir is not None:
353 if ipython_dir is not None:
356 self.ipython_dir = ipython_dir
354 self.ipython_dir = ipython_dir
357 self.config.Global.ipython_dir = self.ipython_dir
355 self.config.Global.ipython_dir = self.ipython_dir
358 return
356 return
359
357
360 if hasattr(self.config.Global, 'ipython_dir'):
358 if hasattr(self.config.Global, 'ipython_dir'):
361 self.ipython_dir = self.config.Global.ipython_dir
359 self.ipython_dir = self.config.Global.ipython_dir
362 else:
360 else:
363 self.ipython_dir = get_ipython_dir()
361 self.ipython_dir = get_ipython_dir()
364
362
365 # All children can just read this
363 # All children can just read this
366 self.config.Global.ipython_dir = self.ipython_dir
364 self.config.Global.ipython_dir = self.ipython_dir
367
365
368 def init_instance_attrs(self):
366 def init_instance_attrs(self):
369 self.more = False
367 self.more = False
370
368
371 # command compiler
369 # command compiler
372 self.compile = CachingCompiler()
370 self.compile = CachingCompiler()
373
371
374 # User input buffers
372 # User input buffers
375 # NOTE: these variables are slated for full removal, once we are 100%
373 # NOTE: these variables are slated for full removal, once we are 100%
376 # sure that the new execution logic is solid. We will delte runlines,
374 # sure that the new execution logic is solid. We will delte runlines,
377 # push_line and these buffers, as all input will be managed by the
375 # push_line and these buffers, as all input will be managed by the
378 # frontends via an inputsplitter instance.
376 # frontends via an inputsplitter instance.
379 self.buffer = []
377 self.buffer = []
380 self.buffer_raw = []
378 self.buffer_raw = []
381
379
382 # Make an empty namespace, which extension writers can rely on both
380 # Make an empty namespace, which extension writers can rely on both
383 # existing and NEVER being used by ipython itself. This gives them a
381 # existing and NEVER being used by ipython itself. This gives them a
384 # convenient location for storing additional information and state
382 # convenient location for storing additional information and state
385 # their extensions may require, without fear of collisions with other
383 # their extensions may require, without fear of collisions with other
386 # ipython names that may develop later.
384 # ipython names that may develop later.
387 self.meta = Struct()
385 self.meta = Struct()
388
386
389 # Object variable to store code object waiting execution. This is
387 # Object variable to store code object waiting execution. This is
390 # used mainly by the multithreaded shells, but it can come in handy in
388 # used mainly by the multithreaded shells, but it can come in handy in
391 # other situations. No need to use a Queue here, since it's a single
389 # other situations. No need to use a Queue here, since it's a single
392 # item which gets cleared once run.
390 # item which gets cleared once run.
393 self.code_to_run = None
391 self.code_to_run = None
394
392
395 # Temporary files used for various purposes. Deleted at exit.
393 # Temporary files used for various purposes. Deleted at exit.
396 self.tempfiles = []
394 self.tempfiles = []
397
395
398 # Keep track of readline usage (later set by init_readline)
396 # Keep track of readline usage (later set by init_readline)
399 self.has_readline = False
397 self.has_readline = False
400
398
401 # keep track of where we started running (mainly for crash post-mortem)
399 # keep track of where we started running (mainly for crash post-mortem)
402 # This is not being used anywhere currently.
400 # This is not being used anywhere currently.
403 self.starting_dir = os.getcwd()
401 self.starting_dir = os.getcwd()
404
402
405 # Indentation management
403 # Indentation management
406 self.indent_current_nsp = 0
404 self.indent_current_nsp = 0
407
405
408 def init_environment(self):
406 def init_environment(self):
409 """Any changes we need to make to the user's environment."""
407 """Any changes we need to make to the user's environment."""
410 pass
408 pass
411
409
412 def init_encoding(self):
410 def init_encoding(self):
413 # Get system encoding at startup time. Certain terminals (like Emacs
411 # Get system encoding at startup time. Certain terminals (like Emacs
414 # under Win32 have it set to None, and we need to have a known valid
412 # under Win32 have it set to None, and we need to have a known valid
415 # encoding to use in the raw_input() method
413 # encoding to use in the raw_input() method
416 try:
414 try:
417 self.stdin_encoding = sys.stdin.encoding or 'ascii'
415 self.stdin_encoding = sys.stdin.encoding or 'ascii'
418 except AttributeError:
416 except AttributeError:
419 self.stdin_encoding = 'ascii'
417 self.stdin_encoding = 'ascii'
420
418
421 def init_syntax_highlighting(self):
419 def init_syntax_highlighting(self):
422 # Python source parser/formatter for syntax highlighting
420 # Python source parser/formatter for syntax highlighting
423 pyformat = PyColorize.Parser().format
421 pyformat = PyColorize.Parser().format
424 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
422 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
425
423
426 def init_pushd_popd_magic(self):
424 def init_pushd_popd_magic(self):
427 # for pushd/popd management
425 # for pushd/popd management
428 try:
426 try:
429 self.home_dir = get_home_dir()
427 self.home_dir = get_home_dir()
430 except HomeDirError, msg:
428 except HomeDirError, msg:
431 fatal(msg)
429 fatal(msg)
432
430
433 self.dir_stack = []
431 self.dir_stack = []
434
432
435 def init_logger(self):
433 def init_logger(self):
436 self.logger = Logger(self.home_dir, logfname='ipython_log.py',
434 self.logger = Logger(self.home_dir, logfname='ipython_log.py',
437 logmode='rotate')
435 logmode='rotate')
438
436
439 def init_logstart(self):
437 def init_logstart(self):
440 """Initialize logging in case it was requested at the command line.
438 """Initialize logging in case it was requested at the command line.
441 """
439 """
442 if self.logappend:
440 if self.logappend:
443 self.magic_logstart(self.logappend + ' append')
441 self.magic_logstart(self.logappend + ' append')
444 elif self.logfile:
442 elif self.logfile:
445 self.magic_logstart(self.logfile)
443 self.magic_logstart(self.logfile)
446 elif self.logstart:
444 elif self.logstart:
447 self.magic_logstart()
445 self.magic_logstart()
448
446
449 def init_builtins(self):
447 def init_builtins(self):
450 self.builtin_trap = BuiltinTrap(shell=self)
448 self.builtin_trap = BuiltinTrap(shell=self)
451
449
452 def init_inspector(self):
450 def init_inspector(self):
453 # Object inspector
451 # Object inspector
454 self.inspector = oinspect.Inspector(oinspect.InspectColors,
452 self.inspector = oinspect.Inspector(oinspect.InspectColors,
455 PyColorize.ANSICodeColors,
453 PyColorize.ANSICodeColors,
456 'NoColor',
454 'NoColor',
457 self.object_info_string_level)
455 self.object_info_string_level)
458
456
459 def init_io(self):
457 def init_io(self):
460 # This will just use sys.stdout and sys.stderr. If you want to
458 # This will just use sys.stdout and sys.stderr. If you want to
461 # override sys.stdout and sys.stderr themselves, you need to do that
459 # override sys.stdout and sys.stderr themselves, you need to do that
462 # *before* instantiating this class, because Term holds onto
460 # *before* instantiating this class, because Term holds onto
463 # references to the underlying streams.
461 # references to the underlying streams.
464 if sys.platform == 'win32' and self.has_readline:
462 if sys.platform == 'win32' and self.has_readline:
465 Term = io.IOTerm(cout=self.readline._outputfile,
463 Term = io.IOTerm(cout=self.readline._outputfile,
466 cerr=self.readline._outputfile)
464 cerr=self.readline._outputfile)
467 else:
465 else:
468 Term = io.IOTerm()
466 Term = io.IOTerm()
469 io.Term = Term
467 io.Term = Term
470
468
471 def init_prompts(self):
469 def init_prompts(self):
472 # TODO: This is a pass for now because the prompts are managed inside
470 # TODO: This is a pass for now because the prompts are managed inside
473 # the DisplayHook. Once there is a separate prompt manager, this
471 # the DisplayHook. Once there is a separate prompt manager, this
474 # will initialize that object and all prompt related information.
472 # will initialize that object and all prompt related information.
475 pass
473 pass
476
474
477 def init_displayhook(self):
475 def init_displayhook(self):
478 # Initialize displayhook, set in/out prompts and printing system
476 # Initialize displayhook, set in/out prompts and printing system
479 self.displayhook = self.displayhook_class(
477 self.displayhook = self.displayhook_class(
480 shell=self,
478 shell=self,
481 cache_size=self.cache_size,
479 cache_size=self.cache_size,
482 input_sep = self.separate_in,
480 input_sep = self.separate_in,
483 output_sep = self.separate_out,
481 output_sep = self.separate_out,
484 output_sep2 = self.separate_out2,
482 output_sep2 = self.separate_out2,
485 ps1 = self.prompt_in1,
483 ps1 = self.prompt_in1,
486 ps2 = self.prompt_in2,
484 ps2 = self.prompt_in2,
487 ps_out = self.prompt_out,
485 ps_out = self.prompt_out,
488 pad_left = self.prompts_pad_left
486 pad_left = self.prompts_pad_left
489 )
487 )
490 # This is a context manager that installs/revmoes the displayhook at
488 # This is a context manager that installs/revmoes the displayhook at
491 # the appropriate time.
489 # the appropriate time.
492 self.display_trap = DisplayTrap(hook=self.displayhook)
490 self.display_trap = DisplayTrap(hook=self.displayhook)
493
491
494 def init_reload_doctest(self):
492 def init_reload_doctest(self):
495 # Do a proper resetting of doctest, including the necessary displayhook
493 # Do a proper resetting of doctest, including the necessary displayhook
496 # monkeypatching
494 # monkeypatching
497 try:
495 try:
498 doctest_reload()
496 doctest_reload()
499 except ImportError:
497 except ImportError:
500 warn("doctest module does not exist.")
498 warn("doctest module does not exist.")
501
499
502 #-------------------------------------------------------------------------
500 #-------------------------------------------------------------------------
503 # Things related to injections into the sys module
501 # Things related to injections into the sys module
504 #-------------------------------------------------------------------------
502 #-------------------------------------------------------------------------
505
503
506 def save_sys_module_state(self):
504 def save_sys_module_state(self):
507 """Save the state of hooks in the sys module.
505 """Save the state of hooks in the sys module.
508
506
509 This has to be called after self.user_ns is created.
507 This has to be called after self.user_ns is created.
510 """
508 """
511 self._orig_sys_module_state = {}
509 self._orig_sys_module_state = {}
512 self._orig_sys_module_state['stdin'] = sys.stdin
510 self._orig_sys_module_state['stdin'] = sys.stdin
513 self._orig_sys_module_state['stdout'] = sys.stdout
511 self._orig_sys_module_state['stdout'] = sys.stdout
514 self._orig_sys_module_state['stderr'] = sys.stderr
512 self._orig_sys_module_state['stderr'] = sys.stderr
515 self._orig_sys_module_state['excepthook'] = sys.excepthook
513 self._orig_sys_module_state['excepthook'] = sys.excepthook
516 try:
514 try:
517 self._orig_sys_modules_main_name = self.user_ns['__name__']
515 self._orig_sys_modules_main_name = self.user_ns['__name__']
518 except KeyError:
516 except KeyError:
519 pass
517 pass
520
518
521 def restore_sys_module_state(self):
519 def restore_sys_module_state(self):
522 """Restore the state of the sys module."""
520 """Restore the state of the sys module."""
523 try:
521 try:
524 for k, v in self._orig_sys_module_state.items():
522 for k, v in self._orig_sys_module_state.iteritems():
525 setattr(sys, k, v)
523 setattr(sys, k, v)
526 except AttributeError:
524 except AttributeError:
527 pass
525 pass
528 # Reset what what done in self.init_sys_modules
526 # Reset what what done in self.init_sys_modules
529 try:
527 try:
530 sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name
528 sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name
531 except (AttributeError, KeyError):
529 except (AttributeError, KeyError):
532 pass
530 pass
533
531
534 #-------------------------------------------------------------------------
532 #-------------------------------------------------------------------------
535 # Things related to hooks
533 # Things related to hooks
536 #-------------------------------------------------------------------------
534 #-------------------------------------------------------------------------
537
535
538 def init_hooks(self):
536 def init_hooks(self):
539 # hooks holds pointers used for user-side customizations
537 # hooks holds pointers used for user-side customizations
540 self.hooks = Struct()
538 self.hooks = Struct()
541
539
542 self.strdispatchers = {}
540 self.strdispatchers = {}
543
541
544 # Set all default hooks, defined in the IPython.hooks module.
542 # Set all default hooks, defined in the IPython.hooks module.
545 hooks = IPython.core.hooks
543 hooks = IPython.core.hooks
546 for hook_name in hooks.__all__:
544 for hook_name in hooks.__all__:
547 # default hooks have priority 100, i.e. low; user hooks should have
545 # default hooks have priority 100, i.e. low; user hooks should have
548 # 0-100 priority
546 # 0-100 priority
549 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
547 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
550
548
551 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
549 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
552 """set_hook(name,hook) -> sets an internal IPython hook.
550 """set_hook(name,hook) -> sets an internal IPython hook.
553
551
554 IPython exposes some of its internal API as user-modifiable hooks. By
552 IPython exposes some of its internal API as user-modifiable hooks. By
555 adding your function to one of these hooks, you can modify IPython's
553 adding your function to one of these hooks, you can modify IPython's
556 behavior to call at runtime your own routines."""
554 behavior to call at runtime your own routines."""
557
555
558 # At some point in the future, this should validate the hook before it
556 # At some point in the future, this should validate the hook before it
559 # accepts it. Probably at least check that the hook takes the number
557 # accepts it. Probably at least check that the hook takes the number
560 # of args it's supposed to.
558 # of args it's supposed to.
561
559
562 f = new.instancemethod(hook,self,self.__class__)
560 f = types.MethodType(hook,self)
563
561
564 # check if the hook is for strdispatcher first
562 # check if the hook is for strdispatcher first
565 if str_key is not None:
563 if str_key is not None:
566 sdp = self.strdispatchers.get(name, StrDispatch())
564 sdp = self.strdispatchers.get(name, StrDispatch())
567 sdp.add_s(str_key, f, priority )
565 sdp.add_s(str_key, f, priority )
568 self.strdispatchers[name] = sdp
566 self.strdispatchers[name] = sdp
569 return
567 return
570 if re_key is not None:
568 if re_key is not None:
571 sdp = self.strdispatchers.get(name, StrDispatch())
569 sdp = self.strdispatchers.get(name, StrDispatch())
572 sdp.add_re(re.compile(re_key), f, priority )
570 sdp.add_re(re.compile(re_key), f, priority )
573 self.strdispatchers[name] = sdp
571 self.strdispatchers[name] = sdp
574 return
572 return
575
573
576 dp = getattr(self.hooks, name, None)
574 dp = getattr(self.hooks, name, None)
577 if name not in IPython.core.hooks.__all__:
575 if name not in IPython.core.hooks.__all__:
578 print "Warning! Hook '%s' is not one of %s" % \
576 print "Warning! Hook '%s' is not one of %s" % \
579 (name, IPython.core.hooks.__all__ )
577 (name, IPython.core.hooks.__all__ )
580 if not dp:
578 if not dp:
581 dp = IPython.core.hooks.CommandChainDispatcher()
579 dp = IPython.core.hooks.CommandChainDispatcher()
582
580
583 try:
581 try:
584 dp.add(f,priority)
582 dp.add(f,priority)
585 except AttributeError:
583 except AttributeError:
586 # it was not commandchain, plain old func - replace
584 # it was not commandchain, plain old func - replace
587 dp = f
585 dp = f
588
586
589 setattr(self.hooks,name, dp)
587 setattr(self.hooks,name, dp)
590
588
591 def register_post_execute(self, func):
589 def register_post_execute(self, func):
592 """Register a function for calling after code execution.
590 """Register a function for calling after code execution.
593 """
591 """
594 if not callable(func):
592 if not callable(func):
595 raise ValueError('argument %s must be callable' % func)
593 raise ValueError('argument %s must be callable' % func)
596 self._post_execute.add(func)
594 self._post_execute.add(func)
597
595
598 #-------------------------------------------------------------------------
596 #-------------------------------------------------------------------------
599 # Things related to the "main" module
597 # Things related to the "main" module
600 #-------------------------------------------------------------------------
598 #-------------------------------------------------------------------------
601
599
602 def new_main_mod(self,ns=None):
600 def new_main_mod(self,ns=None):
603 """Return a new 'main' module object for user code execution.
601 """Return a new 'main' module object for user code execution.
604 """
602 """
605 main_mod = self._user_main_module
603 main_mod = self._user_main_module
606 init_fakemod_dict(main_mod,ns)
604 init_fakemod_dict(main_mod,ns)
607 return main_mod
605 return main_mod
608
606
609 def cache_main_mod(self,ns,fname):
607 def cache_main_mod(self,ns,fname):
610 """Cache a main module's namespace.
608 """Cache a main module's namespace.
611
609
612 When scripts are executed via %run, we must keep a reference to the
610 When scripts are executed via %run, we must keep a reference to the
613 namespace of their __main__ module (a FakeModule instance) around so
611 namespace of their __main__ module (a FakeModule instance) around so
614 that Python doesn't clear it, rendering objects defined therein
612 that Python doesn't clear it, rendering objects defined therein
615 useless.
613 useless.
616
614
617 This method keeps said reference in a private dict, keyed by the
615 This method keeps said reference in a private dict, keyed by the
618 absolute path of the module object (which corresponds to the script
616 absolute path of the module object (which corresponds to the script
619 path). This way, for multiple executions of the same script we only
617 path). This way, for multiple executions of the same script we only
620 keep one copy of the namespace (the last one), thus preventing memory
618 keep one copy of the namespace (the last one), thus preventing memory
621 leaks from old references while allowing the objects from the last
619 leaks from old references while allowing the objects from the last
622 execution to be accessible.
620 execution to be accessible.
623
621
624 Note: we can not allow the actual FakeModule instances to be deleted,
622 Note: we can not allow the actual FakeModule instances to be deleted,
625 because of how Python tears down modules (it hard-sets all their
623 because of how Python tears down modules (it hard-sets all their
626 references to None without regard for reference counts). This method
624 references to None without regard for reference counts). This method
627 must therefore make a *copy* of the given namespace, to allow the
625 must therefore make a *copy* of the given namespace, to allow the
628 original module's __dict__ to be cleared and reused.
626 original module's __dict__ to be cleared and reused.
629
627
630
628
631 Parameters
629 Parameters
632 ----------
630 ----------
633 ns : a namespace (a dict, typically)
631 ns : a namespace (a dict, typically)
634
632
635 fname : str
633 fname : str
636 Filename associated with the namespace.
634 Filename associated with the namespace.
637
635
638 Examples
636 Examples
639 --------
637 --------
640
638
641 In [10]: import IPython
639 In [10]: import IPython
642
640
643 In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
641 In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
644
642
645 In [12]: IPython.__file__ in _ip._main_ns_cache
643 In [12]: IPython.__file__ in _ip._main_ns_cache
646 Out[12]: True
644 Out[12]: True
647 """
645 """
648 self._main_ns_cache[os.path.abspath(fname)] = ns.copy()
646 self._main_ns_cache[os.path.abspath(fname)] = ns.copy()
649
647
650 def clear_main_mod_cache(self):
648 def clear_main_mod_cache(self):
651 """Clear the cache of main modules.
649 """Clear the cache of main modules.
652
650
653 Mainly for use by utilities like %reset.
651 Mainly for use by utilities like %reset.
654
652
655 Examples
653 Examples
656 --------
654 --------
657
655
658 In [15]: import IPython
656 In [15]: import IPython
659
657
660 In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
658 In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
661
659
662 In [17]: len(_ip._main_ns_cache) > 0
660 In [17]: len(_ip._main_ns_cache) > 0
663 Out[17]: True
661 Out[17]: True
664
662
665 In [18]: _ip.clear_main_mod_cache()
663 In [18]: _ip.clear_main_mod_cache()
666
664
667 In [19]: len(_ip._main_ns_cache) == 0
665 In [19]: len(_ip._main_ns_cache) == 0
668 Out[19]: True
666 Out[19]: True
669 """
667 """
670 self._main_ns_cache.clear()
668 self._main_ns_cache.clear()
671
669
672 #-------------------------------------------------------------------------
670 #-------------------------------------------------------------------------
673 # Things related to debugging
671 # Things related to debugging
674 #-------------------------------------------------------------------------
672 #-------------------------------------------------------------------------
675
673
676 def init_pdb(self):
674 def init_pdb(self):
677 # Set calling of pdb on exceptions
675 # Set calling of pdb on exceptions
678 # self.call_pdb is a property
676 # self.call_pdb is a property
679 self.call_pdb = self.pdb
677 self.call_pdb = self.pdb
680
678
681 def _get_call_pdb(self):
679 def _get_call_pdb(self):
682 return self._call_pdb
680 return self._call_pdb
683
681
684 def _set_call_pdb(self,val):
682 def _set_call_pdb(self,val):
685
683
686 if val not in (0,1,False,True):
684 if val not in (0,1,False,True):
687 raise ValueError,'new call_pdb value must be boolean'
685 raise ValueError,'new call_pdb value must be boolean'
688
686
689 # store value in instance
687 # store value in instance
690 self._call_pdb = val
688 self._call_pdb = val
691
689
692 # notify the actual exception handlers
690 # notify the actual exception handlers
693 self.InteractiveTB.call_pdb = val
691 self.InteractiveTB.call_pdb = val
694
692
695 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
693 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
696 'Control auto-activation of pdb at exceptions')
694 'Control auto-activation of pdb at exceptions')
697
695
698 def debugger(self,force=False):
696 def debugger(self,force=False):
699 """Call the pydb/pdb debugger.
697 """Call the pydb/pdb debugger.
700
698
701 Keywords:
699 Keywords:
702
700
703 - force(False): by default, this routine checks the instance call_pdb
701 - force(False): by default, this routine checks the instance call_pdb
704 flag and does not actually invoke the debugger if the flag is false.
702 flag and does not actually invoke the debugger if the flag is false.
705 The 'force' option forces the debugger to activate even if the flag
703 The 'force' option forces the debugger to activate even if the flag
706 is false.
704 is false.
707 """
705 """
708
706
709 if not (force or self.call_pdb):
707 if not (force or self.call_pdb):
710 return
708 return
711
709
712 if not hasattr(sys,'last_traceback'):
710 if not hasattr(sys,'last_traceback'):
713 error('No traceback has been produced, nothing to debug.')
711 error('No traceback has been produced, nothing to debug.')
714 return
712 return
715
713
716 # use pydb if available
714 # use pydb if available
717 if debugger.has_pydb:
715 if debugger.has_pydb:
718 from pydb import pm
716 from pydb import pm
719 else:
717 else:
720 # fallback to our internal debugger
718 # fallback to our internal debugger
721 pm = lambda : self.InteractiveTB.debugger(force=True)
719 pm = lambda : self.InteractiveTB.debugger(force=True)
722 self.history_saving_wrapper(pm)()
720 self.history_saving_wrapper(pm)()
723
721
724 #-------------------------------------------------------------------------
722 #-------------------------------------------------------------------------
725 # Things related to IPython's various namespaces
723 # Things related to IPython's various namespaces
726 #-------------------------------------------------------------------------
724 #-------------------------------------------------------------------------
727
725
728 def init_create_namespaces(self, user_ns=None, user_global_ns=None):
726 def init_create_namespaces(self, user_ns=None, user_global_ns=None):
729 # Create the namespace where the user will operate. user_ns is
727 # Create the namespace where the user will operate. user_ns is
730 # normally the only one used, and it is passed to the exec calls as
728 # normally the only one used, and it is passed to the exec calls as
731 # the locals argument. But we do carry a user_global_ns namespace
729 # the locals argument. But we do carry a user_global_ns namespace
732 # given as the exec 'globals' argument, This is useful in embedding
730 # given as the exec 'globals' argument, This is useful in embedding
733 # situations where the ipython shell opens in a context where the
731 # situations where the ipython shell opens in a context where the
734 # distinction between locals and globals is meaningful. For
732 # distinction between locals and globals is meaningful. For
735 # non-embedded contexts, it is just the same object as the user_ns dict.
733 # non-embedded contexts, it is just the same object as the user_ns dict.
736
734
737 # FIXME. For some strange reason, __builtins__ is showing up at user
735 # FIXME. For some strange reason, __builtins__ is showing up at user
738 # level as a dict instead of a module. This is a manual fix, but I
736 # level as a dict instead of a module. This is a manual fix, but I
739 # should really track down where the problem is coming from. Alex
737 # should really track down where the problem is coming from. Alex
740 # Schmolck reported this problem first.
738 # Schmolck reported this problem first.
741
739
742 # A useful post by Alex Martelli on this topic:
740 # A useful post by Alex Martelli on this topic:
743 # Re: inconsistent value from __builtins__
741 # Re: inconsistent value from __builtins__
744 # Von: Alex Martelli <aleaxit@yahoo.com>
742 # Von: Alex Martelli <aleaxit@yahoo.com>
745 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
743 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
746 # Gruppen: comp.lang.python
744 # Gruppen: comp.lang.python
747
745
748 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
746 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
749 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
747 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
750 # > <type 'dict'>
748 # > <type 'dict'>
751 # > >>> print type(__builtins__)
749 # > >>> print type(__builtins__)
752 # > <type 'module'>
750 # > <type 'module'>
753 # > Is this difference in return value intentional?
751 # > Is this difference in return value intentional?
754
752
755 # Well, it's documented that '__builtins__' can be either a dictionary
753 # Well, it's documented that '__builtins__' can be either a dictionary
756 # or a module, and it's been that way for a long time. Whether it's
754 # or a module, and it's been that way for a long time. Whether it's
757 # intentional (or sensible), I don't know. In any case, the idea is
755 # intentional (or sensible), I don't know. In any case, the idea is
758 # that if you need to access the built-in namespace directly, you
756 # that if you need to access the built-in namespace directly, you
759 # should start with "import __builtin__" (note, no 's') which will
757 # should start with "import __builtin__" (note, no 's') which will
760 # definitely give you a module. Yeah, it's somewhat confusing:-(.
758 # definitely give you a module. Yeah, it's somewhat confusing:-(.
761
759
762 # These routines return properly built dicts as needed by the rest of
760 # These routines return properly built dicts as needed by the rest of
763 # the code, and can also be used by extension writers to generate
761 # the code, and can also be used by extension writers to generate
764 # properly initialized namespaces.
762 # properly initialized namespaces.
765 user_ns, user_global_ns = self.make_user_namespaces(user_ns,
763 user_ns, user_global_ns = self.make_user_namespaces(user_ns,
766 user_global_ns)
764 user_global_ns)
767
765
768 # Assign namespaces
766 # Assign namespaces
769 # This is the namespace where all normal user variables live
767 # This is the namespace where all normal user variables live
770 self.user_ns = user_ns
768 self.user_ns = user_ns
771 self.user_global_ns = user_global_ns
769 self.user_global_ns = user_global_ns
772
770
773 # An auxiliary namespace that checks what parts of the user_ns were
771 # An auxiliary namespace that checks what parts of the user_ns were
774 # loaded at startup, so we can list later only variables defined in
772 # loaded at startup, so we can list later only variables defined in
775 # actual interactive use. Since it is always a subset of user_ns, it
773 # actual interactive use. Since it is always a subset of user_ns, it
776 # doesn't need to be separately tracked in the ns_table.
774 # doesn't need to be separately tracked in the ns_table.
777 self.user_ns_hidden = {}
775 self.user_ns_hidden = {}
778
776
779 # A namespace to keep track of internal data structures to prevent
777 # A namespace to keep track of internal data structures to prevent
780 # them from cluttering user-visible stuff. Will be updated later
778 # them from cluttering user-visible stuff. Will be updated later
781 self.internal_ns = {}
779 self.internal_ns = {}
782
780
783 # Now that FakeModule produces a real module, we've run into a nasty
781 # Now that FakeModule produces a real module, we've run into a nasty
784 # problem: after script execution (via %run), the module where the user
782 # problem: after script execution (via %run), the module where the user
785 # code ran is deleted. Now that this object is a true module (needed
783 # code ran is deleted. Now that this object is a true module (needed
786 # so docetst and other tools work correctly), the Python module
784 # so docetst and other tools work correctly), the Python module
787 # teardown mechanism runs over it, and sets to None every variable
785 # teardown mechanism runs over it, and sets to None every variable
788 # present in that module. Top-level references to objects from the
786 # present in that module. Top-level references to objects from the
789 # script survive, because the user_ns is updated with them. However,
787 # script survive, because the user_ns is updated with them. However,
790 # calling functions defined in the script that use other things from
788 # calling functions defined in the script that use other things from
791 # the script will fail, because the function's closure had references
789 # the script will fail, because the function's closure had references
792 # to the original objects, which are now all None. So we must protect
790 # to the original objects, which are now all None. So we must protect
793 # these modules from deletion by keeping a cache.
791 # these modules from deletion by keeping a cache.
794 #
792 #
795 # To avoid keeping stale modules around (we only need the one from the
793 # To avoid keeping stale modules around (we only need the one from the
796 # last run), we use a dict keyed with the full path to the script, so
794 # last run), we use a dict keyed with the full path to the script, so
797 # only the last version of the module is held in the cache. Note,
795 # only the last version of the module is held in the cache. Note,
798 # however, that we must cache the module *namespace contents* (their
796 # however, that we must cache the module *namespace contents* (their
799 # __dict__). Because if we try to cache the actual modules, old ones
797 # __dict__). Because if we try to cache the actual modules, old ones
800 # (uncached) could be destroyed while still holding references (such as
798 # (uncached) could be destroyed while still holding references (such as
801 # those held by GUI objects that tend to be long-lived)>
799 # those held by GUI objects that tend to be long-lived)>
802 #
800 #
803 # The %reset command will flush this cache. See the cache_main_mod()
801 # The %reset command will flush this cache. See the cache_main_mod()
804 # and clear_main_mod_cache() methods for details on use.
802 # and clear_main_mod_cache() methods for details on use.
805
803
806 # This is the cache used for 'main' namespaces
804 # This is the cache used for 'main' namespaces
807 self._main_ns_cache = {}
805 self._main_ns_cache = {}
808 # And this is the single instance of FakeModule whose __dict__ we keep
806 # And this is the single instance of FakeModule whose __dict__ we keep
809 # copying and clearing for reuse on each %run
807 # copying and clearing for reuse on each %run
810 self._user_main_module = FakeModule()
808 self._user_main_module = FakeModule()
811
809
812 # A table holding all the namespaces IPython deals with, so that
810 # A table holding all the namespaces IPython deals with, so that
813 # introspection facilities can search easily.
811 # introspection facilities can search easily.
814 self.ns_table = {'user':user_ns,
812 self.ns_table = {'user':user_ns,
815 'user_global':user_global_ns,
813 'user_global':user_global_ns,
816 'internal':self.internal_ns,
814 'internal':self.internal_ns,
817 'builtin':__builtin__.__dict__
815 'builtin':__builtin__.__dict__
818 }
816 }
819
817
820 # Similarly, track all namespaces where references can be held and that
818 # Similarly, track all namespaces where references can be held and that
821 # we can safely clear (so it can NOT include builtin). This one can be
819 # we can safely clear (so it can NOT include builtin). This one can be
822 # a simple list. Note that the main execution namespaces, user_ns and
820 # a simple list. Note that the main execution namespaces, user_ns and
823 # user_global_ns, can NOT be listed here, as clearing them blindly
821 # user_global_ns, can NOT be listed here, as clearing them blindly
824 # causes errors in object __del__ methods. Instead, the reset() method
822 # causes errors in object __del__ methods. Instead, the reset() method
825 # clears them manually and carefully.
823 # clears them manually and carefully.
826 self.ns_refs_table = [ self.user_ns_hidden,
824 self.ns_refs_table = [ self.user_ns_hidden,
827 self.internal_ns, self._main_ns_cache ]
825 self.internal_ns, self._main_ns_cache ]
828
826
829 def make_user_namespaces(self, user_ns=None, user_global_ns=None):
827 def make_user_namespaces(self, user_ns=None, user_global_ns=None):
830 """Return a valid local and global user interactive namespaces.
828 """Return a valid local and global user interactive namespaces.
831
829
832 This builds a dict with the minimal information needed to operate as a
830 This builds a dict with the minimal information needed to operate as a
833 valid IPython user namespace, which you can pass to the various
831 valid IPython user namespace, which you can pass to the various
834 embedding classes in ipython. The default implementation returns the
832 embedding classes in ipython. The default implementation returns the
835 same dict for both the locals and the globals to allow functions to
833 same dict for both the locals and the globals to allow functions to
836 refer to variables in the namespace. Customized implementations can
834 refer to variables in the namespace. Customized implementations can
837 return different dicts. The locals dictionary can actually be anything
835 return different dicts. The locals dictionary can actually be anything
838 following the basic mapping protocol of a dict, but the globals dict
836 following the basic mapping protocol of a dict, but the globals dict
839 must be a true dict, not even a subclass. It is recommended that any
837 must be a true dict, not even a subclass. It is recommended that any
840 custom object for the locals namespace synchronize with the globals
838 custom object for the locals namespace synchronize with the globals
841 dict somehow.
839 dict somehow.
842
840
843 Raises TypeError if the provided globals namespace is not a true dict.
841 Raises TypeError if the provided globals namespace is not a true dict.
844
842
845 Parameters
843 Parameters
846 ----------
844 ----------
847 user_ns : dict-like, optional
845 user_ns : dict-like, optional
848 The current user namespace. The items in this namespace should
846 The current user namespace. The items in this namespace should
849 be included in the output. If None, an appropriate blank
847 be included in the output. If None, an appropriate blank
850 namespace should be created.
848 namespace should be created.
851 user_global_ns : dict, optional
849 user_global_ns : dict, optional
852 The current user global namespace. The items in this namespace
850 The current user global namespace. The items in this namespace
853 should be included in the output. If None, an appropriate
851 should be included in the output. If None, an appropriate
854 blank namespace should be created.
852 blank namespace should be created.
855
853
856 Returns
854 Returns
857 -------
855 -------
858 A pair of dictionary-like object to be used as the local namespace
856 A pair of dictionary-like object to be used as the local namespace
859 of the interpreter and a dict to be used as the global namespace.
857 of the interpreter and a dict to be used as the global namespace.
860 """
858 """
861
859
862
860
863 # We must ensure that __builtin__ (without the final 's') is always
861 # We must ensure that __builtin__ (without the final 's') is always
864 # available and pointing to the __builtin__ *module*. For more details:
862 # available and pointing to the __builtin__ *module*. For more details:
865 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
863 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
866
864
867 if user_ns is None:
865 if user_ns is None:
868 # Set __name__ to __main__ to better match the behavior of the
866 # Set __name__ to __main__ to better match the behavior of the
869 # normal interpreter.
867 # normal interpreter.
870 user_ns = {'__name__' :'__main__',
868 user_ns = {'__name__' :'__main__',
871 '__builtin__' : __builtin__,
869 '__builtin__' : __builtin__,
872 '__builtins__' : __builtin__,
870 '__builtins__' : __builtin__,
873 }
871 }
874 else:
872 else:
875 user_ns.setdefault('__name__','__main__')
873 user_ns.setdefault('__name__','__main__')
876 user_ns.setdefault('__builtin__',__builtin__)
874 user_ns.setdefault('__builtin__',__builtin__)
877 user_ns.setdefault('__builtins__',__builtin__)
875 user_ns.setdefault('__builtins__',__builtin__)
878
876
879 if user_global_ns is None:
877 if user_global_ns is None:
880 user_global_ns = user_ns
878 user_global_ns = user_ns
881 if type(user_global_ns) is not dict:
879 if type(user_global_ns) is not dict:
882 raise TypeError("user_global_ns must be a true dict; got %r"
880 raise TypeError("user_global_ns must be a true dict; got %r"
883 % type(user_global_ns))
881 % type(user_global_ns))
884
882
885 return user_ns, user_global_ns
883 return user_ns, user_global_ns
886
884
887 def init_sys_modules(self):
885 def init_sys_modules(self):
888 # We need to insert into sys.modules something that looks like a
886 # We need to insert into sys.modules something that looks like a
889 # module but which accesses the IPython namespace, for shelve and
887 # module but which accesses the IPython namespace, for shelve and
890 # pickle to work interactively. Normally they rely on getting
888 # pickle to work interactively. Normally they rely on getting
891 # everything out of __main__, but for embedding purposes each IPython
889 # everything out of __main__, but for embedding purposes each IPython
892 # instance has its own private namespace, so we can't go shoving
890 # instance has its own private namespace, so we can't go shoving
893 # everything into __main__.
891 # everything into __main__.
894
892
895 # note, however, that we should only do this for non-embedded
893 # note, however, that we should only do this for non-embedded
896 # ipythons, which really mimic the __main__.__dict__ with their own
894 # ipythons, which really mimic the __main__.__dict__ with their own
897 # namespace. Embedded instances, on the other hand, should not do
895 # namespace. Embedded instances, on the other hand, should not do
898 # this because they need to manage the user local/global namespaces
896 # this because they need to manage the user local/global namespaces
899 # only, but they live within a 'normal' __main__ (meaning, they
897 # only, but they live within a 'normal' __main__ (meaning, they
900 # shouldn't overtake the execution environment of the script they're
898 # shouldn't overtake the execution environment of the script they're
901 # embedded in).
899 # embedded in).
902
900
903 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
901 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
904
902
905 try:
903 try:
906 main_name = self.user_ns['__name__']
904 main_name = self.user_ns['__name__']
907 except KeyError:
905 except KeyError:
908 raise KeyError('user_ns dictionary MUST have a "__name__" key')
906 raise KeyError('user_ns dictionary MUST have a "__name__" key')
909 else:
907 else:
910 sys.modules[main_name] = FakeModule(self.user_ns)
908 sys.modules[main_name] = FakeModule(self.user_ns)
911
909
912 def init_user_ns(self):
910 def init_user_ns(self):
913 """Initialize all user-visible namespaces to their minimum defaults.
911 """Initialize all user-visible namespaces to their minimum defaults.
914
912
915 Certain history lists are also initialized here, as they effectively
913 Certain history lists are also initialized here, as they effectively
916 act as user namespaces.
914 act as user namespaces.
917
915
918 Notes
916 Notes
919 -----
917 -----
920 All data structures here are only filled in, they are NOT reset by this
918 All data structures here are only filled in, they are NOT reset by this
921 method. If they were not empty before, data will simply be added to
919 method. If they were not empty before, data will simply be added to
922 therm.
920 therm.
923 """
921 """
924 # This function works in two parts: first we put a few things in
922 # This function works in two parts: first we put a few things in
925 # user_ns, and we sync that contents into user_ns_hidden so that these
923 # user_ns, and we sync that contents into user_ns_hidden so that these
926 # initial variables aren't shown by %who. After the sync, we add the
924 # initial variables aren't shown by %who. After the sync, we add the
927 # rest of what we *do* want the user to see with %who even on a new
925 # rest of what we *do* want the user to see with %who even on a new
928 # session (probably nothing, so theye really only see their own stuff)
926 # session (probably nothing, so theye really only see their own stuff)
929
927
930 # The user dict must *always* have a __builtin__ reference to the
928 # The user dict must *always* have a __builtin__ reference to the
931 # Python standard __builtin__ namespace, which must be imported.
929 # Python standard __builtin__ namespace, which must be imported.
932 # This is so that certain operations in prompt evaluation can be
930 # This is so that certain operations in prompt evaluation can be
933 # reliably executed with builtins. Note that we can NOT use
931 # reliably executed with builtins. Note that we can NOT use
934 # __builtins__ (note the 's'), because that can either be a dict or a
932 # __builtins__ (note the 's'), because that can either be a dict or a
935 # module, and can even mutate at runtime, depending on the context
933 # module, and can even mutate at runtime, depending on the context
936 # (Python makes no guarantees on it). In contrast, __builtin__ is
934 # (Python makes no guarantees on it). In contrast, __builtin__ is
937 # always a module object, though it must be explicitly imported.
935 # always a module object, though it must be explicitly imported.
938
936
939 # For more details:
937 # For more details:
940 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
938 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
941 ns = dict(__builtin__ = __builtin__)
939 ns = dict(__builtin__ = __builtin__)
942
940
943 # Put 'help' in the user namespace
941 # Put 'help' in the user namespace
944 try:
942 try:
945 from site import _Helper
943 from site import _Helper
946 ns['help'] = _Helper()
944 ns['help'] = _Helper()
947 except ImportError:
945 except ImportError:
948 warn('help() not available - check site.py')
946 warn('help() not available - check site.py')
949
947
950 # make global variables for user access to the histories
948 # make global variables for user access to the histories
951 ns['_ih'] = self.input_hist
949 ns['_ih'] = self.input_hist
952 ns['_oh'] = self.output_hist
950 ns['_oh'] = self.output_hist
953 ns['_dh'] = self.dir_hist
951 ns['_dh'] = self.dir_hist
954
952
955 ns['_sh'] = shadowns
953 ns['_sh'] = shadowns
956
954
957 # user aliases to input and output histories. These shouldn't show up
955 # user aliases to input and output histories. These shouldn't show up
958 # in %who, as they can have very large reprs.
956 # in %who, as they can have very large reprs.
959 ns['In'] = self.input_hist
957 ns['In'] = self.input_hist
960 ns['Out'] = self.output_hist
958 ns['Out'] = self.output_hist
961
959
962 # Store myself as the public api!!!
960 # Store myself as the public api!!!
963 ns['get_ipython'] = self.get_ipython
961 ns['get_ipython'] = self.get_ipython
964
962
965 # Sync what we've added so far to user_ns_hidden so these aren't seen
963 # Sync what we've added so far to user_ns_hidden so these aren't seen
966 # by %who
964 # by %who
967 self.user_ns_hidden.update(ns)
965 self.user_ns_hidden.update(ns)
968
966
969 # Anything put into ns now would show up in %who. Think twice before
967 # Anything put into ns now would show up in %who. Think twice before
970 # putting anything here, as we really want %who to show the user their
968 # putting anything here, as we really want %who to show the user their
971 # stuff, not our variables.
969 # stuff, not our variables.
972
970
973 # Finally, update the real user's namespace
971 # Finally, update the real user's namespace
974 self.user_ns.update(ns)
972 self.user_ns.update(ns)
975
973
976 def reset(self):
974 def reset(self):
977 """Clear all internal namespaces.
975 """Clear all internal namespaces.
978
976
979 Note that this is much more aggressive than %reset, since it clears
977 Note that this is much more aggressive than %reset, since it clears
980 fully all namespaces, as well as all input/output lists.
978 fully all namespaces, as well as all input/output lists.
981 """
979 """
982 # Clear histories
980 # Clear histories
983 self.history_manager.reset()
981 self.history_manager.reset()
984
982
985 # Reset counter used to index all histories
983 # Reset counter used to index all histories
986 self.execution_count = 0
984 self.execution_count = 0
987
985
988 # Restore the user namespaces to minimal usability
986 # Restore the user namespaces to minimal usability
989 for ns in self.ns_refs_table:
987 for ns in self.ns_refs_table:
990 ns.clear()
988 ns.clear()
991
989
992 # The main execution namespaces must be cleared very carefully,
990 # The main execution namespaces must be cleared very carefully,
993 # skipping the deletion of the builtin-related keys, because doing so
991 # skipping the deletion of the builtin-related keys, because doing so
994 # would cause errors in many object's __del__ methods.
992 # would cause errors in many object's __del__ methods.
995 for ns in [self.user_ns, self.user_global_ns]:
993 for ns in [self.user_ns, self.user_global_ns]:
996 drop_keys = set(ns.keys())
994 drop_keys = set(ns.keys())
997 drop_keys.discard('__builtin__')
995 drop_keys.discard('__builtin__')
998 drop_keys.discard('__builtins__')
996 drop_keys.discard('__builtins__')
999 for k in drop_keys:
997 for k in drop_keys:
1000 del ns[k]
998 del ns[k]
1001
999
1002 # Restore the user namespaces to minimal usability
1000 # Restore the user namespaces to minimal usability
1003 self.init_user_ns()
1001 self.init_user_ns()
1004
1002
1005 # Restore the default and user aliases
1003 # Restore the default and user aliases
1006 self.alias_manager.clear_aliases()
1004 self.alias_manager.clear_aliases()
1007 self.alias_manager.init_aliases()
1005 self.alias_manager.init_aliases()
1008
1006
1009 def reset_selective(self, regex=None):
1007 def reset_selective(self, regex=None):
1010 """Clear selective variables from internal namespaces based on a
1008 """Clear selective variables from internal namespaces based on a
1011 specified regular expression.
1009 specified regular expression.
1012
1010
1013 Parameters
1011 Parameters
1014 ----------
1012 ----------
1015 regex : string or compiled pattern, optional
1013 regex : string or compiled pattern, optional
1016 A regular expression pattern that will be used in searching
1014 A regular expression pattern that will be used in searching
1017 variable names in the users namespaces.
1015 variable names in the users namespaces.
1018 """
1016 """
1019 if regex is not None:
1017 if regex is not None:
1020 try:
1018 try:
1021 m = re.compile(regex)
1019 m = re.compile(regex)
1022 except TypeError:
1020 except TypeError:
1023 raise TypeError('regex must be a string or compiled pattern')
1021 raise TypeError('regex must be a string or compiled pattern')
1024 # Search for keys in each namespace that match the given regex
1022 # Search for keys in each namespace that match the given regex
1025 # If a match is found, delete the key/value pair.
1023 # If a match is found, delete the key/value pair.
1026 for ns in self.ns_refs_table:
1024 for ns in self.ns_refs_table:
1027 for var in ns:
1025 for var in ns:
1028 if m.search(var):
1026 if m.search(var):
1029 del ns[var]
1027 del ns[var]
1030
1028
1031 def push(self, variables, interactive=True):
1029 def push(self, variables, interactive=True):
1032 """Inject a group of variables into the IPython user namespace.
1030 """Inject a group of variables into the IPython user namespace.
1033
1031
1034 Parameters
1032 Parameters
1035 ----------
1033 ----------
1036 variables : dict, str or list/tuple of str
1034 variables : dict, str or list/tuple of str
1037 The variables to inject into the user's namespace. If a dict, a
1035 The variables to inject into the user's namespace. If a dict, a
1038 simple update is done. If a str, the string is assumed to have
1036 simple update is done. If a str, the string is assumed to have
1039 variable names separated by spaces. A list/tuple of str can also
1037 variable names separated by spaces. A list/tuple of str can also
1040 be used to give the variable names. If just the variable names are
1038 be used to give the variable names. If just the variable names are
1041 give (list/tuple/str) then the variable values looked up in the
1039 give (list/tuple/str) then the variable values looked up in the
1042 callers frame.
1040 callers frame.
1043 interactive : bool
1041 interactive : bool
1044 If True (default), the variables will be listed with the ``who``
1042 If True (default), the variables will be listed with the ``who``
1045 magic.
1043 magic.
1046 """
1044 """
1047 vdict = None
1045 vdict = None
1048
1046
1049 # We need a dict of name/value pairs to do namespace updates.
1047 # We need a dict of name/value pairs to do namespace updates.
1050 if isinstance(variables, dict):
1048 if isinstance(variables, dict):
1051 vdict = variables
1049 vdict = variables
1052 elif isinstance(variables, (basestring, list, tuple)):
1050 elif isinstance(variables, (basestring, list, tuple)):
1053 if isinstance(variables, basestring):
1051 if isinstance(variables, basestring):
1054 vlist = variables.split()
1052 vlist = variables.split()
1055 else:
1053 else:
1056 vlist = variables
1054 vlist = variables
1057 vdict = {}
1055 vdict = {}
1058 cf = sys._getframe(1)
1056 cf = sys._getframe(1)
1059 for name in vlist:
1057 for name in vlist:
1060 try:
1058 try:
1061 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1059 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1062 except:
1060 except:
1063 print ('Could not get variable %s from %s' %
1061 print ('Could not get variable %s from %s' %
1064 (name,cf.f_code.co_name))
1062 (name,cf.f_code.co_name))
1065 else:
1063 else:
1066 raise ValueError('variables must be a dict/str/list/tuple')
1064 raise ValueError('variables must be a dict/str/list/tuple')
1067
1065
1068 # Propagate variables to user namespace
1066 # Propagate variables to user namespace
1069 self.user_ns.update(vdict)
1067 self.user_ns.update(vdict)
1070
1068
1071 # And configure interactive visibility
1069 # And configure interactive visibility
1072 config_ns = self.user_ns_hidden
1070 config_ns = self.user_ns_hidden
1073 if interactive:
1071 if interactive:
1074 for name, val in vdict.iteritems():
1072 for name, val in vdict.iteritems():
1075 config_ns.pop(name, None)
1073 config_ns.pop(name, None)
1076 else:
1074 else:
1077 for name,val in vdict.iteritems():
1075 for name,val in vdict.iteritems():
1078 config_ns[name] = val
1076 config_ns[name] = val
1079
1077
1080 #-------------------------------------------------------------------------
1078 #-------------------------------------------------------------------------
1081 # Things related to object introspection
1079 # Things related to object introspection
1082 #-------------------------------------------------------------------------
1080 #-------------------------------------------------------------------------
1083
1081
1084 def _ofind(self, oname, namespaces=None):
1082 def _ofind(self, oname, namespaces=None):
1085 """Find an object in the available namespaces.
1083 """Find an object in the available namespaces.
1086
1084
1087 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
1085 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
1088
1086
1089 Has special code to detect magic functions.
1087 Has special code to detect magic functions.
1090 """
1088 """
1091 #oname = oname.strip()
1089 #oname = oname.strip()
1092 #print '1- oname: <%r>' % oname # dbg
1090 #print '1- oname: <%r>' % oname # dbg
1093 try:
1091 try:
1094 oname = oname.strip().encode('ascii')
1092 oname = oname.strip().encode('ascii')
1095 #print '2- oname: <%r>' % oname # dbg
1093 #print '2- oname: <%r>' % oname # dbg
1096 except UnicodeEncodeError:
1094 except UnicodeEncodeError:
1097 print 'Python identifiers can only contain ascii characters.'
1095 print 'Python identifiers can only contain ascii characters.'
1098 return dict(found=False)
1096 return dict(found=False)
1099
1097
1100 alias_ns = None
1098 alias_ns = None
1101 if namespaces is None:
1099 if namespaces is None:
1102 # Namespaces to search in:
1100 # Namespaces to search in:
1103 # Put them in a list. The order is important so that we
1101 # Put them in a list. The order is important so that we
1104 # find things in the same order that Python finds them.
1102 # find things in the same order that Python finds them.
1105 namespaces = [ ('Interactive', self.user_ns),
1103 namespaces = [ ('Interactive', self.user_ns),
1106 ('IPython internal', self.internal_ns),
1104 ('IPython internal', self.internal_ns),
1107 ('Python builtin', __builtin__.__dict__),
1105 ('Python builtin', __builtin__.__dict__),
1108 ('Alias', self.alias_manager.alias_table),
1106 ('Alias', self.alias_manager.alias_table),
1109 ]
1107 ]
1110 alias_ns = self.alias_manager.alias_table
1108 alias_ns = self.alias_manager.alias_table
1111
1109
1112 # initialize results to 'null'
1110 # initialize results to 'null'
1113 found = False; obj = None; ospace = None; ds = None;
1111 found = False; obj = None; ospace = None; ds = None;
1114 ismagic = False; isalias = False; parent = None
1112 ismagic = False; isalias = False; parent = None
1115
1113
1116 # We need to special-case 'print', which as of python2.6 registers as a
1114 # We need to special-case 'print', which as of python2.6 registers as a
1117 # function but should only be treated as one if print_function was
1115 # function but should only be treated as one if print_function was
1118 # loaded with a future import. In this case, just bail.
1116 # loaded with a future import. In this case, just bail.
1119 if (oname == 'print' and not (self.compile.compiler_flags &
1117 if (oname == 'print' and not (self.compile.compiler_flags &
1120 __future__.CO_FUTURE_PRINT_FUNCTION)):
1118 __future__.CO_FUTURE_PRINT_FUNCTION)):
1121 return {'found':found, 'obj':obj, 'namespace':ospace,
1119 return {'found':found, 'obj':obj, 'namespace':ospace,
1122 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1120 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1123
1121
1124 # Look for the given name by splitting it in parts. If the head is
1122 # Look for the given name by splitting it in parts. If the head is
1125 # found, then we look for all the remaining parts as members, and only
1123 # found, then we look for all the remaining parts as members, and only
1126 # declare success if we can find them all.
1124 # declare success if we can find them all.
1127 oname_parts = oname.split('.')
1125 oname_parts = oname.split('.')
1128 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
1126 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
1129 for nsname,ns in namespaces:
1127 for nsname,ns in namespaces:
1130 try:
1128 try:
1131 obj = ns[oname_head]
1129 obj = ns[oname_head]
1132 except KeyError:
1130 except KeyError:
1133 continue
1131 continue
1134 else:
1132 else:
1135 #print 'oname_rest:', oname_rest # dbg
1133 #print 'oname_rest:', oname_rest # dbg
1136 for part in oname_rest:
1134 for part in oname_rest:
1137 try:
1135 try:
1138 parent = obj
1136 parent = obj
1139 obj = getattr(obj,part)
1137 obj = getattr(obj,part)
1140 except:
1138 except:
1141 # Blanket except b/c some badly implemented objects
1139 # Blanket except b/c some badly implemented objects
1142 # allow __getattr__ to raise exceptions other than
1140 # allow __getattr__ to raise exceptions other than
1143 # AttributeError, which then crashes IPython.
1141 # AttributeError, which then crashes IPython.
1144 break
1142 break
1145 else:
1143 else:
1146 # If we finish the for loop (no break), we got all members
1144 # If we finish the for loop (no break), we got all members
1147 found = True
1145 found = True
1148 ospace = nsname
1146 ospace = nsname
1149 if ns == alias_ns:
1147 if ns == alias_ns:
1150 isalias = True
1148 isalias = True
1151 break # namespace loop
1149 break # namespace loop
1152
1150
1153 # Try to see if it's magic
1151 # Try to see if it's magic
1154 if not found:
1152 if not found:
1155 if oname.startswith(ESC_MAGIC):
1153 if oname.startswith(ESC_MAGIC):
1156 oname = oname[1:]
1154 oname = oname[1:]
1157 obj = getattr(self,'magic_'+oname,None)
1155 obj = getattr(self,'magic_'+oname,None)
1158 if obj is not None:
1156 if obj is not None:
1159 found = True
1157 found = True
1160 ospace = 'IPython internal'
1158 ospace = 'IPython internal'
1161 ismagic = True
1159 ismagic = True
1162
1160
1163 # Last try: special-case some literals like '', [], {}, etc:
1161 # Last try: special-case some literals like '', [], {}, etc:
1164 if not found and oname_head in ["''",'""','[]','{}','()']:
1162 if not found and oname_head in ["''",'""','[]','{}','()']:
1165 obj = eval(oname_head)
1163 obj = eval(oname_head)
1166 found = True
1164 found = True
1167 ospace = 'Interactive'
1165 ospace = 'Interactive'
1168
1166
1169 return {'found':found, 'obj':obj, 'namespace':ospace,
1167 return {'found':found, 'obj':obj, 'namespace':ospace,
1170 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1168 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1171
1169
1172 def _ofind_property(self, oname, info):
1170 def _ofind_property(self, oname, info):
1173 """Second part of object finding, to look for property details."""
1171 """Second part of object finding, to look for property details."""
1174 if info.found:
1172 if info.found:
1175 # Get the docstring of the class property if it exists.
1173 # Get the docstring of the class property if it exists.
1176 path = oname.split('.')
1174 path = oname.split('.')
1177 root = '.'.join(path[:-1])
1175 root = '.'.join(path[:-1])
1178 if info.parent is not None:
1176 if info.parent is not None:
1179 try:
1177 try:
1180 target = getattr(info.parent, '__class__')
1178 target = getattr(info.parent, '__class__')
1181 # The object belongs to a class instance.
1179 # The object belongs to a class instance.
1182 try:
1180 try:
1183 target = getattr(target, path[-1])
1181 target = getattr(target, path[-1])
1184 # The class defines the object.
1182 # The class defines the object.
1185 if isinstance(target, property):
1183 if isinstance(target, property):
1186 oname = root + '.__class__.' + path[-1]
1184 oname = root + '.__class__.' + path[-1]
1187 info = Struct(self._ofind(oname))
1185 info = Struct(self._ofind(oname))
1188 except AttributeError: pass
1186 except AttributeError: pass
1189 except AttributeError: pass
1187 except AttributeError: pass
1190
1188
1191 # We return either the new info or the unmodified input if the object
1189 # We return either the new info or the unmodified input if the object
1192 # hadn't been found
1190 # hadn't been found
1193 return info
1191 return info
1194
1192
1195 def _object_find(self, oname, namespaces=None):
1193 def _object_find(self, oname, namespaces=None):
1196 """Find an object and return a struct with info about it."""
1194 """Find an object and return a struct with info about it."""
1197 inf = Struct(self._ofind(oname, namespaces))
1195 inf = Struct(self._ofind(oname, namespaces))
1198 return Struct(self._ofind_property(oname, inf))
1196 return Struct(self._ofind_property(oname, inf))
1199
1197
1200 def _inspect(self, meth, oname, namespaces=None, **kw):
1198 def _inspect(self, meth, oname, namespaces=None, **kw):
1201 """Generic interface to the inspector system.
1199 """Generic interface to the inspector system.
1202
1200
1203 This function is meant to be called by pdef, pdoc & friends."""
1201 This function is meant to be called by pdef, pdoc & friends."""
1204 info = self._object_find(oname)
1202 info = self._object_find(oname)
1205 if info.found:
1203 if info.found:
1206 pmethod = getattr(self.inspector, meth)
1204 pmethod = getattr(self.inspector, meth)
1207 formatter = format_screen if info.ismagic else None
1205 formatter = format_screen if info.ismagic else None
1208 if meth == 'pdoc':
1206 if meth == 'pdoc':
1209 pmethod(info.obj, oname, formatter)
1207 pmethod(info.obj, oname, formatter)
1210 elif meth == 'pinfo':
1208 elif meth == 'pinfo':
1211 pmethod(info.obj, oname, formatter, info, **kw)
1209 pmethod(info.obj, oname, formatter, info, **kw)
1212 else:
1210 else:
1213 pmethod(info.obj, oname)
1211 pmethod(info.obj, oname)
1214 else:
1212 else:
1215 print 'Object `%s` not found.' % oname
1213 print 'Object `%s` not found.' % oname
1216 return 'not found' # so callers can take other action
1214 return 'not found' # so callers can take other action
1217
1215
1218 def object_inspect(self, oname):
1216 def object_inspect(self, oname):
1219 info = self._object_find(oname)
1217 info = self._object_find(oname)
1220 if info.found:
1218 if info.found:
1221 return self.inspector.info(info.obj, oname, info=info)
1219 return self.inspector.info(info.obj, oname, info=info)
1222 else:
1220 else:
1223 return oinspect.object_info(name=oname, found=False)
1221 return oinspect.object_info(name=oname, found=False)
1224
1222
1225 #-------------------------------------------------------------------------
1223 #-------------------------------------------------------------------------
1226 # Things related to history management
1224 # Things related to history management
1227 #-------------------------------------------------------------------------
1225 #-------------------------------------------------------------------------
1228
1226
1229 def init_history(self):
1227 def init_history(self):
1230 self.history_manager = HistoryManager(shell=self)
1228 self.history_manager = HistoryManager(shell=self)
1231
1229
1232 def save_hist(self):
1230 def save_hist(self):
1233 """Save input history to a file (via readline library)."""
1231 """Save input history to a file (via readline library)."""
1234 self.history_manager.save_hist()
1232 self.history_manager.save_hist()
1235
1233
1236 # For backwards compatibility
1234 # For backwards compatibility
1237 savehist = save_hist
1235 savehist = save_hist
1238
1236
1239 def reload_hist(self):
1237 def reload_hist(self):
1240 """Reload the input history from disk file."""
1238 """Reload the input history from disk file."""
1241 self.history_manager.reload_hist()
1239 self.history_manager.reload_hist()
1242
1240
1243 # For backwards compatibility
1241 # For backwards compatibility
1244 reloadhist = reload_hist
1242 reloadhist = reload_hist
1245
1243
1246 def history_saving_wrapper(self, func):
1244 def history_saving_wrapper(self, func):
1247 """ Wrap func for readline history saving
1245 """ Wrap func for readline history saving
1248
1246
1249 Convert func into callable that saves & restores
1247 Convert func into callable that saves & restores
1250 history around the call """
1248 history around the call """
1251
1249
1252 if self.has_readline:
1250 if self.has_readline:
1253 from IPython.utils import rlineimpl as readline
1251 from IPython.utils import rlineimpl as readline
1254 else:
1252 else:
1255 return func
1253 return func
1256
1254
1257 def wrapper():
1255 def wrapper():
1258 self.save_hist()
1256 self.save_hist()
1259 try:
1257 try:
1260 func()
1258 func()
1261 finally:
1259 finally:
1262 readline.read_history_file(self.histfile)
1260 readline.read_history_file(self.histfile)
1263 return wrapper
1261 return wrapper
1264
1262
1265 #-------------------------------------------------------------------------
1263 #-------------------------------------------------------------------------
1266 # Things related to exception handling and tracebacks (not debugging)
1264 # Things related to exception handling and tracebacks (not debugging)
1267 #-------------------------------------------------------------------------
1265 #-------------------------------------------------------------------------
1268
1266
1269 def init_traceback_handlers(self, custom_exceptions):
1267 def init_traceback_handlers(self, custom_exceptions):
1270 # Syntax error handler.
1268 # Syntax error handler.
1271 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor')
1269 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor')
1272
1270
1273 # The interactive one is initialized with an offset, meaning we always
1271 # The interactive one is initialized with an offset, meaning we always
1274 # want to remove the topmost item in the traceback, which is our own
1272 # want to remove the topmost item in the traceback, which is our own
1275 # internal code. Valid modes: ['Plain','Context','Verbose']
1273 # internal code. Valid modes: ['Plain','Context','Verbose']
1276 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1274 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1277 color_scheme='NoColor',
1275 color_scheme='NoColor',
1278 tb_offset = 1,
1276 tb_offset = 1,
1279 check_cache=self.compile.check_cache)
1277 check_cache=self.compile.check_cache)
1280
1278
1281 # The instance will store a pointer to the system-wide exception hook,
1279 # The instance will store a pointer to the system-wide exception hook,
1282 # so that runtime code (such as magics) can access it. This is because
1280 # so that runtime code (such as magics) can access it. This is because
1283 # during the read-eval loop, it may get temporarily overwritten.
1281 # during the read-eval loop, it may get temporarily overwritten.
1284 self.sys_excepthook = sys.excepthook
1282 self.sys_excepthook = sys.excepthook
1285
1283
1286 # and add any custom exception handlers the user may have specified
1284 # and add any custom exception handlers the user may have specified
1287 self.set_custom_exc(*custom_exceptions)
1285 self.set_custom_exc(*custom_exceptions)
1288
1286
1289 # Set the exception mode
1287 # Set the exception mode
1290 self.InteractiveTB.set_mode(mode=self.xmode)
1288 self.InteractiveTB.set_mode(mode=self.xmode)
1291
1289
1292 def set_custom_exc(self, exc_tuple, handler):
1290 def set_custom_exc(self, exc_tuple, handler):
1293 """set_custom_exc(exc_tuple,handler)
1291 """set_custom_exc(exc_tuple,handler)
1294
1292
1295 Set a custom exception handler, which will be called if any of the
1293 Set a custom exception handler, which will be called if any of the
1296 exceptions in exc_tuple occur in the mainloop (specifically, in the
1294 exceptions in exc_tuple occur in the mainloop (specifically, in the
1297 run_code() method.
1295 run_code() method.
1298
1296
1299 Inputs:
1297 Inputs:
1300
1298
1301 - exc_tuple: a *tuple* of valid exceptions to call the defined
1299 - exc_tuple: a *tuple* of valid exceptions to call the defined
1302 handler for. It is very important that you use a tuple, and NOT A
1300 handler for. It is very important that you use a tuple, and NOT A
1303 LIST here, because of the way Python's except statement works. If
1301 LIST here, because of the way Python's except statement works. If
1304 you only want to trap a single exception, use a singleton tuple:
1302 you only want to trap a single exception, use a singleton tuple:
1305
1303
1306 exc_tuple == (MyCustomException,)
1304 exc_tuple == (MyCustomException,)
1307
1305
1308 - handler: this must be defined as a function with the following
1306 - handler: this must be defined as a function with the following
1309 basic interface::
1307 basic interface::
1310
1308
1311 def my_handler(self, etype, value, tb, tb_offset=None)
1309 def my_handler(self, etype, value, tb, tb_offset=None)
1312 ...
1310 ...
1313 # The return value must be
1311 # The return value must be
1314 return structured_traceback
1312 return structured_traceback
1315
1313
1316 This will be made into an instance method (via new.instancemethod)
1314 This will be made into an instance method (via types.MethodType)
1317 of IPython itself, and it will be called if any of the exceptions
1315 of IPython itself, and it will be called if any of the exceptions
1318 listed in the exc_tuple are caught. If the handler is None, an
1316 listed in the exc_tuple are caught. If the handler is None, an
1319 internal basic one is used, which just prints basic info.
1317 internal basic one is used, which just prints basic info.
1320
1318
1321 WARNING: by putting in your own exception handler into IPython's main
1319 WARNING: by putting in your own exception handler into IPython's main
1322 execution loop, you run a very good chance of nasty crashes. This
1320 execution loop, you run a very good chance of nasty crashes. This
1323 facility should only be used if you really know what you are doing."""
1321 facility should only be used if you really know what you are doing."""
1324
1322
1325 assert type(exc_tuple)==type(()) , \
1323 assert type(exc_tuple)==type(()) , \
1326 "The custom exceptions must be given AS A TUPLE."
1324 "The custom exceptions must be given AS A TUPLE."
1327
1325
1328 def dummy_handler(self,etype,value,tb):
1326 def dummy_handler(self,etype,value,tb):
1329 print '*** Simple custom exception handler ***'
1327 print '*** Simple custom exception handler ***'
1330 print 'Exception type :',etype
1328 print 'Exception type :',etype
1331 print 'Exception value:',value
1329 print 'Exception value:',value
1332 print 'Traceback :',tb
1330 print 'Traceback :',tb
1333 print 'Source code :','\n'.join(self.buffer)
1331 print 'Source code :','\n'.join(self.buffer)
1334
1332
1335 if handler is None: handler = dummy_handler
1333 if handler is None: handler = dummy_handler
1336
1334
1337 self.CustomTB = new.instancemethod(handler,self,self.__class__)
1335 self.CustomTB = types.MethodType(handler,self)
1338 self.custom_exceptions = exc_tuple
1336 self.custom_exceptions = exc_tuple
1339
1337
1340 def excepthook(self, etype, value, tb):
1338 def excepthook(self, etype, value, tb):
1341 """One more defense for GUI apps that call sys.excepthook.
1339 """One more defense for GUI apps that call sys.excepthook.
1342
1340
1343 GUI frameworks like wxPython trap exceptions and call
1341 GUI frameworks like wxPython trap exceptions and call
1344 sys.excepthook themselves. I guess this is a feature that
1342 sys.excepthook themselves. I guess this is a feature that
1345 enables them to keep running after exceptions that would
1343 enables them to keep running after exceptions that would
1346 otherwise kill their mainloop. This is a bother for IPython
1344 otherwise kill their mainloop. This is a bother for IPython
1347 which excepts to catch all of the program exceptions with a try:
1345 which excepts to catch all of the program exceptions with a try:
1348 except: statement.
1346 except: statement.
1349
1347
1350 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1348 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1351 any app directly invokes sys.excepthook, it will look to the user like
1349 any app directly invokes sys.excepthook, it will look to the user like
1352 IPython crashed. In order to work around this, we can disable the
1350 IPython crashed. In order to work around this, we can disable the
1353 CrashHandler and replace it with this excepthook instead, which prints a
1351 CrashHandler and replace it with this excepthook instead, which prints a
1354 regular traceback using our InteractiveTB. In this fashion, apps which
1352 regular traceback using our InteractiveTB. In this fashion, apps which
1355 call sys.excepthook will generate a regular-looking exception from
1353 call sys.excepthook will generate a regular-looking exception from
1356 IPython, and the CrashHandler will only be triggered by real IPython
1354 IPython, and the CrashHandler will only be triggered by real IPython
1357 crashes.
1355 crashes.
1358
1356
1359 This hook should be used sparingly, only in places which are not likely
1357 This hook should be used sparingly, only in places which are not likely
1360 to be true IPython errors.
1358 to be true IPython errors.
1361 """
1359 """
1362 self.showtraceback((etype,value,tb),tb_offset=0)
1360 self.showtraceback((etype,value,tb),tb_offset=0)
1363
1361
1364 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None,
1362 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None,
1365 exception_only=False):
1363 exception_only=False):
1366 """Display the exception that just occurred.
1364 """Display the exception that just occurred.
1367
1365
1368 If nothing is known about the exception, this is the method which
1366 If nothing is known about the exception, this is the method which
1369 should be used throughout the code for presenting user tracebacks,
1367 should be used throughout the code for presenting user tracebacks,
1370 rather than directly invoking the InteractiveTB object.
1368 rather than directly invoking the InteractiveTB object.
1371
1369
1372 A specific showsyntaxerror() also exists, but this method can take
1370 A specific showsyntaxerror() also exists, but this method can take
1373 care of calling it if needed, so unless you are explicitly catching a
1371 care of calling it if needed, so unless you are explicitly catching a
1374 SyntaxError exception, don't try to analyze the stack manually and
1372 SyntaxError exception, don't try to analyze the stack manually and
1375 simply call this method."""
1373 simply call this method."""
1376
1374
1377 try:
1375 try:
1378 if exc_tuple is None:
1376 if exc_tuple is None:
1379 etype, value, tb = sys.exc_info()
1377 etype, value, tb = sys.exc_info()
1380 else:
1378 else:
1381 etype, value, tb = exc_tuple
1379 etype, value, tb = exc_tuple
1382
1380
1383 if etype is None:
1381 if etype is None:
1384 if hasattr(sys, 'last_type'):
1382 if hasattr(sys, 'last_type'):
1385 etype, value, tb = sys.last_type, sys.last_value, \
1383 etype, value, tb = sys.last_type, sys.last_value, \
1386 sys.last_traceback
1384 sys.last_traceback
1387 else:
1385 else:
1388 self.write_err('No traceback available to show.\n')
1386 self.write_err('No traceback available to show.\n')
1389 return
1387 return
1390
1388
1391 if etype is SyntaxError:
1389 if etype is SyntaxError:
1392 # Though this won't be called by syntax errors in the input
1390 # Though this won't be called by syntax errors in the input
1393 # line, there may be SyntaxError cases whith imported code.
1391 # line, there may be SyntaxError cases whith imported code.
1394 self.showsyntaxerror(filename)
1392 self.showsyntaxerror(filename)
1395 elif etype is UsageError:
1393 elif etype is UsageError:
1396 print "UsageError:", value
1394 print "UsageError:", value
1397 else:
1395 else:
1398 # WARNING: these variables are somewhat deprecated and not
1396 # WARNING: these variables are somewhat deprecated and not
1399 # necessarily safe to use in a threaded environment, but tools
1397 # necessarily safe to use in a threaded environment, but tools
1400 # like pdb depend on their existence, so let's set them. If we
1398 # like pdb depend on their existence, so let's set them. If we
1401 # find problems in the field, we'll need to revisit their use.
1399 # find problems in the field, we'll need to revisit their use.
1402 sys.last_type = etype
1400 sys.last_type = etype
1403 sys.last_value = value
1401 sys.last_value = value
1404 sys.last_traceback = tb
1402 sys.last_traceback = tb
1405
1403
1406 if etype in self.custom_exceptions:
1404 if etype in self.custom_exceptions:
1407 # FIXME: Old custom traceback objects may just return a
1405 # FIXME: Old custom traceback objects may just return a
1408 # string, in that case we just put it into a list
1406 # string, in that case we just put it into a list
1409 stb = self.CustomTB(etype, value, tb, tb_offset)
1407 stb = self.CustomTB(etype, value, tb, tb_offset)
1410 if isinstance(ctb, basestring):
1408 if isinstance(ctb, basestring):
1411 stb = [stb]
1409 stb = [stb]
1412 else:
1410 else:
1413 if exception_only:
1411 if exception_only:
1414 stb = ['An exception has occurred, use %tb to see '
1412 stb = ['An exception has occurred, use %tb to see '
1415 'the full traceback.\n']
1413 'the full traceback.\n']
1416 stb.extend(self.InteractiveTB.get_exception_only(etype,
1414 stb.extend(self.InteractiveTB.get_exception_only(etype,
1417 value))
1415 value))
1418 else:
1416 else:
1419 stb = self.InteractiveTB.structured_traceback(etype,
1417 stb = self.InteractiveTB.structured_traceback(etype,
1420 value, tb, tb_offset=tb_offset)
1418 value, tb, tb_offset=tb_offset)
1421 # FIXME: the pdb calling should be done by us, not by
1419 # FIXME: the pdb calling should be done by us, not by
1422 # the code computing the traceback.
1420 # the code computing the traceback.
1423 if self.InteractiveTB.call_pdb:
1421 if self.InteractiveTB.call_pdb:
1424 # pdb mucks up readline, fix it back
1422 # pdb mucks up readline, fix it back
1425 self.set_readline_completer()
1423 self.set_readline_completer()
1426
1424
1427 # Actually show the traceback
1425 # Actually show the traceback
1428 self._showtraceback(etype, value, stb)
1426 self._showtraceback(etype, value, stb)
1429
1427
1430 except KeyboardInterrupt:
1428 except KeyboardInterrupt:
1431 self.write_err("\nKeyboardInterrupt\n")
1429 self.write_err("\nKeyboardInterrupt\n")
1432
1430
1433 def _showtraceback(self, etype, evalue, stb):
1431 def _showtraceback(self, etype, evalue, stb):
1434 """Actually show a traceback.
1432 """Actually show a traceback.
1435
1433
1436 Subclasses may override this method to put the traceback on a different
1434 Subclasses may override this method to put the traceback on a different
1437 place, like a side channel.
1435 place, like a side channel.
1438 """
1436 """
1439 print >> io.Term.cout, self.InteractiveTB.stb2text(stb)
1437 print >> io.Term.cout, self.InteractiveTB.stb2text(stb)
1440
1438
1441 def showsyntaxerror(self, filename=None):
1439 def showsyntaxerror(self, filename=None):
1442 """Display the syntax error that just occurred.
1440 """Display the syntax error that just occurred.
1443
1441
1444 This doesn't display a stack trace because there isn't one.
1442 This doesn't display a stack trace because there isn't one.
1445
1443
1446 If a filename is given, it is stuffed in the exception instead
1444 If a filename is given, it is stuffed in the exception instead
1447 of what was there before (because Python's parser always uses
1445 of what was there before (because Python's parser always uses
1448 "<string>" when reading from a string).
1446 "<string>" when reading from a string).
1449 """
1447 """
1450 etype, value, last_traceback = sys.exc_info()
1448 etype, value, last_traceback = sys.exc_info()
1451
1449
1452 # See note about these variables in showtraceback() above
1450 # See note about these variables in showtraceback() above
1453 sys.last_type = etype
1451 sys.last_type = etype
1454 sys.last_value = value
1452 sys.last_value = value
1455 sys.last_traceback = last_traceback
1453 sys.last_traceback = last_traceback
1456
1454
1457 if filename and etype is SyntaxError:
1455 if filename and etype is SyntaxError:
1458 # Work hard to stuff the correct filename in the exception
1456 # Work hard to stuff the correct filename in the exception
1459 try:
1457 try:
1460 msg, (dummy_filename, lineno, offset, line) = value
1458 msg, (dummy_filename, lineno, offset, line) = value
1461 except:
1459 except:
1462 # Not the format we expect; leave it alone
1460 # Not the format we expect; leave it alone
1463 pass
1461 pass
1464 else:
1462 else:
1465 # Stuff in the right filename
1463 # Stuff in the right filename
1466 try:
1464 try:
1467 # Assume SyntaxError is a class exception
1465 # Assume SyntaxError is a class exception
1468 value = SyntaxError(msg, (filename, lineno, offset, line))
1466 value = SyntaxError(msg, (filename, lineno, offset, line))
1469 except:
1467 except:
1470 # If that failed, assume SyntaxError is a string
1468 # If that failed, assume SyntaxError is a string
1471 value = msg, (filename, lineno, offset, line)
1469 value = msg, (filename, lineno, offset, line)
1472 stb = self.SyntaxTB.structured_traceback(etype, value, [])
1470 stb = self.SyntaxTB.structured_traceback(etype, value, [])
1473 self._showtraceback(etype, value, stb)
1471 self._showtraceback(etype, value, stb)
1474
1472
1475 #-------------------------------------------------------------------------
1473 #-------------------------------------------------------------------------
1476 # Things related to readline
1474 # Things related to readline
1477 #-------------------------------------------------------------------------
1475 #-------------------------------------------------------------------------
1478
1476
1479 def init_readline(self):
1477 def init_readline(self):
1480 """Command history completion/saving/reloading."""
1478 """Command history completion/saving/reloading."""
1481
1479
1482 if self.readline_use:
1480 if self.readline_use:
1483 import IPython.utils.rlineimpl as readline
1481 import IPython.utils.rlineimpl as readline
1484
1482
1485 self.rl_next_input = None
1483 self.rl_next_input = None
1486 self.rl_do_indent = False
1484 self.rl_do_indent = False
1487
1485
1488 if not self.readline_use or not readline.have_readline:
1486 if not self.readline_use or not readline.have_readline:
1489 self.has_readline = False
1487 self.has_readline = False
1490 self.readline = None
1488 self.readline = None
1491 # Set a number of methods that depend on readline to be no-op
1489 # Set a number of methods that depend on readline to be no-op
1492 self.save_hist = no_op
1490 self.save_hist = no_op
1493 self.reload_hist = no_op
1491 self.reload_hist = no_op
1494 self.set_readline_completer = no_op
1492 self.set_readline_completer = no_op
1495 self.set_custom_completer = no_op
1493 self.set_custom_completer = no_op
1496 self.set_completer_frame = no_op
1494 self.set_completer_frame = no_op
1497 warn('Readline services not available or not loaded.')
1495 warn('Readline services not available or not loaded.')
1498 else:
1496 else:
1499 self.has_readline = True
1497 self.has_readline = True
1500 self.readline = readline
1498 self.readline = readline
1501 sys.modules['readline'] = readline
1499 sys.modules['readline'] = readline
1502
1500
1503 # Platform-specific configuration
1501 # Platform-specific configuration
1504 if os.name == 'nt':
1502 if os.name == 'nt':
1505 # FIXME - check with Frederick to see if we can harmonize
1503 # FIXME - check with Frederick to see if we can harmonize
1506 # naming conventions with pyreadline to avoid this
1504 # naming conventions with pyreadline to avoid this
1507 # platform-dependent check
1505 # platform-dependent check
1508 self.readline_startup_hook = readline.set_pre_input_hook
1506 self.readline_startup_hook = readline.set_pre_input_hook
1509 else:
1507 else:
1510 self.readline_startup_hook = readline.set_startup_hook
1508 self.readline_startup_hook = readline.set_startup_hook
1511
1509
1512 # Load user's initrc file (readline config)
1510 # Load user's initrc file (readline config)
1513 # Or if libedit is used, load editrc.
1511 # Or if libedit is used, load editrc.
1514 inputrc_name = os.environ.get('INPUTRC')
1512 inputrc_name = os.environ.get('INPUTRC')
1515 if inputrc_name is None:
1513 if inputrc_name is None:
1516 home_dir = get_home_dir()
1514 home_dir = get_home_dir()
1517 if home_dir is not None:
1515 if home_dir is not None:
1518 inputrc_name = '.inputrc'
1516 inputrc_name = '.inputrc'
1519 if readline.uses_libedit:
1517 if readline.uses_libedit:
1520 inputrc_name = '.editrc'
1518 inputrc_name = '.editrc'
1521 inputrc_name = os.path.join(home_dir, inputrc_name)
1519 inputrc_name = os.path.join(home_dir, inputrc_name)
1522 if os.path.isfile(inputrc_name):
1520 if os.path.isfile(inputrc_name):
1523 try:
1521 try:
1524 readline.read_init_file(inputrc_name)
1522 readline.read_init_file(inputrc_name)
1525 except:
1523 except:
1526 warn('Problems reading readline initialization file <%s>'
1524 warn('Problems reading readline initialization file <%s>'
1527 % inputrc_name)
1525 % inputrc_name)
1528
1526
1529 # Configure readline according to user's prefs
1527 # Configure readline according to user's prefs
1530 # This is only done if GNU readline is being used. If libedit
1528 # This is only done if GNU readline is being used. If libedit
1531 # is being used (as on Leopard) the readline config is
1529 # is being used (as on Leopard) the readline config is
1532 # not run as the syntax for libedit is different.
1530 # not run as the syntax for libedit is different.
1533 if not readline.uses_libedit:
1531 if not readline.uses_libedit:
1534 for rlcommand in self.readline_parse_and_bind:
1532 for rlcommand in self.readline_parse_and_bind:
1535 #print "loading rl:",rlcommand # dbg
1533 #print "loading rl:",rlcommand # dbg
1536 readline.parse_and_bind(rlcommand)
1534 readline.parse_and_bind(rlcommand)
1537
1535
1538 # Remove some chars from the delimiters list. If we encounter
1536 # Remove some chars from the delimiters list. If we encounter
1539 # unicode chars, discard them.
1537 # unicode chars, discard them.
1540 delims = readline.get_completer_delims().encode("ascii", "ignore")
1538 delims = readline.get_completer_delims().encode("ascii", "ignore")
1541 delims = delims.translate(string._idmap,
1539 delims = delims.translate(None, self.readline_remove_delims)
1542 self.readline_remove_delims)
1543 delims = delims.replace(ESC_MAGIC, '')
1540 delims = delims.replace(ESC_MAGIC, '')
1544 readline.set_completer_delims(delims)
1541 readline.set_completer_delims(delims)
1545 # otherwise we end up with a monster history after a while:
1542 # otherwise we end up with a monster history after a while:
1546 readline.set_history_length(1000)
1543 readline.set_history_length(1000)
1547 try:
1544 try:
1548 #print '*** Reading readline history' # dbg
1545 #print '*** Reading readline history' # dbg
1549 readline.read_history_file(self.histfile)
1546 readline.read_history_file(self.histfile)
1550 except IOError:
1547 except IOError:
1551 pass # It doesn't exist yet.
1548 pass # It doesn't exist yet.
1552
1549
1553 # If we have readline, we want our history saved upon ipython
1550 # If we have readline, we want our history saved upon ipython
1554 # exiting.
1551 # exiting.
1555 atexit.register(self.save_hist)
1552 atexit.register(self.save_hist)
1556
1553
1557 # Configure auto-indent for all platforms
1554 # Configure auto-indent for all platforms
1558 self.set_autoindent(self.autoindent)
1555 self.set_autoindent(self.autoindent)
1559
1556
1560 def set_next_input(self, s):
1557 def set_next_input(self, s):
1561 """ Sets the 'default' input string for the next command line.
1558 """ Sets the 'default' input string for the next command line.
1562
1559
1563 Requires readline.
1560 Requires readline.
1564
1561
1565 Example:
1562 Example:
1566
1563
1567 [D:\ipython]|1> _ip.set_next_input("Hello Word")
1564 [D:\ipython]|1> _ip.set_next_input("Hello Word")
1568 [D:\ipython]|2> Hello Word_ # cursor is here
1565 [D:\ipython]|2> Hello Word_ # cursor is here
1569 """
1566 """
1570
1567
1571 self.rl_next_input = s
1568 self.rl_next_input = s
1572
1569
1573 # Maybe move this to the terminal subclass?
1570 # Maybe move this to the terminal subclass?
1574 def pre_readline(self):
1571 def pre_readline(self):
1575 """readline hook to be used at the start of each line.
1572 """readline hook to be used at the start of each line.
1576
1573
1577 Currently it handles auto-indent only."""
1574 Currently it handles auto-indent only."""
1578
1575
1579 if self.rl_do_indent:
1576 if self.rl_do_indent:
1580 self.readline.insert_text(self._indent_current_str())
1577 self.readline.insert_text(self._indent_current_str())
1581 if self.rl_next_input is not None:
1578 if self.rl_next_input is not None:
1582 self.readline.insert_text(self.rl_next_input)
1579 self.readline.insert_text(self.rl_next_input)
1583 self.rl_next_input = None
1580 self.rl_next_input = None
1584
1581
1585 def _indent_current_str(self):
1582 def _indent_current_str(self):
1586 """return the current level of indentation as a string"""
1583 """return the current level of indentation as a string"""
1587 return self.input_splitter.indent_spaces * ' '
1584 return self.input_splitter.indent_spaces * ' '
1588
1585
1589 #-------------------------------------------------------------------------
1586 #-------------------------------------------------------------------------
1590 # Things related to text completion
1587 # Things related to text completion
1591 #-------------------------------------------------------------------------
1588 #-------------------------------------------------------------------------
1592
1589
1593 def init_completer(self):
1590 def init_completer(self):
1594 """Initialize the completion machinery.
1591 """Initialize the completion machinery.
1595
1592
1596 This creates completion machinery that can be used by client code,
1593 This creates completion machinery that can be used by client code,
1597 either interactively in-process (typically triggered by the readline
1594 either interactively in-process (typically triggered by the readline
1598 library), programatically (such as in test suites) or out-of-prcess
1595 library), programatically (such as in test suites) or out-of-prcess
1599 (typically over the network by remote frontends).
1596 (typically over the network by remote frontends).
1600 """
1597 """
1601 from IPython.core.completer import IPCompleter
1598 from IPython.core.completer import IPCompleter
1602 from IPython.core.completerlib import (module_completer,
1599 from IPython.core.completerlib import (module_completer,
1603 magic_run_completer, cd_completer)
1600 magic_run_completer, cd_completer)
1604
1601
1605 self.Completer = IPCompleter(self,
1602 self.Completer = IPCompleter(self,
1606 self.user_ns,
1603 self.user_ns,
1607 self.user_global_ns,
1604 self.user_global_ns,
1608 self.readline_omit__names,
1605 self.readline_omit__names,
1609 self.alias_manager.alias_table,
1606 self.alias_manager.alias_table,
1610 self.has_readline)
1607 self.has_readline)
1611
1608
1612 # Add custom completers to the basic ones built into IPCompleter
1609 # Add custom completers to the basic ones built into IPCompleter
1613 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1610 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1614 self.strdispatchers['complete_command'] = sdisp
1611 self.strdispatchers['complete_command'] = sdisp
1615 self.Completer.custom_completers = sdisp
1612 self.Completer.custom_completers = sdisp
1616
1613
1617 self.set_hook('complete_command', module_completer, str_key = 'import')
1614 self.set_hook('complete_command', module_completer, str_key = 'import')
1618 self.set_hook('complete_command', module_completer, str_key = 'from')
1615 self.set_hook('complete_command', module_completer, str_key = 'from')
1619 self.set_hook('complete_command', magic_run_completer, str_key = '%run')
1616 self.set_hook('complete_command', magic_run_completer, str_key = '%run')
1620 self.set_hook('complete_command', cd_completer, str_key = '%cd')
1617 self.set_hook('complete_command', cd_completer, str_key = '%cd')
1621
1618
1622 # Only configure readline if we truly are using readline. IPython can
1619 # Only configure readline if we truly are using readline. IPython can
1623 # do tab-completion over the network, in GUIs, etc, where readline
1620 # do tab-completion over the network, in GUIs, etc, where readline
1624 # itself may be absent
1621 # itself may be absent
1625 if self.has_readline:
1622 if self.has_readline:
1626 self.set_readline_completer()
1623 self.set_readline_completer()
1627
1624
1628 def complete(self, text, line=None, cursor_pos=None):
1625 def complete(self, text, line=None, cursor_pos=None):
1629 """Return the completed text and a list of completions.
1626 """Return the completed text and a list of completions.
1630
1627
1631 Parameters
1628 Parameters
1632 ----------
1629 ----------
1633
1630
1634 text : string
1631 text : string
1635 A string of text to be completed on. It can be given as empty and
1632 A string of text to be completed on. It can be given as empty and
1636 instead a line/position pair are given. In this case, the
1633 instead a line/position pair are given. In this case, the
1637 completer itself will split the line like readline does.
1634 completer itself will split the line like readline does.
1638
1635
1639 line : string, optional
1636 line : string, optional
1640 The complete line that text is part of.
1637 The complete line that text is part of.
1641
1638
1642 cursor_pos : int, optional
1639 cursor_pos : int, optional
1643 The position of the cursor on the input line.
1640 The position of the cursor on the input line.
1644
1641
1645 Returns
1642 Returns
1646 -------
1643 -------
1647 text : string
1644 text : string
1648 The actual text that was completed.
1645 The actual text that was completed.
1649
1646
1650 matches : list
1647 matches : list
1651 A sorted list with all possible completions.
1648 A sorted list with all possible completions.
1652
1649
1653 The optional arguments allow the completion to take more context into
1650 The optional arguments allow the completion to take more context into
1654 account, and are part of the low-level completion API.
1651 account, and are part of the low-level completion API.
1655
1652
1656 This is a wrapper around the completion mechanism, similar to what
1653 This is a wrapper around the completion mechanism, similar to what
1657 readline does at the command line when the TAB key is hit. By
1654 readline does at the command line when the TAB key is hit. By
1658 exposing it as a method, it can be used by other non-readline
1655 exposing it as a method, it can be used by other non-readline
1659 environments (such as GUIs) for text completion.
1656 environments (such as GUIs) for text completion.
1660
1657
1661 Simple usage example:
1658 Simple usage example:
1662
1659
1663 In [1]: x = 'hello'
1660 In [1]: x = 'hello'
1664
1661
1665 In [2]: _ip.complete('x.l')
1662 In [2]: _ip.complete('x.l')
1666 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
1663 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
1667 """
1664 """
1668
1665
1669 # Inject names into __builtin__ so we can complete on the added names.
1666 # Inject names into __builtin__ so we can complete on the added names.
1670 with self.builtin_trap:
1667 with self.builtin_trap:
1671 return self.Completer.complete(text, line, cursor_pos)
1668 return self.Completer.complete(text, line, cursor_pos)
1672
1669
1673 def set_custom_completer(self, completer, pos=0):
1670 def set_custom_completer(self, completer, pos=0):
1674 """Adds a new custom completer function.
1671 """Adds a new custom completer function.
1675
1672
1676 The position argument (defaults to 0) is the index in the completers
1673 The position argument (defaults to 0) is the index in the completers
1677 list where you want the completer to be inserted."""
1674 list where you want the completer to be inserted."""
1678
1675
1679 newcomp = new.instancemethod(completer,self.Completer,
1676 newcomp = types.MethodType(completer,self.Completer)
1680 self.Completer.__class__)
1681 self.Completer.matchers.insert(pos,newcomp)
1677 self.Completer.matchers.insert(pos,newcomp)
1682
1678
1683 def set_readline_completer(self):
1679 def set_readline_completer(self):
1684 """Reset readline's completer to be our own."""
1680 """Reset readline's completer to be our own."""
1685 self.readline.set_completer(self.Completer.rlcomplete)
1681 self.readline.set_completer(self.Completer.rlcomplete)
1686
1682
1687 def set_completer_frame(self, frame=None):
1683 def set_completer_frame(self, frame=None):
1688 """Set the frame of the completer."""
1684 """Set the frame of the completer."""
1689 if frame:
1685 if frame:
1690 self.Completer.namespace = frame.f_locals
1686 self.Completer.namespace = frame.f_locals
1691 self.Completer.global_namespace = frame.f_globals
1687 self.Completer.global_namespace = frame.f_globals
1692 else:
1688 else:
1693 self.Completer.namespace = self.user_ns
1689 self.Completer.namespace = self.user_ns
1694 self.Completer.global_namespace = self.user_global_ns
1690 self.Completer.global_namespace = self.user_global_ns
1695
1691
1696 #-------------------------------------------------------------------------
1692 #-------------------------------------------------------------------------
1697 # Things related to magics
1693 # Things related to magics
1698 #-------------------------------------------------------------------------
1694 #-------------------------------------------------------------------------
1699
1695
1700 def init_magics(self):
1696 def init_magics(self):
1701 # FIXME: Move the color initialization to the DisplayHook, which
1697 # FIXME: Move the color initialization to the DisplayHook, which
1702 # should be split into a prompt manager and displayhook. We probably
1698 # should be split into a prompt manager and displayhook. We probably
1703 # even need a centralize colors management object.
1699 # even need a centralize colors management object.
1704 self.magic_colors(self.colors)
1700 self.magic_colors(self.colors)
1705 # History was moved to a separate module
1701 # History was moved to a separate module
1706 from . import history
1702 from . import history
1707 history.init_ipython(self)
1703 history.init_ipython(self)
1708
1704
1709 def magic(self,arg_s):
1705 def magic(self,arg_s):
1710 """Call a magic function by name.
1706 """Call a magic function by name.
1711
1707
1712 Input: a string containing the name of the magic function to call and
1708 Input: a string containing the name of the magic function to call and
1713 any additional arguments to be passed to the magic.
1709 any additional arguments to be passed to the magic.
1714
1710
1715 magic('name -opt foo bar') is equivalent to typing at the ipython
1711 magic('name -opt foo bar') is equivalent to typing at the ipython
1716 prompt:
1712 prompt:
1717
1713
1718 In[1]: %name -opt foo bar
1714 In[1]: %name -opt foo bar
1719
1715
1720 To call a magic without arguments, simply use magic('name').
1716 To call a magic without arguments, simply use magic('name').
1721
1717
1722 This provides a proper Python function to call IPython's magics in any
1718 This provides a proper Python function to call IPython's magics in any
1723 valid Python code you can type at the interpreter, including loops and
1719 valid Python code you can type at the interpreter, including loops and
1724 compound statements.
1720 compound statements.
1725 """
1721 """
1726 args = arg_s.split(' ',1)
1722 args = arg_s.split(' ',1)
1727 magic_name = args[0]
1723 magic_name = args[0]
1728 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
1724 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
1729
1725
1730 try:
1726 try:
1731 magic_args = args[1]
1727 magic_args = args[1]
1732 except IndexError:
1728 except IndexError:
1733 magic_args = ''
1729 magic_args = ''
1734 fn = getattr(self,'magic_'+magic_name,None)
1730 fn = getattr(self,'magic_'+magic_name,None)
1735 if fn is None:
1731 if fn is None:
1736 error("Magic function `%s` not found." % magic_name)
1732 error("Magic function `%s` not found." % magic_name)
1737 else:
1733 else:
1738 magic_args = self.var_expand(magic_args,1)
1734 magic_args = self.var_expand(magic_args,1)
1739 with nested(self.builtin_trap,):
1735 with nested(self.builtin_trap,):
1740 result = fn(magic_args)
1736 result = fn(magic_args)
1741 return result
1737 return result
1742
1738
1743 def define_magic(self, magicname, func):
1739 def define_magic(self, magicname, func):
1744 """Expose own function as magic function for ipython
1740 """Expose own function as magic function for ipython
1745
1741
1746 def foo_impl(self,parameter_s=''):
1742 def foo_impl(self,parameter_s=''):
1747 'My very own magic!. (Use docstrings, IPython reads them).'
1743 'My very own magic!. (Use docstrings, IPython reads them).'
1748 print 'Magic function. Passed parameter is between < >:'
1744 print 'Magic function. Passed parameter is between < >:'
1749 print '<%s>' % parameter_s
1745 print '<%s>' % parameter_s
1750 print 'The self object is:',self
1746 print 'The self object is:',self
1751
1747
1752 self.define_magic('foo',foo_impl)
1748 self.define_magic('foo',foo_impl)
1753 """
1749 """
1754
1750
1755 import new
1751 import new
1756 im = new.instancemethod(func,self, self.__class__)
1752 im = types.MethodType(func,self)
1757 old = getattr(self, "magic_" + magicname, None)
1753 old = getattr(self, "magic_" + magicname, None)
1758 setattr(self, "magic_" + magicname, im)
1754 setattr(self, "magic_" + magicname, im)
1759 return old
1755 return old
1760
1756
1761 #-------------------------------------------------------------------------
1757 #-------------------------------------------------------------------------
1762 # Things related to macros
1758 # Things related to macros
1763 #-------------------------------------------------------------------------
1759 #-------------------------------------------------------------------------
1764
1760
1765 def define_macro(self, name, themacro):
1761 def define_macro(self, name, themacro):
1766 """Define a new macro
1762 """Define a new macro
1767
1763
1768 Parameters
1764 Parameters
1769 ----------
1765 ----------
1770 name : str
1766 name : str
1771 The name of the macro.
1767 The name of the macro.
1772 themacro : str or Macro
1768 themacro : str or Macro
1773 The action to do upon invoking the macro. If a string, a new
1769 The action to do upon invoking the macro. If a string, a new
1774 Macro object is created by passing the string to it.
1770 Macro object is created by passing the string to it.
1775 """
1771 """
1776
1772
1777 from IPython.core import macro
1773 from IPython.core import macro
1778
1774
1779 if isinstance(themacro, basestring):
1775 if isinstance(themacro, basestring):
1780 themacro = macro.Macro(themacro)
1776 themacro = macro.Macro(themacro)
1781 if not isinstance(themacro, macro.Macro):
1777 if not isinstance(themacro, macro.Macro):
1782 raise ValueError('A macro must be a string or a Macro instance.')
1778 raise ValueError('A macro must be a string or a Macro instance.')
1783 self.user_ns[name] = themacro
1779 self.user_ns[name] = themacro
1784
1780
1785 #-------------------------------------------------------------------------
1781 #-------------------------------------------------------------------------
1786 # Things related to the running of system commands
1782 # Things related to the running of system commands
1787 #-------------------------------------------------------------------------
1783 #-------------------------------------------------------------------------
1788
1784
1789 def system(self, cmd):
1785 def system(self, cmd):
1790 """Call the given cmd in a subprocess.
1786 """Call the given cmd in a subprocess.
1791
1787
1792 Parameters
1788 Parameters
1793 ----------
1789 ----------
1794 cmd : str
1790 cmd : str
1795 Command to execute (can not end in '&', as bacground processes are
1791 Command to execute (can not end in '&', as bacground processes are
1796 not supported.
1792 not supported.
1797 """
1793 """
1798 # We do not support backgrounding processes because we either use
1794 # We do not support backgrounding processes because we either use
1799 # pexpect or pipes to read from. Users can always just call
1795 # pexpect or pipes to read from. Users can always just call
1800 # os.system() if they really want a background process.
1796 # os.system() if they really want a background process.
1801 if cmd.endswith('&'):
1797 if cmd.endswith('&'):
1802 raise OSError("Background processes not supported.")
1798 raise OSError("Background processes not supported.")
1803
1799
1804 return system(self.var_expand(cmd, depth=2))
1800 return system(self.var_expand(cmd, depth=2))
1805
1801
1806 def getoutput(self, cmd, split=True):
1802 def getoutput(self, cmd, split=True):
1807 """Get output (possibly including stderr) from a subprocess.
1803 """Get output (possibly including stderr) from a subprocess.
1808
1804
1809 Parameters
1805 Parameters
1810 ----------
1806 ----------
1811 cmd : str
1807 cmd : str
1812 Command to execute (can not end in '&', as background processes are
1808 Command to execute (can not end in '&', as background processes are
1813 not supported.
1809 not supported.
1814 split : bool, optional
1810 split : bool, optional
1815
1811
1816 If True, split the output into an IPython SList. Otherwise, an
1812 If True, split the output into an IPython SList. Otherwise, an
1817 IPython LSString is returned. These are objects similar to normal
1813 IPython LSString is returned. These are objects similar to normal
1818 lists and strings, with a few convenience attributes for easier
1814 lists and strings, with a few convenience attributes for easier
1819 manipulation of line-based output. You can use '?' on them for
1815 manipulation of line-based output. You can use '?' on them for
1820 details.
1816 details.
1821 """
1817 """
1822 if cmd.endswith('&'):
1818 if cmd.endswith('&'):
1823 raise OSError("Background processes not supported.")
1819 raise OSError("Background processes not supported.")
1824 out = getoutput(self.var_expand(cmd, depth=2))
1820 out = getoutput(self.var_expand(cmd, depth=2))
1825 if split:
1821 if split:
1826 out = SList(out.splitlines())
1822 out = SList(out.splitlines())
1827 else:
1823 else:
1828 out = LSString(out)
1824 out = LSString(out)
1829 return out
1825 return out
1830
1826
1831 #-------------------------------------------------------------------------
1827 #-------------------------------------------------------------------------
1832 # Things related to aliases
1828 # Things related to aliases
1833 #-------------------------------------------------------------------------
1829 #-------------------------------------------------------------------------
1834
1830
1835 def init_alias(self):
1831 def init_alias(self):
1836 self.alias_manager = AliasManager(shell=self, config=self.config)
1832 self.alias_manager = AliasManager(shell=self, config=self.config)
1837 self.ns_table['alias'] = self.alias_manager.alias_table,
1833 self.ns_table['alias'] = self.alias_manager.alias_table,
1838
1834
1839 #-------------------------------------------------------------------------
1835 #-------------------------------------------------------------------------
1840 # Things related to extensions and plugins
1836 # Things related to extensions and plugins
1841 #-------------------------------------------------------------------------
1837 #-------------------------------------------------------------------------
1842
1838
1843 def init_extension_manager(self):
1839 def init_extension_manager(self):
1844 self.extension_manager = ExtensionManager(shell=self, config=self.config)
1840 self.extension_manager = ExtensionManager(shell=self, config=self.config)
1845
1841
1846 def init_plugin_manager(self):
1842 def init_plugin_manager(self):
1847 self.plugin_manager = PluginManager(config=self.config)
1843 self.plugin_manager = PluginManager(config=self.config)
1848
1844
1849 #-------------------------------------------------------------------------
1845 #-------------------------------------------------------------------------
1850 # Things related to payloads
1846 # Things related to payloads
1851 #-------------------------------------------------------------------------
1847 #-------------------------------------------------------------------------
1852
1848
1853 def init_payload(self):
1849 def init_payload(self):
1854 self.payload_manager = PayloadManager(config=self.config)
1850 self.payload_manager = PayloadManager(config=self.config)
1855
1851
1856 #-------------------------------------------------------------------------
1852 #-------------------------------------------------------------------------
1857 # Things related to the prefilter
1853 # Things related to the prefilter
1858 #-------------------------------------------------------------------------
1854 #-------------------------------------------------------------------------
1859
1855
1860 def init_prefilter(self):
1856 def init_prefilter(self):
1861 self.prefilter_manager = PrefilterManager(shell=self, config=self.config)
1857 self.prefilter_manager = PrefilterManager(shell=self, config=self.config)
1862 # Ultimately this will be refactored in the new interpreter code, but
1858 # Ultimately this will be refactored in the new interpreter code, but
1863 # for now, we should expose the main prefilter method (there's legacy
1859 # for now, we should expose the main prefilter method (there's legacy
1864 # code out there that may rely on this).
1860 # code out there that may rely on this).
1865 self.prefilter = self.prefilter_manager.prefilter_lines
1861 self.prefilter = self.prefilter_manager.prefilter_lines
1866
1862
1867 def auto_rewrite_input(self, cmd):
1863 def auto_rewrite_input(self, cmd):
1868 """Print to the screen the rewritten form of the user's command.
1864 """Print to the screen the rewritten form of the user's command.
1869
1865
1870 This shows visual feedback by rewriting input lines that cause
1866 This shows visual feedback by rewriting input lines that cause
1871 automatic calling to kick in, like::
1867 automatic calling to kick in, like::
1872
1868
1873 /f x
1869 /f x
1874
1870
1875 into::
1871 into::
1876
1872
1877 ------> f(x)
1873 ------> f(x)
1878
1874
1879 after the user's input prompt. This helps the user understand that the
1875 after the user's input prompt. This helps the user understand that the
1880 input line was transformed automatically by IPython.
1876 input line was transformed automatically by IPython.
1881 """
1877 """
1882 rw = self.displayhook.prompt1.auto_rewrite() + cmd
1878 rw = self.displayhook.prompt1.auto_rewrite() + cmd
1883
1879
1884 try:
1880 try:
1885 # plain ascii works better w/ pyreadline, on some machines, so
1881 # plain ascii works better w/ pyreadline, on some machines, so
1886 # we use it and only print uncolored rewrite if we have unicode
1882 # we use it and only print uncolored rewrite if we have unicode
1887 rw = str(rw)
1883 rw = str(rw)
1888 print >> IPython.utils.io.Term.cout, rw
1884 print >> IPython.utils.io.Term.cout, rw
1889 except UnicodeEncodeError:
1885 except UnicodeEncodeError:
1890 print "------> " + cmd
1886 print "------> " + cmd
1891
1887
1892 #-------------------------------------------------------------------------
1888 #-------------------------------------------------------------------------
1893 # Things related to extracting values/expressions from kernel and user_ns
1889 # Things related to extracting values/expressions from kernel and user_ns
1894 #-------------------------------------------------------------------------
1890 #-------------------------------------------------------------------------
1895
1891
1896 def _simple_error(self):
1892 def _simple_error(self):
1897 etype, value = sys.exc_info()[:2]
1893 etype, value = sys.exc_info()[:2]
1898 return u'[ERROR] {e.__name__}: {v}'.format(e=etype, v=value)
1894 return u'[ERROR] {e.__name__}: {v}'.format(e=etype, v=value)
1899
1895
1900 def user_variables(self, names):
1896 def user_variables(self, names):
1901 """Get a list of variable names from the user's namespace.
1897 """Get a list of variable names from the user's namespace.
1902
1898
1903 Parameters
1899 Parameters
1904 ----------
1900 ----------
1905 names : list of strings
1901 names : list of strings
1906 A list of names of variables to be read from the user namespace.
1902 A list of names of variables to be read from the user namespace.
1907
1903
1908 Returns
1904 Returns
1909 -------
1905 -------
1910 A dict, keyed by the input names and with the repr() of each value.
1906 A dict, keyed by the input names and with the repr() of each value.
1911 """
1907 """
1912 out = {}
1908 out = {}
1913 user_ns = self.user_ns
1909 user_ns = self.user_ns
1914 for varname in names:
1910 for varname in names:
1915 try:
1911 try:
1916 value = repr(user_ns[varname])
1912 value = repr(user_ns[varname])
1917 except:
1913 except:
1918 value = self._simple_error()
1914 value = self._simple_error()
1919 out[varname] = value
1915 out[varname] = value
1920 return out
1916 return out
1921
1917
1922 def user_expressions(self, expressions):
1918 def user_expressions(self, expressions):
1923 """Evaluate a dict of expressions in the user's namespace.
1919 """Evaluate a dict of expressions in the user's namespace.
1924
1920
1925 Parameters
1921 Parameters
1926 ----------
1922 ----------
1927 expressions : dict
1923 expressions : dict
1928 A dict with string keys and string values. The expression values
1924 A dict with string keys and string values. The expression values
1929 should be valid Python expressions, each of which will be evaluated
1925 should be valid Python expressions, each of which will be evaluated
1930 in the user namespace.
1926 in the user namespace.
1931
1927
1932 Returns
1928 Returns
1933 -------
1929 -------
1934 A dict, keyed like the input expressions dict, with the repr() of each
1930 A dict, keyed like the input expressions dict, with the repr() of each
1935 value.
1931 value.
1936 """
1932 """
1937 out = {}
1933 out = {}
1938 user_ns = self.user_ns
1934 user_ns = self.user_ns
1939 global_ns = self.user_global_ns
1935 global_ns = self.user_global_ns
1940 for key, expr in expressions.iteritems():
1936 for key, expr in expressions.iteritems():
1941 try:
1937 try:
1942 value = repr(eval(expr, global_ns, user_ns))
1938 value = repr(eval(expr, global_ns, user_ns))
1943 except:
1939 except:
1944 value = self._simple_error()
1940 value = self._simple_error()
1945 out[key] = value
1941 out[key] = value
1946 return out
1942 return out
1947
1943
1948 #-------------------------------------------------------------------------
1944 #-------------------------------------------------------------------------
1949 # Things related to the running of code
1945 # Things related to the running of code
1950 #-------------------------------------------------------------------------
1946 #-------------------------------------------------------------------------
1951
1947
1952 def ex(self, cmd):
1948 def ex(self, cmd):
1953 """Execute a normal python statement in user namespace."""
1949 """Execute a normal python statement in user namespace."""
1954 with nested(self.builtin_trap,):
1950 with nested(self.builtin_trap,):
1955 exec cmd in self.user_global_ns, self.user_ns
1951 exec cmd in self.user_global_ns, self.user_ns
1956
1952
1957 def ev(self, expr):
1953 def ev(self, expr):
1958 """Evaluate python expression expr in user namespace.
1954 """Evaluate python expression expr in user namespace.
1959
1955
1960 Returns the result of evaluation
1956 Returns the result of evaluation
1961 """
1957 """
1962 with nested(self.builtin_trap,):
1958 with nested(self.builtin_trap,):
1963 return eval(expr, self.user_global_ns, self.user_ns)
1959 return eval(expr, self.user_global_ns, self.user_ns)
1964
1960
1965 def safe_execfile(self, fname, *where, **kw):
1961 def safe_execfile(self, fname, *where, **kw):
1966 """A safe version of the builtin execfile().
1962 """A safe version of the builtin execfile().
1967
1963
1968 This version will never throw an exception, but instead print
1964 This version will never throw an exception, but instead print
1969 helpful error messages to the screen. This only works on pure
1965 helpful error messages to the screen. This only works on pure
1970 Python files with the .py extension.
1966 Python files with the .py extension.
1971
1967
1972 Parameters
1968 Parameters
1973 ----------
1969 ----------
1974 fname : string
1970 fname : string
1975 The name of the file to be executed.
1971 The name of the file to be executed.
1976 where : tuple
1972 where : tuple
1977 One or two namespaces, passed to execfile() as (globals,locals).
1973 One or two namespaces, passed to execfile() as (globals,locals).
1978 If only one is given, it is passed as both.
1974 If only one is given, it is passed as both.
1979 exit_ignore : bool (False)
1975 exit_ignore : bool (False)
1980 If True, then silence SystemExit for non-zero status (it is always
1976 If True, then silence SystemExit for non-zero status (it is always
1981 silenced for zero status, as it is so common).
1977 silenced for zero status, as it is so common).
1982 """
1978 """
1983 kw.setdefault('exit_ignore', False)
1979 kw.setdefault('exit_ignore', False)
1984
1980
1985 fname = os.path.abspath(os.path.expanduser(fname))
1981 fname = os.path.abspath(os.path.expanduser(fname))
1986
1982
1987 # Make sure we have a .py file
1983 # Make sure we have a .py file
1988 if not fname.endswith('.py'):
1984 if not fname.endswith('.py'):
1989 warn('File must end with .py to be run using execfile: <%s>' % fname)
1985 warn('File must end with .py to be run using execfile: <%s>' % fname)
1990
1986
1991 # Make sure we can open the file
1987 # Make sure we can open the file
1992 try:
1988 try:
1993 with open(fname) as thefile:
1989 with open(fname) as thefile:
1994 pass
1990 pass
1995 except:
1991 except:
1996 warn('Could not open file <%s> for safe execution.' % fname)
1992 warn('Could not open file <%s> for safe execution.' % fname)
1997 return
1993 return
1998
1994
1999 # Find things also in current directory. This is needed to mimic the
1995 # Find things also in current directory. This is needed to mimic the
2000 # behavior of running a script from the system command line, where
1996 # behavior of running a script from the system command line, where
2001 # Python inserts the script's directory into sys.path
1997 # Python inserts the script's directory into sys.path
2002 dname = os.path.dirname(fname)
1998 dname = os.path.dirname(fname)
2003
1999
2004 with prepended_to_syspath(dname):
2000 with prepended_to_syspath(dname):
2005 try:
2001 try:
2006 execfile(fname,*where)
2002 execfile(fname,*where)
2007 except SystemExit, status:
2003 except SystemExit, status:
2008 # If the call was made with 0 or None exit status (sys.exit(0)
2004 # If the call was made with 0 or None exit status (sys.exit(0)
2009 # or sys.exit() ), don't bother showing a traceback, as both of
2005 # or sys.exit() ), don't bother showing a traceback, as both of
2010 # these are considered normal by the OS:
2006 # these are considered normal by the OS:
2011 # > python -c'import sys;sys.exit(0)'; echo $?
2007 # > python -c'import sys;sys.exit(0)'; echo $?
2012 # 0
2008 # 0
2013 # > python -c'import sys;sys.exit()'; echo $?
2009 # > python -c'import sys;sys.exit()'; echo $?
2014 # 0
2010 # 0
2015 # For other exit status, we show the exception unless
2011 # For other exit status, we show the exception unless
2016 # explicitly silenced, but only in short form.
2012 # explicitly silenced, but only in short form.
2017 if status.code not in (0, None) and not kw['exit_ignore']:
2013 if status.code not in (0, None) and not kw['exit_ignore']:
2018 self.showtraceback(exception_only=True)
2014 self.showtraceback(exception_only=True)
2019 except:
2015 except:
2020 self.showtraceback()
2016 self.showtraceback()
2021
2017
2022 def safe_execfile_ipy(self, fname):
2018 def safe_execfile_ipy(self, fname):
2023 """Like safe_execfile, but for .ipy files with IPython syntax.
2019 """Like safe_execfile, but for .ipy files with IPython syntax.
2024
2020
2025 Parameters
2021 Parameters
2026 ----------
2022 ----------
2027 fname : str
2023 fname : str
2028 The name of the file to execute. The filename must have a
2024 The name of the file to execute. The filename must have a
2029 .ipy extension.
2025 .ipy extension.
2030 """
2026 """
2031 fname = os.path.abspath(os.path.expanduser(fname))
2027 fname = os.path.abspath(os.path.expanduser(fname))
2032
2028
2033 # Make sure we have a .py file
2029 # Make sure we have a .py file
2034 if not fname.endswith('.ipy'):
2030 if not fname.endswith('.ipy'):
2035 warn('File must end with .py to be run using execfile: <%s>' % fname)
2031 warn('File must end with .py to be run using execfile: <%s>' % fname)
2036
2032
2037 # Make sure we can open the file
2033 # Make sure we can open the file
2038 try:
2034 try:
2039 with open(fname) as thefile:
2035 with open(fname) as thefile:
2040 pass
2036 pass
2041 except:
2037 except:
2042 warn('Could not open file <%s> for safe execution.' % fname)
2038 warn('Could not open file <%s> for safe execution.' % fname)
2043 return
2039 return
2044
2040
2045 # Find things also in current directory. This is needed to mimic the
2041 # Find things also in current directory. This is needed to mimic the
2046 # behavior of running a script from the system command line, where
2042 # behavior of running a script from the system command line, where
2047 # Python inserts the script's directory into sys.path
2043 # Python inserts the script's directory into sys.path
2048 dname = os.path.dirname(fname)
2044 dname = os.path.dirname(fname)
2049
2045
2050 with prepended_to_syspath(dname):
2046 with prepended_to_syspath(dname):
2051 try:
2047 try:
2052 with open(fname) as thefile:
2048 with open(fname) as thefile:
2053 # self.run_cell currently captures all exceptions
2049 # self.run_cell currently captures all exceptions
2054 # raised in user code. It would be nice if there were
2050 # raised in user code. It would be nice if there were
2055 # versions of runlines, execfile that did raise, so
2051 # versions of runlines, execfile that did raise, so
2056 # we could catch the errors.
2052 # we could catch the errors.
2057 self.run_cell(thefile.read())
2053 self.run_cell(thefile.read())
2058 except:
2054 except:
2059 self.showtraceback()
2055 self.showtraceback()
2060 warn('Unknown failure executing file: <%s>' % fname)
2056 warn('Unknown failure executing file: <%s>' % fname)
2061
2057
2062 def run_cell(self, cell):
2058 def run_cell(self, cell):
2063 """Run the contents of an entire multiline 'cell' of code.
2059 """Run the contents of an entire multiline 'cell' of code.
2064
2060
2065 The cell is split into separate blocks which can be executed
2061 The cell is split into separate blocks which can be executed
2066 individually. Then, based on how many blocks there are, they are
2062 individually. Then, based on how many blocks there are, they are
2067 executed as follows:
2063 executed as follows:
2068
2064
2069 - A single block: 'single' mode.
2065 - A single block: 'single' mode.
2070
2066
2071 If there's more than one block, it depends:
2067 If there's more than one block, it depends:
2072
2068
2073 - if the last one is no more than two lines long, run all but the last
2069 - if the last one is no more than two lines long, run all but the last
2074 in 'exec' mode and the very last one in 'single' mode. This makes it
2070 in 'exec' mode and the very last one in 'single' mode. This makes it
2075 easy to type simple expressions at the end to see computed values. -
2071 easy to type simple expressions at the end to see computed values. -
2076 otherwise (last one is also multiline), run all in 'exec' mode
2072 otherwise (last one is also multiline), run all in 'exec' mode
2077
2073
2078 When code is executed in 'single' mode, :func:`sys.displayhook` fires,
2074 When code is executed in 'single' mode, :func:`sys.displayhook` fires,
2079 results are displayed and output prompts are computed. In 'exec' mode,
2075 results are displayed and output prompts are computed. In 'exec' mode,
2080 no results are displayed unless :func:`print` is called explicitly;
2076 no results are displayed unless :func:`print` is called explicitly;
2081 this mode is more akin to running a script.
2077 this mode is more akin to running a script.
2082
2078
2083 Parameters
2079 Parameters
2084 ----------
2080 ----------
2085 cell : str
2081 cell : str
2086 A single or multiline string.
2082 A single or multiline string.
2087 """
2083 """
2088
2084
2089 # We need to break up the input into executable blocks that can be run
2085 # We need to break up the input into executable blocks that can be run
2090 # in 'single' mode, to provide comfortable user behavior.
2086 # in 'single' mode, to provide comfortable user behavior.
2091 blocks = self.input_splitter.split_blocks(cell)
2087 blocks = self.input_splitter.split_blocks(cell)
2092
2088
2093 if not blocks:
2089 if not blocks:
2094 return
2090 return
2095
2091
2096 # Store the 'ipython' version of the cell as well, since that's what
2092 # Store the 'ipython' version of the cell as well, since that's what
2097 # needs to go into the translated history and get executed (the
2093 # needs to go into the translated history and get executed (the
2098 # original cell may contain non-python syntax).
2094 # original cell may contain non-python syntax).
2099 ipy_cell = ''.join(blocks)
2095 ipy_cell = ''.join(blocks)
2100
2096
2101 # Store raw and processed history
2097 # Store raw and processed history
2102 self.history_manager.store_inputs(ipy_cell, cell)
2098 self.history_manager.store_inputs(ipy_cell, cell)
2103
2099
2104 self.logger.log(ipy_cell, cell)
2100 self.logger.log(ipy_cell, cell)
2105 # dbg code!!!
2101 # dbg code!!!
2106 if 0:
2102 if 0:
2107 def myapp(self, val): # dbg
2103 def myapp(self, val): # dbg
2108 import traceback as tb
2104 import traceback as tb
2109 stack = ''.join(tb.format_stack())
2105 stack = ''.join(tb.format_stack())
2110 print 'Value:', val
2106 print 'Value:', val
2111 print 'Stack:\n', stack
2107 print 'Stack:\n', stack
2112 list.append(self, val)
2108 list.append(self, val)
2113
2109
2114 import new
2110 import new
2115 self.input_hist.append = new.instancemethod(myapp, self.input_hist,
2111 self.input_hist.append = types.MethodType(myapp, self.input_hist)
2116 list)
2117 # End dbg
2112 # End dbg
2118
2113
2119 # All user code execution must happen with our context managers active
2114 # All user code execution must happen with our context managers active
2120 with nested(self.builtin_trap, self.display_trap):
2115 with nested(self.builtin_trap, self.display_trap):
2121
2116
2122 # Single-block input should behave like an interactive prompt
2117 # Single-block input should behave like an interactive prompt
2123 if len(blocks) == 1:
2118 if len(blocks) == 1:
2124 # since we return here, we need to update the execution count
2119 # since we return here, we need to update the execution count
2125 out = self.run_one_block(blocks[0])
2120 out = self.run_one_block(blocks[0])
2126 self.execution_count += 1
2121 self.execution_count += 1
2127 return out
2122 return out
2128
2123
2129 # In multi-block input, if the last block is a simple (one-two
2124 # In multi-block input, if the last block is a simple (one-two
2130 # lines) expression, run it in single mode so it produces output.
2125 # lines) expression, run it in single mode so it produces output.
2131 # Otherwise just feed the whole thing to run_code. This seems like
2126 # Otherwise just feed the whole thing to run_code. This seems like
2132 # a reasonable usability design.
2127 # a reasonable usability design.
2133 last = blocks[-1]
2128 last = blocks[-1]
2134 last_nlines = len(last.splitlines())
2129 last_nlines = len(last.splitlines())
2135
2130
2136 # Note: below, whenever we call run_code, we must sync history
2131 # Note: below, whenever we call run_code, we must sync history
2137 # ourselves, because run_code is NOT meant to manage history at all.
2132 # ourselves, because run_code is NOT meant to manage history at all.
2138 if last_nlines < 2:
2133 if last_nlines < 2:
2139 # Here we consider the cell split between 'body' and 'last',
2134 # Here we consider the cell split between 'body' and 'last',
2140 # store all history and execute 'body', and if successful, then
2135 # store all history and execute 'body', and if successful, then
2141 # proceed to execute 'last'.
2136 # proceed to execute 'last'.
2142
2137
2143 # Get the main body to run as a cell
2138 # Get the main body to run as a cell
2144 ipy_body = ''.join(blocks[:-1])
2139 ipy_body = ''.join(blocks[:-1])
2145 retcode = self.run_source(ipy_body, symbol='exec',
2140 retcode = self.run_source(ipy_body, symbol='exec',
2146 post_execute=False)
2141 post_execute=False)
2147 if retcode==0:
2142 if retcode==0:
2148 # And the last expression via runlines so it produces output
2143 # And the last expression via runlines so it produces output
2149 self.run_one_block(last)
2144 self.run_one_block(last)
2150 else:
2145 else:
2151 # Run the whole cell as one entity, storing both raw and
2146 # Run the whole cell as one entity, storing both raw and
2152 # processed input in history
2147 # processed input in history
2153 self.run_source(ipy_cell, symbol='exec')
2148 self.run_source(ipy_cell, symbol='exec')
2154
2149
2155 # Each cell is a *single* input, regardless of how many lines it has
2150 # Each cell is a *single* input, regardless of how many lines it has
2156 self.execution_count += 1
2151 self.execution_count += 1
2157
2152
2158 def run_one_block(self, block):
2153 def run_one_block(self, block):
2159 """Run a single interactive block.
2154 """Run a single interactive block.
2160
2155
2161 If the block is single-line, dynamic transformations are applied to it
2156 If the block is single-line, dynamic transformations are applied to it
2162 (like automagics, autocall and alias recognition).
2157 (like automagics, autocall and alias recognition).
2163 """
2158 """
2164 if len(block.splitlines()) <= 1:
2159 if len(block.splitlines()) <= 1:
2165 out = self.run_single_line(block)
2160 out = self.run_single_line(block)
2166 else:
2161 else:
2167 out = self.run_code(block)
2162 out = self.run_code(block)
2168 return out
2163 return out
2169
2164
2170 def run_single_line(self, line):
2165 def run_single_line(self, line):
2171 """Run a single-line interactive statement.
2166 """Run a single-line interactive statement.
2172
2167
2173 This assumes the input has been transformed to IPython syntax by
2168 This assumes the input has been transformed to IPython syntax by
2174 applying all static transformations (those with an explicit prefix like
2169 applying all static transformations (those with an explicit prefix like
2175 % or !), but it will further try to apply the dynamic ones.
2170 % or !), but it will further try to apply the dynamic ones.
2176
2171
2177 It does not update history.
2172 It does not update history.
2178 """
2173 """
2179 tline = self.prefilter_manager.prefilter_line(line)
2174 tline = self.prefilter_manager.prefilter_line(line)
2180 return self.run_source(tline)
2175 return self.run_source(tline)
2181
2176
2182 # PENDING REMOVAL: this method is slated for deletion, once our new
2177 # PENDING REMOVAL: this method is slated for deletion, once our new
2183 # input logic has been 100% moved to frontends and is stable.
2178 # input logic has been 100% moved to frontends and is stable.
2184 def runlines(self, lines, clean=False):
2179 def runlines(self, lines, clean=False):
2185 """Run a string of one or more lines of source.
2180 """Run a string of one or more lines of source.
2186
2181
2187 This method is capable of running a string containing multiple source
2182 This method is capable of running a string containing multiple source
2188 lines, as if they had been entered at the IPython prompt. Since it
2183 lines, as if they had been entered at the IPython prompt. Since it
2189 exposes IPython's processing machinery, the given strings can contain
2184 exposes IPython's processing machinery, the given strings can contain
2190 magic calls (%magic), special shell access (!cmd), etc.
2185 magic calls (%magic), special shell access (!cmd), etc.
2191 """
2186 """
2192
2187
2193 if isinstance(lines, (list, tuple)):
2188 if isinstance(lines, (list, tuple)):
2194 lines = '\n'.join(lines)
2189 lines = '\n'.join(lines)
2195
2190
2196 if clean:
2191 if clean:
2197 lines = self._cleanup_ipy_script(lines)
2192 lines = self._cleanup_ipy_script(lines)
2198
2193
2199 # We must start with a clean buffer, in case this is run from an
2194 # We must start with a clean buffer, in case this is run from an
2200 # interactive IPython session (via a magic, for example).
2195 # interactive IPython session (via a magic, for example).
2201 self.reset_buffer()
2196 self.reset_buffer()
2202 lines = lines.splitlines()
2197 lines = lines.splitlines()
2203
2198
2204 # Since we will prefilter all lines, store the user's raw input too
2199 # Since we will prefilter all lines, store the user's raw input too
2205 # before we apply any transformations
2200 # before we apply any transformations
2206 self.buffer_raw[:] = [ l+'\n' for l in lines]
2201 self.buffer_raw[:] = [ l+'\n' for l in lines]
2207
2202
2208 more = False
2203 more = False
2209 prefilter_lines = self.prefilter_manager.prefilter_lines
2204 prefilter_lines = self.prefilter_manager.prefilter_lines
2210 with nested(self.builtin_trap, self.display_trap):
2205 with nested(self.builtin_trap, self.display_trap):
2211 for line in lines:
2206 for line in lines:
2212 # skip blank lines so we don't mess up the prompt counter, but
2207 # skip blank lines so we don't mess up the prompt counter, but
2213 # do NOT skip even a blank line if we are in a code block (more
2208 # do NOT skip even a blank line if we are in a code block (more
2214 # is true)
2209 # is true)
2215
2210
2216 if line or more:
2211 if line or more:
2217 more = self.push_line(prefilter_lines(line, more))
2212 more = self.push_line(prefilter_lines(line, more))
2218 # IPython's run_source returns None if there was an error
2213 # IPython's run_source returns None if there was an error
2219 # compiling the code. This allows us to stop processing
2214 # compiling the code. This allows us to stop processing
2220 # right away, so the user gets the error message at the
2215 # right away, so the user gets the error message at the
2221 # right place.
2216 # right place.
2222 if more is None:
2217 if more is None:
2223 break
2218 break
2224 # final newline in case the input didn't have it, so that the code
2219 # final newline in case the input didn't have it, so that the code
2225 # actually does get executed
2220 # actually does get executed
2226 if more:
2221 if more:
2227 self.push_line('\n')
2222 self.push_line('\n')
2228
2223
2229 def run_source(self, source, filename=None,
2224 def run_source(self, source, filename=None,
2230 symbol='single', post_execute=True):
2225 symbol='single', post_execute=True):
2231 """Compile and run some source in the interpreter.
2226 """Compile and run some source in the interpreter.
2232
2227
2233 Arguments are as for compile_command().
2228 Arguments are as for compile_command().
2234
2229
2235 One several things can happen:
2230 One several things can happen:
2236
2231
2237 1) The input is incorrect; compile_command() raised an
2232 1) The input is incorrect; compile_command() raised an
2238 exception (SyntaxError or OverflowError). A syntax traceback
2233 exception (SyntaxError or OverflowError). A syntax traceback
2239 will be printed by calling the showsyntaxerror() method.
2234 will be printed by calling the showsyntaxerror() method.
2240
2235
2241 2) The input is incomplete, and more input is required;
2236 2) The input is incomplete, and more input is required;
2242 compile_command() returned None. Nothing happens.
2237 compile_command() returned None. Nothing happens.
2243
2238
2244 3) The input is complete; compile_command() returned a code
2239 3) The input is complete; compile_command() returned a code
2245 object. The code is executed by calling self.run_code() (which
2240 object. The code is executed by calling self.run_code() (which
2246 also handles run-time exceptions, except for SystemExit).
2241 also handles run-time exceptions, except for SystemExit).
2247
2242
2248 The return value is:
2243 The return value is:
2249
2244
2250 - True in case 2
2245 - True in case 2
2251
2246
2252 - False in the other cases, unless an exception is raised, where
2247 - False in the other cases, unless an exception is raised, where
2253 None is returned instead. This can be used by external callers to
2248 None is returned instead. This can be used by external callers to
2254 know whether to continue feeding input or not.
2249 know whether to continue feeding input or not.
2255
2250
2256 The return value can be used to decide whether to use sys.ps1 or
2251 The return value can be used to decide whether to use sys.ps1 or
2257 sys.ps2 to prompt the next line."""
2252 sys.ps2 to prompt the next line."""
2258
2253
2259 # We need to ensure that the source is unicode from here on.
2254 # We need to ensure that the source is unicode from here on.
2260 if type(source)==str:
2255 if type(source)==str:
2261 usource = source.decode(self.stdin_encoding)
2256 usource = source.decode(self.stdin_encoding)
2262 else:
2257 else:
2263 usource = source
2258 usource = source
2264
2259
2265 if 0: # dbg
2260 if 0: # dbg
2266 print 'Source:', repr(source) # dbg
2261 print 'Source:', repr(source) # dbg
2267 print 'USource:', repr(usource) # dbg
2262 print 'USource:', repr(usource) # dbg
2268 print 'type:', type(source) # dbg
2263 print 'type:', type(source) # dbg
2269 print 'encoding', self.stdin_encoding # dbg
2264 print 'encoding', self.stdin_encoding # dbg
2270
2265
2271 try:
2266 try:
2272 code = self.compile(usource, symbol, self.execution_count)
2267 code = self.compile(usource, symbol, self.execution_count)
2273 except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError):
2268 except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError):
2274 # Case 1
2269 # Case 1
2275 self.showsyntaxerror(filename)
2270 self.showsyntaxerror(filename)
2276 return None
2271 return None
2277
2272
2278 if code is None:
2273 if code is None:
2279 # Case 2
2274 # Case 2
2280 return True
2275 return True
2281
2276
2282 # Case 3
2277 # Case 3
2283 # We store the code object so that threaded shells and
2278 # We store the code object so that threaded shells and
2284 # custom exception handlers can access all this info if needed.
2279 # custom exception handlers can access all this info if needed.
2285 # The source corresponding to this can be obtained from the
2280 # The source corresponding to this can be obtained from the
2286 # buffer attribute as '\n'.join(self.buffer).
2281 # buffer attribute as '\n'.join(self.buffer).
2287 self.code_to_run = code
2282 self.code_to_run = code
2288 # now actually execute the code object
2283 # now actually execute the code object
2289 if self.run_code(code, post_execute) == 0:
2284 if self.run_code(code, post_execute) == 0:
2290 return False
2285 return False
2291 else:
2286 else:
2292 return None
2287 return None
2293
2288
2294 # For backwards compatibility
2289 # For backwards compatibility
2295 runsource = run_source
2290 runsource = run_source
2296
2291
2297 def run_code(self, code_obj, post_execute=True):
2292 def run_code(self, code_obj, post_execute=True):
2298 """Execute a code object.
2293 """Execute a code object.
2299
2294
2300 When an exception occurs, self.showtraceback() is called to display a
2295 When an exception occurs, self.showtraceback() is called to display a
2301 traceback.
2296 traceback.
2302
2297
2303 Return value: a flag indicating whether the code to be run completed
2298 Return value: a flag indicating whether the code to be run completed
2304 successfully:
2299 successfully:
2305
2300
2306 - 0: successful execution.
2301 - 0: successful execution.
2307 - 1: an error occurred.
2302 - 1: an error occurred.
2308 """
2303 """
2309
2304
2310 # Set our own excepthook in case the user code tries to call it
2305 # Set our own excepthook in case the user code tries to call it
2311 # directly, so that the IPython crash handler doesn't get triggered
2306 # directly, so that the IPython crash handler doesn't get triggered
2312 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
2307 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
2313
2308
2314 # we save the original sys.excepthook in the instance, in case config
2309 # we save the original sys.excepthook in the instance, in case config
2315 # code (such as magics) needs access to it.
2310 # code (such as magics) needs access to it.
2316 self.sys_excepthook = old_excepthook
2311 self.sys_excepthook = old_excepthook
2317 outflag = 1 # happens in more places, so it's easier as default
2312 outflag = 1 # happens in more places, so it's easier as default
2318 try:
2313 try:
2319 try:
2314 try:
2320 self.hooks.pre_run_code_hook()
2315 self.hooks.pre_run_code_hook()
2321 #rprint('Running code') # dbg
2316 #rprint('Running code') # dbg
2322 exec code_obj in self.user_global_ns, self.user_ns
2317 exec code_obj in self.user_global_ns, self.user_ns
2323 finally:
2318 finally:
2324 # Reset our crash handler in place
2319 # Reset our crash handler in place
2325 sys.excepthook = old_excepthook
2320 sys.excepthook = old_excepthook
2326 except SystemExit:
2321 except SystemExit:
2327 self.reset_buffer()
2322 self.reset_buffer()
2328 self.showtraceback(exception_only=True)
2323 self.showtraceback(exception_only=True)
2329 warn("To exit: use any of 'exit', 'quit', %Exit or Ctrl-D.", level=1)
2324 warn("To exit: use any of 'exit', 'quit', %Exit or Ctrl-D.", level=1)
2330 except self.custom_exceptions:
2325 except self.custom_exceptions:
2331 etype,value,tb = sys.exc_info()
2326 etype,value,tb = sys.exc_info()
2332 self.CustomTB(etype,value,tb)
2327 self.CustomTB(etype,value,tb)
2333 except:
2328 except:
2334 self.showtraceback()
2329 self.showtraceback()
2335 else:
2330 else:
2336 outflag = 0
2331 outflag = 0
2337 if softspace(sys.stdout, 0):
2332 if softspace(sys.stdout, 0):
2338 print
2333 print
2339
2334
2340 # Execute any registered post-execution functions. Here, any errors
2335 # Execute any registered post-execution functions. Here, any errors
2341 # are reported only minimally and just on the terminal, because the
2336 # are reported only minimally and just on the terminal, because the
2342 # main exception channel may be occupied with a user traceback.
2337 # main exception channel may be occupied with a user traceback.
2343 # FIXME: we need to think this mechanism a little more carefully.
2338 # FIXME: we need to think this mechanism a little more carefully.
2344 if post_execute:
2339 if post_execute:
2345 for func in self._post_execute:
2340 for func in self._post_execute:
2346 try:
2341 try:
2347 func()
2342 func()
2348 except:
2343 except:
2349 head = '[ ERROR ] Evaluating post_execute function: %s' % \
2344 head = '[ ERROR ] Evaluating post_execute function: %s' % \
2350 func
2345 func
2351 print >> io.Term.cout, head
2346 print >> io.Term.cout, head
2352 print >> io.Term.cout, self._simple_error()
2347 print >> io.Term.cout, self._simple_error()
2353 print >> io.Term.cout, 'Removing from post_execute'
2348 print >> io.Term.cout, 'Removing from post_execute'
2354 self._post_execute.remove(func)
2349 self._post_execute.remove(func)
2355
2350
2356 # Flush out code object which has been run (and source)
2351 # Flush out code object which has been run (and source)
2357 self.code_to_run = None
2352 self.code_to_run = None
2358 return outflag
2353 return outflag
2359
2354
2360 # For backwards compatibility
2355 # For backwards compatibility
2361 runcode = run_code
2356 runcode = run_code
2362
2357
2363 # PENDING REMOVAL: this method is slated for deletion, once our new
2358 # PENDING REMOVAL: this method is slated for deletion, once our new
2364 # input logic has been 100% moved to frontends and is stable.
2359 # input logic has been 100% moved to frontends and is stable.
2365 def push_line(self, line):
2360 def push_line(self, line):
2366 """Push a line to the interpreter.
2361 """Push a line to the interpreter.
2367
2362
2368 The line should not have a trailing newline; it may have
2363 The line should not have a trailing newline; it may have
2369 internal newlines. The line is appended to a buffer and the
2364 internal newlines. The line is appended to a buffer and the
2370 interpreter's run_source() method is called with the
2365 interpreter's run_source() method is called with the
2371 concatenated contents of the buffer as source. If this
2366 concatenated contents of the buffer as source. If this
2372 indicates that the command was executed or invalid, the buffer
2367 indicates that the command was executed or invalid, the buffer
2373 is reset; otherwise, the command is incomplete, and the buffer
2368 is reset; otherwise, the command is incomplete, and the buffer
2374 is left as it was after the line was appended. The return
2369 is left as it was after the line was appended. The return
2375 value is 1 if more input is required, 0 if the line was dealt
2370 value is 1 if more input is required, 0 if the line was dealt
2376 with in some way (this is the same as run_source()).
2371 with in some way (this is the same as run_source()).
2377 """
2372 """
2378
2373
2379 # autoindent management should be done here, and not in the
2374 # autoindent management should be done here, and not in the
2380 # interactive loop, since that one is only seen by keyboard input. We
2375 # interactive loop, since that one is only seen by keyboard input. We
2381 # need this done correctly even for code run via runlines (which uses
2376 # need this done correctly even for code run via runlines (which uses
2382 # push).
2377 # push).
2383
2378
2384 #print 'push line: <%s>' % line # dbg
2379 #print 'push line: <%s>' % line # dbg
2385 self.buffer.append(line)
2380 self.buffer.append(line)
2386 full_source = '\n'.join(self.buffer)
2381 full_source = '\n'.join(self.buffer)
2387 more = self.run_source(full_source, self.filename)
2382 more = self.run_source(full_source, self.filename)
2388 if not more:
2383 if not more:
2389 self.history_manager.store_inputs('\n'.join(self.buffer_raw),
2384 self.history_manager.store_inputs('\n'.join(self.buffer_raw),
2390 full_source)
2385 full_source)
2391 self.reset_buffer()
2386 self.reset_buffer()
2392 self.execution_count += 1
2387 self.execution_count += 1
2393 return more
2388 return more
2394
2389
2395 def reset_buffer(self):
2390 def reset_buffer(self):
2396 """Reset the input buffer."""
2391 """Reset the input buffer."""
2397 self.buffer[:] = []
2392 self.buffer[:] = []
2398 self.buffer_raw[:] = []
2393 self.buffer_raw[:] = []
2399 self.input_splitter.reset()
2394 self.input_splitter.reset()
2400
2395
2401 # For backwards compatibility
2396 # For backwards compatibility
2402 resetbuffer = reset_buffer
2397 resetbuffer = reset_buffer
2403
2398
2404 def _is_secondary_block_start(self, s):
2399 def _is_secondary_block_start(self, s):
2405 if not s.endswith(':'):
2400 if not s.endswith(':'):
2406 return False
2401 return False
2407 if (s.startswith('elif') or
2402 if (s.startswith('elif') or
2408 s.startswith('else') or
2403 s.startswith('else') or
2409 s.startswith('except') or
2404 s.startswith('except') or
2410 s.startswith('finally')):
2405 s.startswith('finally')):
2411 return True
2406 return True
2412
2407
2413 def _cleanup_ipy_script(self, script):
2408 def _cleanup_ipy_script(self, script):
2414 """Make a script safe for self.runlines()
2409 """Make a script safe for self.runlines()
2415
2410
2416 Currently, IPython is lines based, with blocks being detected by
2411 Currently, IPython is lines based, with blocks being detected by
2417 empty lines. This is a problem for block based scripts that may
2412 empty lines. This is a problem for block based scripts that may
2418 not have empty lines after blocks. This script adds those empty
2413 not have empty lines after blocks. This script adds those empty
2419 lines to make scripts safe for running in the current line based
2414 lines to make scripts safe for running in the current line based
2420 IPython.
2415 IPython.
2421 """
2416 """
2422 res = []
2417 res = []
2423 lines = script.splitlines()
2418 lines = script.splitlines()
2424 level = 0
2419 level = 0
2425
2420
2426 for l in lines:
2421 for l in lines:
2427 lstripped = l.lstrip()
2422 lstripped = l.lstrip()
2428 stripped = l.strip()
2423 stripped = l.strip()
2429 if not stripped:
2424 if not stripped:
2430 continue
2425 continue
2431 newlevel = len(l) - len(lstripped)
2426 newlevel = len(l) - len(lstripped)
2432 if level > 0 and newlevel == 0 and \
2427 if level > 0 and newlevel == 0 and \
2433 not self._is_secondary_block_start(stripped):
2428 not self._is_secondary_block_start(stripped):
2434 # add empty line
2429 # add empty line
2435 res.append('')
2430 res.append('')
2436 res.append(l)
2431 res.append(l)
2437 level = newlevel
2432 level = newlevel
2438
2433
2439 return '\n'.join(res) + '\n'
2434 return '\n'.join(res) + '\n'
2440
2435
2441 #-------------------------------------------------------------------------
2436 #-------------------------------------------------------------------------
2442 # Things related to GUI support and pylab
2437 # Things related to GUI support and pylab
2443 #-------------------------------------------------------------------------
2438 #-------------------------------------------------------------------------
2444
2439
2445 def enable_pylab(self, gui=None):
2440 def enable_pylab(self, gui=None):
2446 raise NotImplementedError('Implement enable_pylab in a subclass')
2441 raise NotImplementedError('Implement enable_pylab in a subclass')
2447
2442
2448 #-------------------------------------------------------------------------
2443 #-------------------------------------------------------------------------
2449 # Utilities
2444 # Utilities
2450 #-------------------------------------------------------------------------
2445 #-------------------------------------------------------------------------
2451
2446
2452 def var_expand(self,cmd,depth=0):
2447 def var_expand(self,cmd,depth=0):
2453 """Expand python variables in a string.
2448 """Expand python variables in a string.
2454
2449
2455 The depth argument indicates how many frames above the caller should
2450 The depth argument indicates how many frames above the caller should
2456 be walked to look for the local namespace where to expand variables.
2451 be walked to look for the local namespace where to expand variables.
2457
2452
2458 The global namespace for expansion is always the user's interactive
2453 The global namespace for expansion is always the user's interactive
2459 namespace.
2454 namespace.
2460 """
2455 """
2461
2456
2462 return str(ItplNS(cmd,
2457 return str(ItplNS(cmd,
2463 self.user_ns, # globals
2458 self.user_ns, # globals
2464 # Skip our own frame in searching for locals:
2459 # Skip our own frame in searching for locals:
2465 sys._getframe(depth+1).f_locals # locals
2460 sys._getframe(depth+1).f_locals # locals
2466 ))
2461 ))
2467
2462
2468 def mktempfile(self, data=None, prefix='ipython_edit_'):
2463 def mktempfile(self, data=None, prefix='ipython_edit_'):
2469 """Make a new tempfile and return its filename.
2464 """Make a new tempfile and return its filename.
2470
2465
2471 This makes a call to tempfile.mktemp, but it registers the created
2466 This makes a call to tempfile.mktemp, but it registers the created
2472 filename internally so ipython cleans it up at exit time.
2467 filename internally so ipython cleans it up at exit time.
2473
2468
2474 Optional inputs:
2469 Optional inputs:
2475
2470
2476 - data(None): if data is given, it gets written out to the temp file
2471 - data(None): if data is given, it gets written out to the temp file
2477 immediately, and the file is closed again."""
2472 immediately, and the file is closed again."""
2478
2473
2479 filename = tempfile.mktemp('.py', prefix)
2474 filename = tempfile.mktemp('.py', prefix)
2480 self.tempfiles.append(filename)
2475 self.tempfiles.append(filename)
2481
2476
2482 if data:
2477 if data:
2483 tmp_file = open(filename,'w')
2478 tmp_file = open(filename,'w')
2484 tmp_file.write(data)
2479 tmp_file.write(data)
2485 tmp_file.close()
2480 tmp_file.close()
2486 return filename
2481 return filename
2487
2482
2488 # TODO: This should be removed when Term is refactored.
2483 # TODO: This should be removed when Term is refactored.
2489 def write(self,data):
2484 def write(self,data):
2490 """Write a string to the default output"""
2485 """Write a string to the default output"""
2491 io.Term.cout.write(data)
2486 io.Term.cout.write(data)
2492
2487
2493 # TODO: This should be removed when Term is refactored.
2488 # TODO: This should be removed when Term is refactored.
2494 def write_err(self,data):
2489 def write_err(self,data):
2495 """Write a string to the default error output"""
2490 """Write a string to the default error output"""
2496 io.Term.cerr.write(data)
2491 io.Term.cerr.write(data)
2497
2492
2498 def ask_yes_no(self,prompt,default=True):
2493 def ask_yes_no(self,prompt,default=True):
2499 if self.quiet:
2494 if self.quiet:
2500 return True
2495 return True
2501 return ask_yes_no(prompt,default)
2496 return ask_yes_no(prompt,default)
2502
2497
2503 def show_usage(self):
2498 def show_usage(self):
2504 """Show a usage message"""
2499 """Show a usage message"""
2505 page.page(IPython.core.usage.interactive_usage)
2500 page.page(IPython.core.usage.interactive_usage)
2506
2501
2507 #-------------------------------------------------------------------------
2502 #-------------------------------------------------------------------------
2508 # Things related to IPython exiting
2503 # Things related to IPython exiting
2509 #-------------------------------------------------------------------------
2504 #-------------------------------------------------------------------------
2510 def atexit_operations(self):
2505 def atexit_operations(self):
2511 """This will be executed at the time of exit.
2506 """This will be executed at the time of exit.
2512
2507
2513 Cleanup operations and saving of persistent data that is done
2508 Cleanup operations and saving of persistent data that is done
2514 unconditionally by IPython should be performed here.
2509 unconditionally by IPython should be performed here.
2515
2510
2516 For things that may depend on startup flags or platform specifics (such
2511 For things that may depend on startup flags or platform specifics (such
2517 as having readline or not), register a separate atexit function in the
2512 as having readline or not), register a separate atexit function in the
2518 code that has the appropriate information, rather than trying to
2513 code that has the appropriate information, rather than trying to
2519 clutter
2514 clutter
2520 """
2515 """
2521 # Cleanup all tempfiles left around
2516 # Cleanup all tempfiles left around
2522 for tfile in self.tempfiles:
2517 for tfile in self.tempfiles:
2523 try:
2518 try:
2524 os.unlink(tfile)
2519 os.unlink(tfile)
2525 except OSError:
2520 except OSError:
2526 pass
2521 pass
2527
2522
2528 # Clear all user namespaces to release all references cleanly.
2523 # Clear all user namespaces to release all references cleanly.
2529 self.reset()
2524 self.reset()
2530
2525
2531 # Run user hooks
2526 # Run user hooks
2532 self.hooks.shutdown_hook()
2527 self.hooks.shutdown_hook()
2533
2528
2534 def cleanup(self):
2529 def cleanup(self):
2535 self.restore_sys_module_state()
2530 self.restore_sys_module_state()
2536
2531
2537
2532
2538 class InteractiveShellABC(object):
2533 class InteractiveShellABC(object):
2539 """An abstract base class for InteractiveShell."""
2534 """An abstract base class for InteractiveShell."""
2540 __metaclass__ = abc.ABCMeta
2535 __metaclass__ = abc.ABCMeta
2541
2536
2542 InteractiveShellABC.register(InteractiveShell)
2537 InteractiveShellABC.register(InteractiveShell)
@@ -1,892 +1,891 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Tools for inspecting Python objects.
2 """Tools for inspecting Python objects.
3
3
4 Uses syntax highlighting for presenting the various information elements.
4 Uses syntax highlighting for presenting the various information elements.
5
5
6 Similar in spirit to the inspect module, but all calls take a name argument to
6 Similar in spirit to the inspect module, but all calls take a name argument to
7 reference the name under which an object is being read.
7 reference the name under which an object is being read.
8 """
8 """
9
9
10 #*****************************************************************************
10 #*****************************************************************************
11 # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
11 # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
12 #
12 #
13 # Distributed under the terms of the BSD License. The full license is in
13 # Distributed under the terms of the BSD License. The full license is in
14 # the file COPYING, distributed as part of this software.
14 # the file COPYING, distributed as part of this software.
15 #*****************************************************************************
15 #*****************************************************************************
16
16
17 __all__ = ['Inspector','InspectColors']
17 __all__ = ['Inspector','InspectColors']
18
18
19 # stdlib modules
19 # stdlib modules
20 import __builtin__
20 import __builtin__
21 import StringIO
21 import StringIO
22 import inspect
22 import inspect
23 import linecache
23 import linecache
24 import os
24 import os
25 import string
26 import sys
25 import sys
27 import types
26 import types
28 from collections import namedtuple
27 from collections import namedtuple
29 from itertools import izip_longest
28 from itertools import izip_longest
30
29
31 # IPython's own
30 # IPython's own
32 from IPython.core import page
31 from IPython.core import page
33 from IPython.external.Itpl import itpl
32 from IPython.external.Itpl import itpl
34 from IPython.utils import PyColorize
33 from IPython.utils import PyColorize
35 import IPython.utils.io
34 import IPython.utils.io
36 from IPython.utils.text import indent
35 from IPython.utils.text import indent
37 from IPython.utils.wildcard import list_namespace
36 from IPython.utils.wildcard import list_namespace
38 from IPython.utils.coloransi import *
37 from IPython.utils.coloransi import *
39
38
40 #****************************************************************************
39 #****************************************************************************
41 # Builtin color schemes
40 # Builtin color schemes
42
41
43 Colors = TermColors # just a shorthand
42 Colors = TermColors # just a shorthand
44
43
45 # Build a few color schemes
44 # Build a few color schemes
46 NoColor = ColorScheme(
45 NoColor = ColorScheme(
47 'NoColor',{
46 'NoColor',{
48 'header' : Colors.NoColor,
47 'header' : Colors.NoColor,
49 'normal' : Colors.NoColor # color off (usu. Colors.Normal)
48 'normal' : Colors.NoColor # color off (usu. Colors.Normal)
50 } )
49 } )
51
50
52 LinuxColors = ColorScheme(
51 LinuxColors = ColorScheme(
53 'Linux',{
52 'Linux',{
54 'header' : Colors.LightRed,
53 'header' : Colors.LightRed,
55 'normal' : Colors.Normal # color off (usu. Colors.Normal)
54 'normal' : Colors.Normal # color off (usu. Colors.Normal)
56 } )
55 } )
57
56
58 LightBGColors = ColorScheme(
57 LightBGColors = ColorScheme(
59 'LightBG',{
58 'LightBG',{
60 'header' : Colors.Red,
59 'header' : Colors.Red,
61 'normal' : Colors.Normal # color off (usu. Colors.Normal)
60 'normal' : Colors.Normal # color off (usu. Colors.Normal)
62 } )
61 } )
63
62
64 # Build table of color schemes (needed by the parser)
63 # Build table of color schemes (needed by the parser)
65 InspectColors = ColorSchemeTable([NoColor,LinuxColors,LightBGColors],
64 InspectColors = ColorSchemeTable([NoColor,LinuxColors,LightBGColors],
66 'Linux')
65 'Linux')
67
66
68 #****************************************************************************
67 #****************************************************************************
69 # Auxiliary functions and objects
68 # Auxiliary functions and objects
70
69
71 # See the messaging spec for the definition of all these fields. This list
70 # See the messaging spec for the definition of all these fields. This list
72 # effectively defines the order of display
71 # effectively defines the order of display
73 info_fields = ['type_name', 'base_class', 'string_form', 'namespace',
72 info_fields = ['type_name', 'base_class', 'string_form', 'namespace',
74 'length', 'file', 'definition', 'docstring', 'source',
73 'length', 'file', 'definition', 'docstring', 'source',
75 'init_definition', 'class_docstring', 'init_docstring',
74 'init_definition', 'class_docstring', 'init_docstring',
76 'call_def', 'call_docstring',
75 'call_def', 'call_docstring',
77 # These won't be printed but will be used to determine how to
76 # These won't be printed but will be used to determine how to
78 # format the object
77 # format the object
79 'ismagic', 'isalias', 'argspec', 'found', 'name',
78 'ismagic', 'isalias', 'argspec', 'found', 'name',
80 ]
79 ]
81
80
82
81
83 def object_info(**kw):
82 def object_info(**kw):
84 """Make an object info dict with all fields present."""
83 """Make an object info dict with all fields present."""
85 infodict = dict(izip_longest(info_fields, [None]))
84 infodict = dict(izip_longest(info_fields, [None]))
86 infodict.update(kw)
85 infodict.update(kw)
87 return infodict
86 return infodict
88
87
89
88
90 def getdoc(obj):
89 def getdoc(obj):
91 """Stable wrapper around inspect.getdoc.
90 """Stable wrapper around inspect.getdoc.
92
91
93 This can't crash because of attribute problems.
92 This can't crash because of attribute problems.
94
93
95 It also attempts to call a getdoc() method on the given object. This
94 It also attempts to call a getdoc() method on the given object. This
96 allows objects which provide their docstrings via non-standard mechanisms
95 allows objects which provide their docstrings via non-standard mechanisms
97 (like Pyro proxies) to still be inspected by ipython's ? system."""
96 (like Pyro proxies) to still be inspected by ipython's ? system."""
98
97
99 ds = None # default return value
98 ds = None # default return value
100 try:
99 try:
101 ds = inspect.getdoc(obj)
100 ds = inspect.getdoc(obj)
102 except:
101 except:
103 # Harden against an inspect failure, which can occur with
102 # Harden against an inspect failure, which can occur with
104 # SWIG-wrapped extensions.
103 # SWIG-wrapped extensions.
105 pass
104 pass
106 # Allow objects to offer customized documentation via a getdoc method:
105 # Allow objects to offer customized documentation via a getdoc method:
107 try:
106 try:
108 ds2 = obj.getdoc()
107 ds2 = obj.getdoc()
109 except:
108 except:
110 pass
109 pass
111 else:
110 else:
112 # if we get extra info, we add it to the normal docstring.
111 # if we get extra info, we add it to the normal docstring.
113 if ds is None:
112 if ds is None:
114 ds = ds2
113 ds = ds2
115 else:
114 else:
116 ds = '%s\n%s' % (ds,ds2)
115 ds = '%s\n%s' % (ds,ds2)
117 return ds
116 return ds
118
117
119
118
120 def getsource(obj,is_binary=False):
119 def getsource(obj,is_binary=False):
121 """Wrapper around inspect.getsource.
120 """Wrapper around inspect.getsource.
122
121
123 This can be modified by other projects to provide customized source
122 This can be modified by other projects to provide customized source
124 extraction.
123 extraction.
125
124
126 Inputs:
125 Inputs:
127
126
128 - obj: an object whose source code we will attempt to extract.
127 - obj: an object whose source code we will attempt to extract.
129
128
130 Optional inputs:
129 Optional inputs:
131
130
132 - is_binary: whether the object is known to come from a binary source.
131 - is_binary: whether the object is known to come from a binary source.
133 This implementation will skip returning any output for binary objects, but
132 This implementation will skip returning any output for binary objects, but
134 custom extractors may know how to meaningfully process them."""
133 custom extractors may know how to meaningfully process them."""
135
134
136 if is_binary:
135 if is_binary:
137 return None
136 return None
138 else:
137 else:
139 try:
138 try:
140 src = inspect.getsource(obj)
139 src = inspect.getsource(obj)
141 except TypeError:
140 except TypeError:
142 if hasattr(obj,'__class__'):
141 if hasattr(obj,'__class__'):
143 src = inspect.getsource(obj.__class__)
142 src = inspect.getsource(obj.__class__)
144 return src
143 return src
145
144
146 def getargspec(obj):
145 def getargspec(obj):
147 """Get the names and default values of a function's arguments.
146 """Get the names and default values of a function's arguments.
148
147
149 A tuple of four things is returned: (args, varargs, varkw, defaults).
148 A tuple of four things is returned: (args, varargs, varkw, defaults).
150 'args' is a list of the argument names (it may contain nested lists).
149 'args' is a list of the argument names (it may contain nested lists).
151 'varargs' and 'varkw' are the names of the * and ** arguments or None.
150 'varargs' and 'varkw' are the names of the * and ** arguments or None.
152 'defaults' is an n-tuple of the default values of the last n arguments.
151 'defaults' is an n-tuple of the default values of the last n arguments.
153
152
154 Modified version of inspect.getargspec from the Python Standard
153 Modified version of inspect.getargspec from the Python Standard
155 Library."""
154 Library."""
156
155
157 if inspect.isfunction(obj):
156 if inspect.isfunction(obj):
158 func_obj = obj
157 func_obj = obj
159 elif inspect.ismethod(obj):
158 elif inspect.ismethod(obj):
160 func_obj = obj.im_func
159 func_obj = obj.im_func
161 elif hasattr(obj, '__call__'):
160 elif hasattr(obj, '__call__'):
162 func_obj = obj.__call__
161 func_obj = obj.__call__
163 else:
162 else:
164 raise TypeError('arg is not a Python function')
163 raise TypeError('arg is not a Python function')
165 args, varargs, varkw = inspect.getargs(func_obj.func_code)
164 args, varargs, varkw = inspect.getargs(func_obj.func_code)
166 return args, varargs, varkw, func_obj.func_defaults
165 return args, varargs, varkw, func_obj.func_defaults
167
166
168
167
169 def format_argspec(argspec):
168 def format_argspec(argspec):
170 """Format argspect, convenience wrapper around inspect's.
169 """Format argspect, convenience wrapper around inspect's.
171
170
172 This takes a dict instead of ordered arguments and calls
171 This takes a dict instead of ordered arguments and calls
173 inspect.format_argspec with the arguments in the necessary order.
172 inspect.format_argspec with the arguments in the necessary order.
174 """
173 """
175 return inspect.formatargspec(argspec['args'], argspec['varargs'],
174 return inspect.formatargspec(argspec['args'], argspec['varargs'],
176 argspec['varkw'], argspec['defaults'])
175 argspec['varkw'], argspec['defaults'])
177
176
178
177
179 def call_tip(oinfo, format_call=True):
178 def call_tip(oinfo, format_call=True):
180 """Extract call tip data from an oinfo dict.
179 """Extract call tip data from an oinfo dict.
181
180
182 Parameters
181 Parameters
183 ----------
182 ----------
184 oinfo : dict
183 oinfo : dict
185
184
186 format_call : bool, optional
185 format_call : bool, optional
187 If True, the call line is formatted and returned as a string. If not, a
186 If True, the call line is formatted and returned as a string. If not, a
188 tuple of (name, argspec) is returned.
187 tuple of (name, argspec) is returned.
189
188
190 Returns
189 Returns
191 -------
190 -------
192 call_info : None, str or (str, dict) tuple.
191 call_info : None, str or (str, dict) tuple.
193 When format_call is True, the whole call information is formattted as a
192 When format_call is True, the whole call information is formattted as a
194 single string. Otherwise, the object's name and its argspec dict are
193 single string. Otherwise, the object's name and its argspec dict are
195 returned. If no call information is available, None is returned.
194 returned. If no call information is available, None is returned.
196
195
197 docstring : str or None
196 docstring : str or None
198 The most relevant docstring for calling purposes is returned, if
197 The most relevant docstring for calling purposes is returned, if
199 available. The priority is: call docstring for callable instances, then
198 available. The priority is: call docstring for callable instances, then
200 constructor docstring for classes, then main object's docstring otherwise
199 constructor docstring for classes, then main object's docstring otherwise
201 (regular functions).
200 (regular functions).
202 """
201 """
203 # Get call definition
202 # Get call definition
204 argspec = oinfo['argspec']
203 argspec = oinfo['argspec']
205 if argspec is None:
204 if argspec is None:
206 call_line = None
205 call_line = None
207 else:
206 else:
208 # Callable objects will have 'self' as their first argument, prune
207 # Callable objects will have 'self' as their first argument, prune
209 # it out if it's there for clarity (since users do *not* pass an
208 # it out if it's there for clarity (since users do *not* pass an
210 # extra first argument explicitly).
209 # extra first argument explicitly).
211 try:
210 try:
212 has_self = argspec['args'][0] == 'self'
211 has_self = argspec['args'][0] == 'self'
213 except (KeyError, IndexError):
212 except (KeyError, IndexError):
214 pass
213 pass
215 else:
214 else:
216 if has_self:
215 if has_self:
217 argspec['args'] = argspec['args'][1:]
216 argspec['args'] = argspec['args'][1:]
218
217
219 call_line = oinfo['name']+format_argspec(argspec)
218 call_line = oinfo['name']+format_argspec(argspec)
220
219
221 # Now get docstring.
220 # Now get docstring.
222 # The priority is: call docstring, constructor docstring, main one.
221 # The priority is: call docstring, constructor docstring, main one.
223 doc = oinfo['call_docstring']
222 doc = oinfo['call_docstring']
224 if doc is None:
223 if doc is None:
225 doc = oinfo['init_docstring']
224 doc = oinfo['init_docstring']
226 if doc is None:
225 if doc is None:
227 doc = oinfo['docstring']
226 doc = oinfo['docstring']
228
227
229 return call_line, doc
228 return call_line, doc
230
229
231 #****************************************************************************
230 #****************************************************************************
232 # Class definitions
231 # Class definitions
233
232
234 class myStringIO(StringIO.StringIO):
233 class myStringIO(StringIO.StringIO):
235 """Adds a writeln method to normal StringIO."""
234 """Adds a writeln method to normal StringIO."""
236 def writeln(self,*arg,**kw):
235 def writeln(self,*arg,**kw):
237 """Does a write() and then a write('\n')"""
236 """Does a write() and then a write('\n')"""
238 self.write(*arg,**kw)
237 self.write(*arg,**kw)
239 self.write('\n')
238 self.write('\n')
240
239
241
240
242 class Inspector:
241 class Inspector:
243 def __init__(self, color_table=InspectColors,
242 def __init__(self, color_table=InspectColors,
244 code_color_table=PyColorize.ANSICodeColors,
243 code_color_table=PyColorize.ANSICodeColors,
245 scheme='NoColor',
244 scheme='NoColor',
246 str_detail_level=0):
245 str_detail_level=0):
247 self.color_table = color_table
246 self.color_table = color_table
248 self.parser = PyColorize.Parser(code_color_table,out='str')
247 self.parser = PyColorize.Parser(code_color_table,out='str')
249 self.format = self.parser.format
248 self.format = self.parser.format
250 self.str_detail_level = str_detail_level
249 self.str_detail_level = str_detail_level
251 self.set_active_scheme(scheme)
250 self.set_active_scheme(scheme)
252
251
253 def _getdef(self,obj,oname=''):
252 def _getdef(self,obj,oname=''):
254 """Return the definition header for any callable object.
253 """Return the definition header for any callable object.
255
254
256 If any exception is generated, None is returned instead and the
255 If any exception is generated, None is returned instead and the
257 exception is suppressed."""
256 exception is suppressed."""
258
257
259 try:
258 try:
260 # We need a plain string here, NOT unicode!
259 # We need a plain string here, NOT unicode!
261 hdef = oname + inspect.formatargspec(*getargspec(obj))
260 hdef = oname + inspect.formatargspec(*getargspec(obj))
262 return hdef.encode('ascii')
261 return hdef.encode('ascii')
263 except:
262 except:
264 return None
263 return None
265
264
266 def __head(self,h):
265 def __head(self,h):
267 """Return a header string with proper colors."""
266 """Return a header string with proper colors."""
268 return '%s%s%s' % (self.color_table.active_colors.header,h,
267 return '%s%s%s' % (self.color_table.active_colors.header,h,
269 self.color_table.active_colors.normal)
268 self.color_table.active_colors.normal)
270
269
271 def set_active_scheme(self,scheme):
270 def set_active_scheme(self,scheme):
272 self.color_table.set_active_scheme(scheme)
271 self.color_table.set_active_scheme(scheme)
273 self.parser.color_table.set_active_scheme(scheme)
272 self.parser.color_table.set_active_scheme(scheme)
274
273
275 def noinfo(self,msg,oname):
274 def noinfo(self,msg,oname):
276 """Generic message when no information is found."""
275 """Generic message when no information is found."""
277 print 'No %s found' % msg,
276 print 'No %s found' % msg,
278 if oname:
277 if oname:
279 print 'for %s' % oname
278 print 'for %s' % oname
280 else:
279 else:
281 print
280 print
282
281
283 def pdef(self,obj,oname=''):
282 def pdef(self,obj,oname=''):
284 """Print the definition header for any callable object.
283 """Print the definition header for any callable object.
285
284
286 If the object is a class, print the constructor information."""
285 If the object is a class, print the constructor information."""
287
286
288 if not callable(obj):
287 if not callable(obj):
289 print 'Object is not callable.'
288 print 'Object is not callable.'
290 return
289 return
291
290
292 header = ''
291 header = ''
293
292
294 if inspect.isclass(obj):
293 if inspect.isclass(obj):
295 header = self.__head('Class constructor information:\n')
294 header = self.__head('Class constructor information:\n')
296 obj = obj.__init__
295 obj = obj.__init__
297 elif type(obj) is types.InstanceType:
296 elif type(obj) is types.InstanceType:
298 obj = obj.__call__
297 obj = obj.__call__
299
298
300 output = self._getdef(obj,oname)
299 output = self._getdef(obj,oname)
301 if output is None:
300 if output is None:
302 self.noinfo('definition header',oname)
301 self.noinfo('definition header',oname)
303 else:
302 else:
304 print >>IPython.utils.io.Term.cout, header,self.format(output),
303 print >>IPython.utils.io.Term.cout, header,self.format(output),
305
304
306 def pdoc(self,obj,oname='',formatter = None):
305 def pdoc(self,obj,oname='',formatter = None):
307 """Print the docstring for any object.
306 """Print the docstring for any object.
308
307
309 Optional:
308 Optional:
310 -formatter: a function to run the docstring through for specially
309 -formatter: a function to run the docstring through for specially
311 formatted docstrings."""
310 formatted docstrings."""
312
311
313 head = self.__head # so that itpl can find it even if private
312 head = self.__head # so that itpl can find it even if private
314 ds = getdoc(obj)
313 ds = getdoc(obj)
315 if formatter:
314 if formatter:
316 ds = formatter(ds)
315 ds = formatter(ds)
317 if inspect.isclass(obj):
316 if inspect.isclass(obj):
318 init_ds = getdoc(obj.__init__)
317 init_ds = getdoc(obj.__init__)
319 output = itpl('$head("Class Docstring:")\n'
318 output = itpl('$head("Class Docstring:")\n'
320 '$indent(ds)\n'
319 '$indent(ds)\n'
321 '$head("Constructor Docstring"):\n'
320 '$head("Constructor Docstring"):\n'
322 '$indent(init_ds)')
321 '$indent(init_ds)')
323 elif (type(obj) is types.InstanceType or isinstance(obj,object)) \
322 elif (type(obj) is types.InstanceType or isinstance(obj,object)) \
324 and hasattr(obj,'__call__'):
323 and hasattr(obj,'__call__'):
325 call_ds = getdoc(obj.__call__)
324 call_ds = getdoc(obj.__call__)
326 if call_ds:
325 if call_ds:
327 output = itpl('$head("Class Docstring:")\n$indent(ds)\n'
326 output = itpl('$head("Class Docstring:")\n$indent(ds)\n'
328 '$head("Calling Docstring:")\n$indent(call_ds)')
327 '$head("Calling Docstring:")\n$indent(call_ds)')
329 else:
328 else:
330 output = ds
329 output = ds
331 else:
330 else:
332 output = ds
331 output = ds
333 if output is None:
332 if output is None:
334 self.noinfo('documentation',oname)
333 self.noinfo('documentation',oname)
335 return
334 return
336 page.page(output)
335 page.page(output)
337
336
338 def psource(self,obj,oname=''):
337 def psource(self,obj,oname=''):
339 """Print the source code for an object."""
338 """Print the source code for an object."""
340
339
341 # Flush the source cache because inspect can return out-of-date source
340 # Flush the source cache because inspect can return out-of-date source
342 linecache.checkcache()
341 linecache.checkcache()
343 try:
342 try:
344 src = getsource(obj)
343 src = getsource(obj)
345 except:
344 except:
346 self.noinfo('source',oname)
345 self.noinfo('source',oname)
347 else:
346 else:
348 page.page(self.format(src))
347 page.page(self.format(src))
349
348
350 def pfile(self,obj,oname=''):
349 def pfile(self,obj,oname=''):
351 """Show the whole file where an object was defined."""
350 """Show the whole file where an object was defined."""
352
351
353 try:
352 try:
354 try:
353 try:
355 lineno = inspect.getsourcelines(obj)[1]
354 lineno = inspect.getsourcelines(obj)[1]
356 except TypeError:
355 except TypeError:
357 # For instances, try the class object like getsource() does
356 # For instances, try the class object like getsource() does
358 if hasattr(obj,'__class__'):
357 if hasattr(obj,'__class__'):
359 lineno = inspect.getsourcelines(obj.__class__)[1]
358 lineno = inspect.getsourcelines(obj.__class__)[1]
360 # Adjust the inspected object so getabsfile() below works
359 # Adjust the inspected object so getabsfile() below works
361 obj = obj.__class__
360 obj = obj.__class__
362 except:
361 except:
363 self.noinfo('file',oname)
362 self.noinfo('file',oname)
364 return
363 return
365
364
366 # We only reach this point if object was successfully queried
365 # We only reach this point if object was successfully queried
367
366
368 # run contents of file through pager starting at line
367 # run contents of file through pager starting at line
369 # where the object is defined
368 # where the object is defined
370 ofile = inspect.getabsfile(obj)
369 ofile = inspect.getabsfile(obj)
371
370
372 if (ofile.endswith('.so') or ofile.endswith('.dll')):
371 if (ofile.endswith('.so') or ofile.endswith('.dll')):
373 print 'File %r is binary, not printing.' % ofile
372 print 'File %r is binary, not printing.' % ofile
374 elif not os.path.isfile(ofile):
373 elif not os.path.isfile(ofile):
375 print 'File %r does not exist, not printing.' % ofile
374 print 'File %r does not exist, not printing.' % ofile
376 else:
375 else:
377 # Print only text files, not extension binaries. Note that
376 # Print only text files, not extension binaries. Note that
378 # getsourcelines returns lineno with 1-offset and page() uses
377 # getsourcelines returns lineno with 1-offset and page() uses
379 # 0-offset, so we must adjust.
378 # 0-offset, so we must adjust.
380 page.page(self.format(open(ofile).read()),lineno-1)
379 page.page(self.format(open(ofile).read()),lineno-1)
381
380
382 def pinfo(self,obj,oname='',formatter=None,info=None,detail_level=0):
381 def pinfo(self,obj,oname='',formatter=None,info=None,detail_level=0):
383 """Show detailed information about an object.
382 """Show detailed information about an object.
384
383
385 Optional arguments:
384 Optional arguments:
386
385
387 - oname: name of the variable pointing to the object.
386 - oname: name of the variable pointing to the object.
388
387
389 - formatter: special formatter for docstrings (see pdoc)
388 - formatter: special formatter for docstrings (see pdoc)
390
389
391 - info: a structure with some information fields which may have been
390 - info: a structure with some information fields which may have been
392 precomputed already.
391 precomputed already.
393
392
394 - detail_level: if set to 1, more information is given.
393 - detail_level: if set to 1, more information is given.
395 """
394 """
396
395
397 obj_type = type(obj)
396 obj_type = type(obj)
398
397
399 header = self.__head
398 header = self.__head
400 if info is None:
399 if info is None:
401 ismagic = 0
400 ismagic = 0
402 isalias = 0
401 isalias = 0
403 ospace = ''
402 ospace = ''
404 else:
403 else:
405 ismagic = info.ismagic
404 ismagic = info.ismagic
406 isalias = info.isalias
405 isalias = info.isalias
407 ospace = info.namespace
406 ospace = info.namespace
408 # Get docstring, special-casing aliases:
407 # Get docstring, special-casing aliases:
409 if isalias:
408 if isalias:
410 if not callable(obj):
409 if not callable(obj):
411 try:
410 try:
412 ds = "Alias to the system command:\n %s" % obj[1]
411 ds = "Alias to the system command:\n %s" % obj[1]
413 except:
412 except:
414 ds = "Alias: " + str(obj)
413 ds = "Alias: " + str(obj)
415 else:
414 else:
416 ds = "Alias to " + str(obj)
415 ds = "Alias to " + str(obj)
417 if obj.__doc__:
416 if obj.__doc__:
418 ds += "\nDocstring:\n" + obj.__doc__
417 ds += "\nDocstring:\n" + obj.__doc__
419 else:
418 else:
420 ds = getdoc(obj)
419 ds = getdoc(obj)
421 if ds is None:
420 if ds is None:
422 ds = '<no docstring>'
421 ds = '<no docstring>'
423 if formatter is not None:
422 if formatter is not None:
424 ds = formatter(ds)
423 ds = formatter(ds)
425
424
426 # store output in a list which gets joined with \n at the end.
425 # store output in a list which gets joined with \n at the end.
427 out = myStringIO()
426 out = myStringIO()
428
427
429 string_max = 200 # max size of strings to show (snipped if longer)
428 string_max = 200 # max size of strings to show (snipped if longer)
430 shalf = int((string_max -5)/2)
429 shalf = int((string_max -5)/2)
431
430
432 if ismagic:
431 if ismagic:
433 obj_type_name = 'Magic function'
432 obj_type_name = 'Magic function'
434 elif isalias:
433 elif isalias:
435 obj_type_name = 'System alias'
434 obj_type_name = 'System alias'
436 else:
435 else:
437 obj_type_name = obj_type.__name__
436 obj_type_name = obj_type.__name__
438 out.writeln(header('Type:\t\t')+obj_type_name)
437 out.writeln(header('Type:\t\t')+obj_type_name)
439
438
440 try:
439 try:
441 bclass = obj.__class__
440 bclass = obj.__class__
442 out.writeln(header('Base Class:\t')+str(bclass))
441 out.writeln(header('Base Class:\t')+str(bclass))
443 except: pass
442 except: pass
444
443
445 # String form, but snip if too long in ? form (full in ??)
444 # String form, but snip if too long in ? form (full in ??)
446 if detail_level >= self.str_detail_level:
445 if detail_level >= self.str_detail_level:
447 try:
446 try:
448 ostr = str(obj)
447 ostr = str(obj)
449 str_head = 'String Form:'
448 str_head = 'String Form:'
450 if not detail_level and len(ostr)>string_max:
449 if not detail_level and len(ostr)>string_max:
451 ostr = ostr[:shalf] + ' <...> ' + ostr[-shalf:]
450 ostr = ostr[:shalf] + ' <...> ' + ostr[-shalf:]
452 ostr = ("\n" + " " * len(str_head.expandtabs())).\
451 ostr = ("\n" + " " * len(str_head.expandtabs())).\
453 join(map(string.strip,ostr.split("\n")))
452 join(q.strip() for q in ostr.split("\n"))
454 if ostr.find('\n') > -1:
453 if ostr.find('\n') > -1:
455 # Print multi-line strings starting at the next line.
454 # Print multi-line strings starting at the next line.
456 str_sep = '\n'
455 str_sep = '\n'
457 else:
456 else:
458 str_sep = '\t'
457 str_sep = '\t'
459 out.writeln("%s%s%s" % (header(str_head),str_sep,ostr))
458 out.writeln("%s%s%s" % (header(str_head),str_sep,ostr))
460 except:
459 except:
461 pass
460 pass
462
461
463 if ospace:
462 if ospace:
464 out.writeln(header('Namespace:\t')+ospace)
463 out.writeln(header('Namespace:\t')+ospace)
465
464
466 # Length (for strings and lists)
465 # Length (for strings and lists)
467 try:
466 try:
468 length = str(len(obj))
467 length = str(len(obj))
469 out.writeln(header('Length:\t\t')+length)
468 out.writeln(header('Length:\t\t')+length)
470 except: pass
469 except: pass
471
470
472 # Filename where object was defined
471 # Filename where object was defined
473 binary_file = False
472 binary_file = False
474 try:
473 try:
475 try:
474 try:
476 fname = inspect.getabsfile(obj)
475 fname = inspect.getabsfile(obj)
477 except TypeError:
476 except TypeError:
478 # For an instance, the file that matters is where its class was
477 # For an instance, the file that matters is where its class was
479 # declared.
478 # declared.
480 if hasattr(obj,'__class__'):
479 if hasattr(obj,'__class__'):
481 fname = inspect.getabsfile(obj.__class__)
480 fname = inspect.getabsfile(obj.__class__)
482 if fname.endswith('<string>'):
481 if fname.endswith('<string>'):
483 fname = 'Dynamically generated function. No source code available.'
482 fname = 'Dynamically generated function. No source code available.'
484 if (fname.endswith('.so') or fname.endswith('.dll')):
483 if (fname.endswith('.so') or fname.endswith('.dll')):
485 binary_file = True
484 binary_file = True
486 out.writeln(header('File:\t\t')+fname)
485 out.writeln(header('File:\t\t')+fname)
487 except:
486 except:
488 # if anything goes wrong, we don't want to show source, so it's as
487 # if anything goes wrong, we don't want to show source, so it's as
489 # if the file was binary
488 # if the file was binary
490 binary_file = True
489 binary_file = True
491
490
492 # reconstruct the function definition and print it:
491 # reconstruct the function definition and print it:
493 defln = self._getdef(obj,oname)
492 defln = self._getdef(obj,oname)
494 if defln:
493 if defln:
495 out.write(header('Definition:\t')+self.format(defln))
494 out.write(header('Definition:\t')+self.format(defln))
496
495
497 # Docstrings only in detail 0 mode, since source contains them (we
496 # Docstrings only in detail 0 mode, since source contains them (we
498 # avoid repetitions). If source fails, we add them back, see below.
497 # avoid repetitions). If source fails, we add them back, see below.
499 if ds and detail_level == 0:
498 if ds and detail_level == 0:
500 out.writeln(header('Docstring:\n') + indent(ds))
499 out.writeln(header('Docstring:\n') + indent(ds))
501
500
502 # Original source code for any callable
501 # Original source code for any callable
503 if detail_level:
502 if detail_level:
504 # Flush the source cache because inspect can return out-of-date
503 # Flush the source cache because inspect can return out-of-date
505 # source
504 # source
506 linecache.checkcache()
505 linecache.checkcache()
507 source_success = False
506 source_success = False
508 try:
507 try:
509 try:
508 try:
510 src = getsource(obj,binary_file)
509 src = getsource(obj,binary_file)
511 except TypeError:
510 except TypeError:
512 if hasattr(obj,'__class__'):
511 if hasattr(obj,'__class__'):
513 src = getsource(obj.__class__,binary_file)
512 src = getsource(obj.__class__,binary_file)
514 if src is not None:
513 if src is not None:
515 source = self.format(src)
514 source = self.format(src)
516 out.write(header('Source:\n')+source.rstrip())
515 out.write(header('Source:\n')+source.rstrip())
517 source_success = True
516 source_success = True
518 except Exception, msg:
517 except Exception, msg:
519 pass
518 pass
520
519
521 if ds and not source_success:
520 if ds and not source_success:
522 out.writeln(header('Docstring [source file open failed]:\n')
521 out.writeln(header('Docstring [source file open failed]:\n')
523 + indent(ds))
522 + indent(ds))
524
523
525 # Constructor docstring for classes
524 # Constructor docstring for classes
526 if inspect.isclass(obj):
525 if inspect.isclass(obj):
527 # reconstruct the function definition and print it:
526 # reconstruct the function definition and print it:
528 try:
527 try:
529 obj_init = obj.__init__
528 obj_init = obj.__init__
530 except AttributeError:
529 except AttributeError:
531 init_def = init_ds = None
530 init_def = init_ds = None
532 else:
531 else:
533 init_def = self._getdef(obj_init,oname)
532 init_def = self._getdef(obj_init,oname)
534 init_ds = getdoc(obj_init)
533 init_ds = getdoc(obj_init)
535 # Skip Python's auto-generated docstrings
534 # Skip Python's auto-generated docstrings
536 if init_ds and \
535 if init_ds and \
537 init_ds.startswith('x.__init__(...) initializes'):
536 init_ds.startswith('x.__init__(...) initializes'):
538 init_ds = None
537 init_ds = None
539
538
540 if init_def or init_ds:
539 if init_def or init_ds:
541 out.writeln(header('\nConstructor information:'))
540 out.writeln(header('\nConstructor information:'))
542 if init_def:
541 if init_def:
543 out.write(header('Definition:\t')+ self.format(init_def))
542 out.write(header('Definition:\t')+ self.format(init_def))
544 if init_ds:
543 if init_ds:
545 out.writeln(header('Docstring:\n') + indent(init_ds))
544 out.writeln(header('Docstring:\n') + indent(init_ds))
546 # and class docstring for instances:
545 # and class docstring for instances:
547 elif obj_type is types.InstanceType or \
546 elif obj_type is types.InstanceType or \
548 isinstance(obj,object):
547 isinstance(obj,object):
549
548
550 # First, check whether the instance docstring is identical to the
549 # First, check whether the instance docstring is identical to the
551 # class one, and print it separately if they don't coincide. In
550 # class one, and print it separately if they don't coincide. In
552 # most cases they will, but it's nice to print all the info for
551 # most cases they will, but it's nice to print all the info for
553 # objects which use instance-customized docstrings.
552 # objects which use instance-customized docstrings.
554 if ds:
553 if ds:
555 try:
554 try:
556 cls = getattr(obj,'__class__')
555 cls = getattr(obj,'__class__')
557 except:
556 except:
558 class_ds = None
557 class_ds = None
559 else:
558 else:
560 class_ds = getdoc(cls)
559 class_ds = getdoc(cls)
561 # Skip Python's auto-generated docstrings
560 # Skip Python's auto-generated docstrings
562 if class_ds and \
561 if class_ds and \
563 (class_ds.startswith('function(code, globals[,') or \
562 (class_ds.startswith('function(code, globals[,') or \
564 class_ds.startswith('instancemethod(function, instance,') or \
563 class_ds.startswith('instancemethod(function, instance,') or \
565 class_ds.startswith('module(name[,') ):
564 class_ds.startswith('module(name[,') ):
566 class_ds = None
565 class_ds = None
567 if class_ds and ds != class_ds:
566 if class_ds and ds != class_ds:
568 out.writeln(header('Class Docstring:\n') +
567 out.writeln(header('Class Docstring:\n') +
569 indent(class_ds))
568 indent(class_ds))
570
569
571 # Next, try to show constructor docstrings
570 # Next, try to show constructor docstrings
572 try:
571 try:
573 init_ds = getdoc(obj.__init__)
572 init_ds = getdoc(obj.__init__)
574 # Skip Python's auto-generated docstrings
573 # Skip Python's auto-generated docstrings
575 if init_ds and \
574 if init_ds and \
576 init_ds.startswith('x.__init__(...) initializes'):
575 init_ds.startswith('x.__init__(...) initializes'):
577 init_ds = None
576 init_ds = None
578 except AttributeError:
577 except AttributeError:
579 init_ds = None
578 init_ds = None
580 if init_ds:
579 if init_ds:
581 out.writeln(header('Constructor Docstring:\n') +
580 out.writeln(header('Constructor Docstring:\n') +
582 indent(init_ds))
581 indent(init_ds))
583
582
584 # Call form docstring for callable instances
583 # Call form docstring for callable instances
585 if hasattr(obj,'__call__'):
584 if hasattr(obj,'__call__'):
586 #out.writeln(header('Callable:\t')+'Yes')
585 #out.writeln(header('Callable:\t')+'Yes')
587 call_def = self._getdef(obj.__call__,oname)
586 call_def = self._getdef(obj.__call__,oname)
588 #if call_def is None:
587 #if call_def is None:
589 # out.writeln(header('Call def:\t')+
588 # out.writeln(header('Call def:\t')+
590 # 'Calling definition not available.')
589 # 'Calling definition not available.')
591 if call_def is not None:
590 if call_def is not None:
592 out.writeln(header('Call def:\t')+self.format(call_def))
591 out.writeln(header('Call def:\t')+self.format(call_def))
593 call_ds = getdoc(obj.__call__)
592 call_ds = getdoc(obj.__call__)
594 # Skip Python's auto-generated docstrings
593 # Skip Python's auto-generated docstrings
595 if call_ds and call_ds.startswith('x.__call__(...) <==> x(...)'):
594 if call_ds and call_ds.startswith('x.__call__(...) <==> x(...)'):
596 call_ds = None
595 call_ds = None
597 if call_ds:
596 if call_ds:
598 out.writeln(header('Call docstring:\n') + indent(call_ds))
597 out.writeln(header('Call docstring:\n') + indent(call_ds))
599
598
600 # Finally send to printer/pager
599 # Finally send to printer/pager
601 output = out.getvalue()
600 output = out.getvalue()
602 if output:
601 if output:
603 page.page(output)
602 page.page(output)
604 # end pinfo
603 # end pinfo
605
604
606 def info(self, obj, oname='', formatter=None, info=None, detail_level=0):
605 def info(self, obj, oname='', formatter=None, info=None, detail_level=0):
607 """Compute a dict with detailed information about an object.
606 """Compute a dict with detailed information about an object.
608
607
609 Optional arguments:
608 Optional arguments:
610
609
611 - oname: name of the variable pointing to the object.
610 - oname: name of the variable pointing to the object.
612
611
613 - formatter: special formatter for docstrings (see pdoc)
612 - formatter: special formatter for docstrings (see pdoc)
614
613
615 - info: a structure with some information fields which may have been
614 - info: a structure with some information fields which may have been
616 precomputed already.
615 precomputed already.
617
616
618 - detail_level: if set to 1, more information is given.
617 - detail_level: if set to 1, more information is given.
619 """
618 """
620
619
621 obj_type = type(obj)
620 obj_type = type(obj)
622
621
623 header = self.__head
622 header = self.__head
624 if info is None:
623 if info is None:
625 ismagic = 0
624 ismagic = 0
626 isalias = 0
625 isalias = 0
627 ospace = ''
626 ospace = ''
628 else:
627 else:
629 ismagic = info.ismagic
628 ismagic = info.ismagic
630 isalias = info.isalias
629 isalias = info.isalias
631 ospace = info.namespace
630 ospace = info.namespace
632
631
633 # Get docstring, special-casing aliases:
632 # Get docstring, special-casing aliases:
634 if isalias:
633 if isalias:
635 if not callable(obj):
634 if not callable(obj):
636 try:
635 try:
637 ds = "Alias to the system command:\n %s" % obj[1]
636 ds = "Alias to the system command:\n %s" % obj[1]
638 except:
637 except:
639 ds = "Alias: " + str(obj)
638 ds = "Alias: " + str(obj)
640 else:
639 else:
641 ds = "Alias to " + str(obj)
640 ds = "Alias to " + str(obj)
642 if obj.__doc__:
641 if obj.__doc__:
643 ds += "\nDocstring:\n" + obj.__doc__
642 ds += "\nDocstring:\n" + obj.__doc__
644 else:
643 else:
645 ds = getdoc(obj)
644 ds = getdoc(obj)
646 if ds is None:
645 if ds is None:
647 ds = '<no docstring>'
646 ds = '<no docstring>'
648 if formatter is not None:
647 if formatter is not None:
649 ds = formatter(ds)
648 ds = formatter(ds)
650
649
651 # store output in a dict, we initialize it here and fill it as we go
650 # store output in a dict, we initialize it here and fill it as we go
652 out = dict(name=oname, found=True, isalias=isalias, ismagic=ismagic)
651 out = dict(name=oname, found=True, isalias=isalias, ismagic=ismagic)
653
652
654 string_max = 200 # max size of strings to show (snipped if longer)
653 string_max = 200 # max size of strings to show (snipped if longer)
655 shalf = int((string_max -5)/2)
654 shalf = int((string_max -5)/2)
656
655
657 if ismagic:
656 if ismagic:
658 obj_type_name = 'Magic function'
657 obj_type_name = 'Magic function'
659 elif isalias:
658 elif isalias:
660 obj_type_name = 'System alias'
659 obj_type_name = 'System alias'
661 else:
660 else:
662 obj_type_name = obj_type.__name__
661 obj_type_name = obj_type.__name__
663 out['type_name'] = obj_type_name
662 out['type_name'] = obj_type_name
664
663
665 try:
664 try:
666 bclass = obj.__class__
665 bclass = obj.__class__
667 out['base_class'] = str(bclass)
666 out['base_class'] = str(bclass)
668 except: pass
667 except: pass
669
668
670 # String form, but snip if too long in ? form (full in ??)
669 # String form, but snip if too long in ? form (full in ??)
671 if detail_level >= self.str_detail_level:
670 if detail_level >= self.str_detail_level:
672 try:
671 try:
673 ostr = str(obj)
672 ostr = str(obj)
674 str_head = 'string_form'
673 str_head = 'string_form'
675 if not detail_level and len(ostr)>string_max:
674 if not detail_level and len(ostr)>string_max:
676 ostr = ostr[:shalf] + ' <...> ' + ostr[-shalf:]
675 ostr = ostr[:shalf] + ' <...> ' + ostr[-shalf:]
677 ostr = ("\n" + " " * len(str_head.expandtabs())).\
676 ostr = ("\n" + " " * len(str_head.expandtabs())).\
678 join(map(string.strip,ostr.split("\n")))
677 join(q.strip() for q in ostr.split("\n"))
679 if ostr.find('\n') > -1:
678 if ostr.find('\n') > -1:
680 # Print multi-line strings starting at the next line.
679 # Print multi-line strings starting at the next line.
681 str_sep = '\n'
680 str_sep = '\n'
682 else:
681 else:
683 str_sep = '\t'
682 str_sep = '\t'
684 out[str_head] = ostr
683 out[str_head] = ostr
685 except:
684 except:
686 pass
685 pass
687
686
688 if ospace:
687 if ospace:
689 out['namespace'] = ospace
688 out['namespace'] = ospace
690
689
691 # Length (for strings and lists)
690 # Length (for strings and lists)
692 try:
691 try:
693 out['length'] = str(len(obj))
692 out['length'] = str(len(obj))
694 except: pass
693 except: pass
695
694
696 # Filename where object was defined
695 # Filename where object was defined
697 binary_file = False
696 binary_file = False
698 try:
697 try:
699 try:
698 try:
700 fname = inspect.getabsfile(obj)
699 fname = inspect.getabsfile(obj)
701 except TypeError:
700 except TypeError:
702 # For an instance, the file that matters is where its class was
701 # For an instance, the file that matters is where its class was
703 # declared.
702 # declared.
704 if hasattr(obj,'__class__'):
703 if hasattr(obj,'__class__'):
705 fname = inspect.getabsfile(obj.__class__)
704 fname = inspect.getabsfile(obj.__class__)
706 if fname.endswith('<string>'):
705 if fname.endswith('<string>'):
707 fname = 'Dynamically generated function. No source code available.'
706 fname = 'Dynamically generated function. No source code available.'
708 if (fname.endswith('.so') or fname.endswith('.dll')):
707 if (fname.endswith('.so') or fname.endswith('.dll')):
709 binary_file = True
708 binary_file = True
710 out['file'] = fname
709 out['file'] = fname
711 except:
710 except:
712 # if anything goes wrong, we don't want to show source, so it's as
711 # if anything goes wrong, we don't want to show source, so it's as
713 # if the file was binary
712 # if the file was binary
714 binary_file = True
713 binary_file = True
715
714
716 # reconstruct the function definition and print it:
715 # reconstruct the function definition and print it:
717 defln = self._getdef(obj, oname)
716 defln = self._getdef(obj, oname)
718 if defln:
717 if defln:
719 out['definition'] = self.format(defln)
718 out['definition'] = self.format(defln)
720
719
721 # Docstrings only in detail 0 mode, since source contains them (we
720 # Docstrings only in detail 0 mode, since source contains them (we
722 # avoid repetitions). If source fails, we add them back, see below.
721 # avoid repetitions). If source fails, we add them back, see below.
723 if ds and detail_level == 0:
722 if ds and detail_level == 0:
724 out['docstring'] = ds
723 out['docstring'] = ds
725
724
726 # Original source code for any callable
725 # Original source code for any callable
727 if detail_level:
726 if detail_level:
728 # Flush the source cache because inspect can return out-of-date
727 # Flush the source cache because inspect can return out-of-date
729 # source
728 # source
730 linecache.checkcache()
729 linecache.checkcache()
731 source_success = False
730 source_success = False
732 try:
731 try:
733 try:
732 try:
734 src = getsource(obj,binary_file)
733 src = getsource(obj,binary_file)
735 except TypeError:
734 except TypeError:
736 if hasattr(obj,'__class__'):
735 if hasattr(obj,'__class__'):
737 src = getsource(obj.__class__,binary_file)
736 src = getsource(obj.__class__,binary_file)
738 if src is not None:
737 if src is not None:
739 source = self.format(src)
738 source = self.format(src)
740 out['source'] = source.rstrip()
739 out['source'] = source.rstrip()
741 source_success = True
740 source_success = True
742 except Exception, msg:
741 except Exception, msg:
743 pass
742 pass
744
743
745 # Constructor docstring for classes
744 # Constructor docstring for classes
746 if inspect.isclass(obj):
745 if inspect.isclass(obj):
747 # reconstruct the function definition and print it:
746 # reconstruct the function definition and print it:
748 try:
747 try:
749 obj_init = obj.__init__
748 obj_init = obj.__init__
750 except AttributeError:
749 except AttributeError:
751 init_def = init_ds = None
750 init_def = init_ds = None
752 else:
751 else:
753 init_def = self._getdef(obj_init,oname)
752 init_def = self._getdef(obj_init,oname)
754 init_ds = getdoc(obj_init)
753 init_ds = getdoc(obj_init)
755 # Skip Python's auto-generated docstrings
754 # Skip Python's auto-generated docstrings
756 if init_ds and \
755 if init_ds and \
757 init_ds.startswith('x.__init__(...) initializes'):
756 init_ds.startswith('x.__init__(...) initializes'):
758 init_ds = None
757 init_ds = None
759
758
760 if init_def or init_ds:
759 if init_def or init_ds:
761 if init_def:
760 if init_def:
762 out['init_definition'] = self.format(init_def)
761 out['init_definition'] = self.format(init_def)
763 if init_ds:
762 if init_ds:
764 out['init_docstring'] = init_ds
763 out['init_docstring'] = init_ds
765
764
766 # and class docstring for instances:
765 # and class docstring for instances:
767 elif obj_type is types.InstanceType or \
766 elif obj_type is types.InstanceType or \
768 isinstance(obj, object):
767 isinstance(obj, object):
769 # First, check whether the instance docstring is identical to the
768 # First, check whether the instance docstring is identical to the
770 # class one, and print it separately if they don't coincide. In
769 # class one, and print it separately if they don't coincide. In
771 # most cases they will, but it's nice to print all the info for
770 # most cases they will, but it's nice to print all the info for
772 # objects which use instance-customized docstrings.
771 # objects which use instance-customized docstrings.
773 if ds:
772 if ds:
774 try:
773 try:
775 cls = getattr(obj,'__class__')
774 cls = getattr(obj,'__class__')
776 except:
775 except:
777 class_ds = None
776 class_ds = None
778 else:
777 else:
779 class_ds = getdoc(cls)
778 class_ds = getdoc(cls)
780 # Skip Python's auto-generated docstrings
779 # Skip Python's auto-generated docstrings
781 if class_ds and \
780 if class_ds and \
782 (class_ds.startswith('function(code, globals[,') or \
781 (class_ds.startswith('function(code, globals[,') or \
783 class_ds.startswith('instancemethod(function, instance,') or \
782 class_ds.startswith('instancemethod(function, instance,') or \
784 class_ds.startswith('module(name[,') ):
783 class_ds.startswith('module(name[,') ):
785 class_ds = None
784 class_ds = None
786 if class_ds and ds != class_ds:
785 if class_ds and ds != class_ds:
787 out['class_docstring'] = class_ds
786 out['class_docstring'] = class_ds
788
787
789 # Next, try to show constructor docstrings
788 # Next, try to show constructor docstrings
790 try:
789 try:
791 init_ds = getdoc(obj.__init__)
790 init_ds = getdoc(obj.__init__)
792 # Skip Python's auto-generated docstrings
791 # Skip Python's auto-generated docstrings
793 if init_ds and \
792 if init_ds and \
794 init_ds.startswith('x.__init__(...) initializes'):
793 init_ds.startswith('x.__init__(...) initializes'):
795 init_ds = None
794 init_ds = None
796 except AttributeError:
795 except AttributeError:
797 init_ds = None
796 init_ds = None
798 if init_ds:
797 if init_ds:
799 out['init_docstring'] = init_ds
798 out['init_docstring'] = init_ds
800
799
801 # Call form docstring for callable instances
800 # Call form docstring for callable instances
802 if hasattr(obj, '__call__'):
801 if hasattr(obj, '__call__'):
803 call_def = self._getdef(obj.__call__, oname)
802 call_def = self._getdef(obj.__call__, oname)
804 if call_def is not None:
803 if call_def is not None:
805 out['call_def'] = self.format(call_def)
804 out['call_def'] = self.format(call_def)
806 call_ds = getdoc(obj.__call__)
805 call_ds = getdoc(obj.__call__)
807 # Skip Python's auto-generated docstrings
806 # Skip Python's auto-generated docstrings
808 if call_ds and call_ds.startswith('x.__call__(...) <==> x(...)'):
807 if call_ds and call_ds.startswith('x.__call__(...) <==> x(...)'):
809 call_ds = None
808 call_ds = None
810 if call_ds:
809 if call_ds:
811 out['call_docstring'] = call_ds
810 out['call_docstring'] = call_ds
812
811
813 # Compute the object's argspec as a callable. The key is to decide
812 # Compute the object's argspec as a callable. The key is to decide
814 # whether to pull it from the object itself, from its __init__ or
813 # whether to pull it from the object itself, from its __init__ or
815 # from its __call__ method.
814 # from its __call__ method.
816
815
817 if inspect.isclass(obj):
816 if inspect.isclass(obj):
818 callable_obj = obj.__init__
817 callable_obj = obj.__init__
819 elif callable(obj):
818 elif callable(obj):
820 callable_obj = obj
819 callable_obj = obj
821 else:
820 else:
822 callable_obj = None
821 callable_obj = None
823
822
824 if callable_obj:
823 if callable_obj:
825 try:
824 try:
826 args, varargs, varkw, defaults = getargspec(callable_obj)
825 args, varargs, varkw, defaults = getargspec(callable_obj)
827 except (TypeError, AttributeError):
826 except (TypeError, AttributeError):
828 # For extensions/builtins we can't retrieve the argspec
827 # For extensions/builtins we can't retrieve the argspec
829 pass
828 pass
830 else:
829 else:
831 out['argspec'] = dict(args=args, varargs=varargs,
830 out['argspec'] = dict(args=args, varargs=varargs,
832 varkw=varkw, defaults=defaults)
831 varkw=varkw, defaults=defaults)
833
832
834 return object_info(**out)
833 return object_info(**out)
835
834
836
835
837 def psearch(self,pattern,ns_table,ns_search=[],
836 def psearch(self,pattern,ns_table,ns_search=[],
838 ignore_case=False,show_all=False):
837 ignore_case=False,show_all=False):
839 """Search namespaces with wildcards for objects.
838 """Search namespaces with wildcards for objects.
840
839
841 Arguments:
840 Arguments:
842
841
843 - pattern: string containing shell-like wildcards to use in namespace
842 - pattern: string containing shell-like wildcards to use in namespace
844 searches and optionally a type specification to narrow the search to
843 searches and optionally a type specification to narrow the search to
845 objects of that type.
844 objects of that type.
846
845
847 - ns_table: dict of name->namespaces for search.
846 - ns_table: dict of name->namespaces for search.
848
847
849 Optional arguments:
848 Optional arguments:
850
849
851 - ns_search: list of namespace names to include in search.
850 - ns_search: list of namespace names to include in search.
852
851
853 - ignore_case(False): make the search case-insensitive.
852 - ignore_case(False): make the search case-insensitive.
854
853
855 - show_all(False): show all names, including those starting with
854 - show_all(False): show all names, including those starting with
856 underscores.
855 underscores.
857 """
856 """
858 #print 'ps pattern:<%r>' % pattern # dbg
857 #print 'ps pattern:<%r>' % pattern # dbg
859
858
860 # defaults
859 # defaults
861 type_pattern = 'all'
860 type_pattern = 'all'
862 filter = ''
861 filter = ''
863
862
864 cmds = pattern.split()
863 cmds = pattern.split()
865 len_cmds = len(cmds)
864 len_cmds = len(cmds)
866 if len_cmds == 1:
865 if len_cmds == 1:
867 # Only filter pattern given
866 # Only filter pattern given
868 filter = cmds[0]
867 filter = cmds[0]
869 elif len_cmds == 2:
868 elif len_cmds == 2:
870 # Both filter and type specified
869 # Both filter and type specified
871 filter,type_pattern = cmds
870 filter,type_pattern = cmds
872 else:
871 else:
873 raise ValueError('invalid argument string for psearch: <%s>' %
872 raise ValueError('invalid argument string for psearch: <%s>' %
874 pattern)
873 pattern)
875
874
876 # filter search namespaces
875 # filter search namespaces
877 for name in ns_search:
876 for name in ns_search:
878 if name not in ns_table:
877 if name not in ns_table:
879 raise ValueError('invalid namespace <%s>. Valid names: %s' %
878 raise ValueError('invalid namespace <%s>. Valid names: %s' %
880 (name,ns_table.keys()))
879 (name,ns_table.keys()))
881
880
882 #print 'type_pattern:',type_pattern # dbg
881 #print 'type_pattern:',type_pattern # dbg
883 search_result = []
882 search_result = []
884 for ns_name in ns_search:
883 for ns_name in ns_search:
885 ns = ns_table[ns_name]
884 ns = ns_table[ns_name]
886 tmp_res = list(list_namespace(ns,type_pattern,filter,
885 tmp_res = list(list_namespace(ns,type_pattern,filter,
887 ignore_case=ignore_case,
886 ignore_case=ignore_case,
888 show_all=show_all))
887 show_all=show_all))
889 search_result.extend(tmp_res)
888 search_result.extend(tmp_res)
890 search_result.sort()
889 search_result.sort()
891
890
892 page.page('\n'.join(search_result))
891 page.page('\n'.join(search_result))
@@ -1,1244 +1,1243 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """
2 """
3 ultratb.py -- Spice up your tracebacks!
3 ultratb.py -- Spice up your tracebacks!
4
4
5 * ColorTB
5 * ColorTB
6 I've always found it a bit hard to visually parse tracebacks in Python. The
6 I've always found it a bit hard to visually parse tracebacks in Python. The
7 ColorTB class is a solution to that problem. It colors the different parts of a
7 ColorTB class is a solution to that problem. It colors the different parts of a
8 traceback in a manner similar to what you would expect from a syntax-highlighting
8 traceback in a manner similar to what you would expect from a syntax-highlighting
9 text editor.
9 text editor.
10
10
11 Installation instructions for ColorTB:
11 Installation instructions for ColorTB:
12 import sys,ultratb
12 import sys,ultratb
13 sys.excepthook = ultratb.ColorTB()
13 sys.excepthook = ultratb.ColorTB()
14
14
15 * VerboseTB
15 * VerboseTB
16 I've also included a port of Ka-Ping Yee's "cgitb.py" that produces all kinds
16 I've also included a port of Ka-Ping Yee's "cgitb.py" that produces all kinds
17 of useful info when a traceback occurs. Ping originally had it spit out HTML
17 of useful info when a traceback occurs. Ping originally had it spit out HTML
18 and intended it for CGI programmers, but why should they have all the fun? I
18 and intended it for CGI programmers, but why should they have all the fun? I
19 altered it to spit out colored text to the terminal. It's a bit overwhelming,
19 altered it to spit out colored text to the terminal. It's a bit overwhelming,
20 but kind of neat, and maybe useful for long-running programs that you believe
20 but kind of neat, and maybe useful for long-running programs that you believe
21 are bug-free. If a crash *does* occur in that type of program you want details.
21 are bug-free. If a crash *does* occur in that type of program you want details.
22 Give it a shot--you'll love it or you'll hate it.
22 Give it a shot--you'll love it or you'll hate it.
23
23
24 Note:
24 Note:
25
25
26 The Verbose mode prints the variables currently visible where the exception
26 The Verbose mode prints the variables currently visible where the exception
27 happened (shortening their strings if too long). This can potentially be
27 happened (shortening their strings if too long). This can potentially be
28 very slow, if you happen to have a huge data structure whose string
28 very slow, if you happen to have a huge data structure whose string
29 representation is complex to compute. Your computer may appear to freeze for
29 representation is complex to compute. Your computer may appear to freeze for
30 a while with cpu usage at 100%. If this occurs, you can cancel the traceback
30 a while with cpu usage at 100%. If this occurs, you can cancel the traceback
31 with Ctrl-C (maybe hitting it more than once).
31 with Ctrl-C (maybe hitting it more than once).
32
32
33 If you encounter this kind of situation often, you may want to use the
33 If you encounter this kind of situation often, you may want to use the
34 Verbose_novars mode instead of the regular Verbose, which avoids formatting
34 Verbose_novars mode instead of the regular Verbose, which avoids formatting
35 variables (but otherwise includes the information and context given by
35 variables (but otherwise includes the information and context given by
36 Verbose).
36 Verbose).
37
37
38
38
39 Installation instructions for ColorTB:
39 Installation instructions for ColorTB:
40 import sys,ultratb
40 import sys,ultratb
41 sys.excepthook = ultratb.VerboseTB()
41 sys.excepthook = ultratb.VerboseTB()
42
42
43 Note: Much of the code in this module was lifted verbatim from the standard
43 Note: Much of the code in this module was lifted verbatim from the standard
44 library module 'traceback.py' and Ka-Ping Yee's 'cgitb.py'.
44 library module 'traceback.py' and Ka-Ping Yee's 'cgitb.py'.
45
45
46 * Color schemes
46 * Color schemes
47 The colors are defined in the class TBTools through the use of the
47 The colors are defined in the class TBTools through the use of the
48 ColorSchemeTable class. Currently the following exist:
48 ColorSchemeTable class. Currently the following exist:
49
49
50 - NoColor: allows all of this module to be used in any terminal (the color
50 - NoColor: allows all of this module to be used in any terminal (the color
51 escapes are just dummy blank strings).
51 escapes are just dummy blank strings).
52
52
53 - Linux: is meant to look good in a terminal like the Linux console (black
53 - Linux: is meant to look good in a terminal like the Linux console (black
54 or very dark background).
54 or very dark background).
55
55
56 - LightBG: similar to Linux but swaps dark/light colors to be more readable
56 - LightBG: similar to Linux but swaps dark/light colors to be more readable
57 in light background terminals.
57 in light background terminals.
58
58
59 You can implement other color schemes easily, the syntax is fairly
59 You can implement other color schemes easily, the syntax is fairly
60 self-explanatory. Please send back new schemes you develop to the author for
60 self-explanatory. Please send back new schemes you develop to the author for
61 possible inclusion in future releases.
61 possible inclusion in future releases.
62 """
62 """
63
63
64 #*****************************************************************************
64 #*****************************************************************************
65 # Copyright (C) 2001 Nathaniel Gray <n8gray@caltech.edu>
65 # Copyright (C) 2001 Nathaniel Gray <n8gray@caltech.edu>
66 # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
66 # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
67 #
67 #
68 # Distributed under the terms of the BSD License. The full license is in
68 # Distributed under the terms of the BSD License. The full license is in
69 # the file COPYING, distributed as part of this software.
69 # the file COPYING, distributed as part of this software.
70 #*****************************************************************************
70 #*****************************************************************************
71
71
72 from __future__ import with_statement
72 from __future__ import with_statement
73
73
74 import inspect
74 import inspect
75 import keyword
75 import keyword
76 import linecache
76 import linecache
77 import os
77 import os
78 import pydoc
78 import pydoc
79 import re
79 import re
80 import string
81 import sys
80 import sys
82 import time
81 import time
83 import tokenize
82 import tokenize
84 import traceback
83 import traceback
85 import types
84 import types
86
85
87 # For purposes of monkeypatching inspect to fix a bug in it.
86 # For purposes of monkeypatching inspect to fix a bug in it.
88 from inspect import getsourcefile, getfile, getmodule,\
87 from inspect import getsourcefile, getfile, getmodule,\
89 ismodule, isclass, ismethod, isfunction, istraceback, isframe, iscode
88 ismodule, isclass, ismethod, isfunction, istraceback, isframe, iscode
90
89
91 # IPython's own modules
90 # IPython's own modules
92 # Modified pdb which doesn't damage IPython's readline handling
91 # Modified pdb which doesn't damage IPython's readline handling
93 from IPython.core import debugger, ipapi
92 from IPython.core import debugger, ipapi
94 from IPython.core.display_trap import DisplayTrap
93 from IPython.core.display_trap import DisplayTrap
95 from IPython.core.excolors import exception_colors
94 from IPython.core.excolors import exception_colors
96 from IPython.utils import PyColorize
95 from IPython.utils import PyColorize
97 from IPython.utils import io
96 from IPython.utils import io
98 from IPython.utils.data import uniq_stable
97 from IPython.utils.data import uniq_stable
99 from IPython.utils.warn import info, error
98 from IPython.utils.warn import info, error
100
99
101 # Globals
100 # Globals
102 # amount of space to put line numbers before verbose tracebacks
101 # amount of space to put line numbers before verbose tracebacks
103 INDENT_SIZE = 8
102 INDENT_SIZE = 8
104
103
105 # Default color scheme. This is used, for example, by the traceback
104 # Default color scheme. This is used, for example, by the traceback
106 # formatter. When running in an actual IPython instance, the user's rc.colors
105 # formatter. When running in an actual IPython instance, the user's rc.colors
107 # value is used, but havinga module global makes this functionality available
106 # value is used, but havinga module global makes this functionality available
108 # to users of ultratb who are NOT running inside ipython.
107 # to users of ultratb who are NOT running inside ipython.
109 DEFAULT_SCHEME = 'NoColor'
108 DEFAULT_SCHEME = 'NoColor'
110
109
111 #---------------------------------------------------------------------------
110 #---------------------------------------------------------------------------
112 # Code begins
111 # Code begins
113
112
114 # Utility functions
113 # Utility functions
115 def inspect_error():
114 def inspect_error():
116 """Print a message about internal inspect errors.
115 """Print a message about internal inspect errors.
117
116
118 These are unfortunately quite common."""
117 These are unfortunately quite common."""
119
118
120 error('Internal Python error in the inspect module.\n'
119 error('Internal Python error in the inspect module.\n'
121 'Below is the traceback from this internal error.\n')
120 'Below is the traceback from this internal error.\n')
122
121
123
122
124 def findsource(object):
123 def findsource(object):
125 """Return the entire source file and starting line number for an object.
124 """Return the entire source file and starting line number for an object.
126
125
127 The argument may be a module, class, method, function, traceback, frame,
126 The argument may be a module, class, method, function, traceback, frame,
128 or code object. The source code is returned as a list of all the lines
127 or code object. The source code is returned as a list of all the lines
129 in the file and the line number indexes a line in that list. An IOError
128 in the file and the line number indexes a line in that list. An IOError
130 is raised if the source code cannot be retrieved.
129 is raised if the source code cannot be retrieved.
131
130
132 FIXED version with which we monkeypatch the stdlib to work around a bug."""
131 FIXED version with which we monkeypatch the stdlib to work around a bug."""
133
132
134 file = getsourcefile(object) or getfile(object)
133 file = getsourcefile(object) or getfile(object)
135 # If the object is a frame, then trying to get the globals dict from its
134 # If the object is a frame, then trying to get the globals dict from its
136 # module won't work. Instead, the frame object itself has the globals
135 # module won't work. Instead, the frame object itself has the globals
137 # dictionary.
136 # dictionary.
138 globals_dict = None
137 globals_dict = None
139 if inspect.isframe(object):
138 if inspect.isframe(object):
140 # XXX: can this ever be false?
139 # XXX: can this ever be false?
141 globals_dict = object.f_globals
140 globals_dict = object.f_globals
142 else:
141 else:
143 module = getmodule(object, file)
142 module = getmodule(object, file)
144 if module:
143 if module:
145 globals_dict = module.__dict__
144 globals_dict = module.__dict__
146 lines = linecache.getlines(file, globals_dict)
145 lines = linecache.getlines(file, globals_dict)
147 if not lines:
146 if not lines:
148 raise IOError('could not get source code')
147 raise IOError('could not get source code')
149
148
150 if ismodule(object):
149 if ismodule(object):
151 return lines, 0
150 return lines, 0
152
151
153 if isclass(object):
152 if isclass(object):
154 name = object.__name__
153 name = object.__name__
155 pat = re.compile(r'^(\s*)class\s*' + name + r'\b')
154 pat = re.compile(r'^(\s*)class\s*' + name + r'\b')
156 # make some effort to find the best matching class definition:
155 # make some effort to find the best matching class definition:
157 # use the one with the least indentation, which is the one
156 # use the one with the least indentation, which is the one
158 # that's most probably not inside a function definition.
157 # that's most probably not inside a function definition.
159 candidates = []
158 candidates = []
160 for i in range(len(lines)):
159 for i in range(len(lines)):
161 match = pat.match(lines[i])
160 match = pat.match(lines[i])
162 if match:
161 if match:
163 # if it's at toplevel, it's already the best one
162 # if it's at toplevel, it's already the best one
164 if lines[i][0] == 'c':
163 if lines[i][0] == 'c':
165 return lines, i
164 return lines, i
166 # else add whitespace to candidate list
165 # else add whitespace to candidate list
167 candidates.append((match.group(1), i))
166 candidates.append((match.group(1), i))
168 if candidates:
167 if candidates:
169 # this will sort by whitespace, and by line number,
168 # this will sort by whitespace, and by line number,
170 # less whitespace first
169 # less whitespace first
171 candidates.sort()
170 candidates.sort()
172 return lines, candidates[0][1]
171 return lines, candidates[0][1]
173 else:
172 else:
174 raise IOError('could not find class definition')
173 raise IOError('could not find class definition')
175
174
176 if ismethod(object):
175 if ismethod(object):
177 object = object.im_func
176 object = object.im_func
178 if isfunction(object):
177 if isfunction(object):
179 object = object.func_code
178 object = object.func_code
180 if istraceback(object):
179 if istraceback(object):
181 object = object.tb_frame
180 object = object.tb_frame
182 if isframe(object):
181 if isframe(object):
183 object = object.f_code
182 object = object.f_code
184 if iscode(object):
183 if iscode(object):
185 if not hasattr(object, 'co_firstlineno'):
184 if not hasattr(object, 'co_firstlineno'):
186 raise IOError('could not find function definition')
185 raise IOError('could not find function definition')
187 pat = re.compile(r'^(\s*def\s)|(.*(?<!\w)lambda(:|\s))|^(\s*@)')
186 pat = re.compile(r'^(\s*def\s)|(.*(?<!\w)lambda(:|\s))|^(\s*@)')
188 pmatch = pat.match
187 pmatch = pat.match
189 # fperez - fix: sometimes, co_firstlineno can give a number larger than
188 # fperez - fix: sometimes, co_firstlineno can give a number larger than
190 # the length of lines, which causes an error. Safeguard against that.
189 # the length of lines, which causes an error. Safeguard against that.
191 lnum = min(object.co_firstlineno,len(lines))-1
190 lnum = min(object.co_firstlineno,len(lines))-1
192 while lnum > 0:
191 while lnum > 0:
193 if pmatch(lines[lnum]): break
192 if pmatch(lines[lnum]): break
194 lnum -= 1
193 lnum -= 1
195
194
196 return lines, lnum
195 return lines, lnum
197 raise IOError('could not find code object')
196 raise IOError('could not find code object')
198
197
199 # Monkeypatch inspect to apply our bugfix. This code only works with py25
198 # Monkeypatch inspect to apply our bugfix. This code only works with py25
200 if sys.version_info[:2] >= (2,5):
199 if sys.version_info[:2] >= (2,5):
201 inspect.findsource = findsource
200 inspect.findsource = findsource
202
201
203 def fix_frame_records_filenames(records):
202 def fix_frame_records_filenames(records):
204 """Try to fix the filenames in each record from inspect.getinnerframes().
203 """Try to fix the filenames in each record from inspect.getinnerframes().
205
204
206 Particularly, modules loaded from within zip files have useless filenames
205 Particularly, modules loaded from within zip files have useless filenames
207 attached to their code object, and inspect.getinnerframes() just uses it.
206 attached to their code object, and inspect.getinnerframes() just uses it.
208 """
207 """
209 fixed_records = []
208 fixed_records = []
210 for frame, filename, line_no, func_name, lines, index in records:
209 for frame, filename, line_no, func_name, lines, index in records:
211 # Look inside the frame's globals dictionary for __file__, which should
210 # Look inside the frame's globals dictionary for __file__, which should
212 # be better.
211 # be better.
213 better_fn = frame.f_globals.get('__file__', None)
212 better_fn = frame.f_globals.get('__file__', None)
214 if isinstance(better_fn, str):
213 if isinstance(better_fn, str):
215 # Check the type just in case someone did something weird with
214 # Check the type just in case someone did something weird with
216 # __file__. It might also be None if the error occurred during
215 # __file__. It might also be None if the error occurred during
217 # import.
216 # import.
218 filename = better_fn
217 filename = better_fn
219 fixed_records.append((frame, filename, line_no, func_name, lines, index))
218 fixed_records.append((frame, filename, line_no, func_name, lines, index))
220 return fixed_records
219 return fixed_records
221
220
222
221
223 def _fixed_getinnerframes(etb, context=1,tb_offset=0):
222 def _fixed_getinnerframes(etb, context=1,tb_offset=0):
224 import linecache
223 import linecache
225 LNUM_POS, LINES_POS, INDEX_POS = 2, 4, 5
224 LNUM_POS, LINES_POS, INDEX_POS = 2, 4, 5
226
225
227 records = fix_frame_records_filenames(inspect.getinnerframes(etb, context))
226 records = fix_frame_records_filenames(inspect.getinnerframes(etb, context))
228
227
229 # If the error is at the console, don't build any context, since it would
228 # If the error is at the console, don't build any context, since it would
230 # otherwise produce 5 blank lines printed out (there is no file at the
229 # otherwise produce 5 blank lines printed out (there is no file at the
231 # console)
230 # console)
232 rec_check = records[tb_offset:]
231 rec_check = records[tb_offset:]
233 try:
232 try:
234 rname = rec_check[0][1]
233 rname = rec_check[0][1]
235 if rname == '<ipython console>' or rname.endswith('<string>'):
234 if rname == '<ipython console>' or rname.endswith('<string>'):
236 return rec_check
235 return rec_check
237 except IndexError:
236 except IndexError:
238 pass
237 pass
239
238
240 aux = traceback.extract_tb(etb)
239 aux = traceback.extract_tb(etb)
241 assert len(records) == len(aux)
240 assert len(records) == len(aux)
242 for i, (file, lnum, _, _) in zip(range(len(records)), aux):
241 for i, (file, lnum, _, _) in zip(range(len(records)), aux):
243 maybeStart = lnum-1 - context//2
242 maybeStart = lnum-1 - context//2
244 start = max(maybeStart, 0)
243 start = max(maybeStart, 0)
245 end = start + context
244 end = start + context
246 lines = linecache.getlines(file)[start:end]
245 lines = linecache.getlines(file)[start:end]
247 buf = list(records[i])
246 buf = list(records[i])
248 buf[LNUM_POS] = lnum
247 buf[LNUM_POS] = lnum
249 buf[INDEX_POS] = lnum - 1 - start
248 buf[INDEX_POS] = lnum - 1 - start
250 buf[LINES_POS] = lines
249 buf[LINES_POS] = lines
251 records[i] = tuple(buf)
250 records[i] = tuple(buf)
252 return records[tb_offset:]
251 return records[tb_offset:]
253
252
254 # Helper function -- largely belongs to VerboseTB, but we need the same
253 # Helper function -- largely belongs to VerboseTB, but we need the same
255 # functionality to produce a pseudo verbose TB for SyntaxErrors, so that they
254 # functionality to produce a pseudo verbose TB for SyntaxErrors, so that they
256 # can be recognized properly by ipython.el's py-traceback-line-re
255 # can be recognized properly by ipython.el's py-traceback-line-re
257 # (SyntaxErrors have to be treated specially because they have no traceback)
256 # (SyntaxErrors have to be treated specially because they have no traceback)
258
257
259 _parser = PyColorize.Parser()
258 _parser = PyColorize.Parser()
260
259
261 def _format_traceback_lines(lnum, index, lines, Colors, lvals=None,scheme=None):
260 def _format_traceback_lines(lnum, index, lines, Colors, lvals=None,scheme=None):
262 numbers_width = INDENT_SIZE - 1
261 numbers_width = INDENT_SIZE - 1
263 res = []
262 res = []
264 i = lnum - index
263 i = lnum - index
265
264
266 # This lets us get fully syntax-highlighted tracebacks.
265 # This lets us get fully syntax-highlighted tracebacks.
267 if scheme is None:
266 if scheme is None:
268 ipinst = ipapi.get()
267 ipinst = ipapi.get()
269 if ipinst is not None:
268 if ipinst is not None:
270 scheme = ipinst.colors
269 scheme = ipinst.colors
271 else:
270 else:
272 scheme = DEFAULT_SCHEME
271 scheme = DEFAULT_SCHEME
273
272
274 _line_format = _parser.format2
273 _line_format = _parser.format2
275
274
276 for line in lines:
275 for line in lines:
277 # FIXME: we need to ensure the source is a pure string at this point,
276 # FIXME: we need to ensure the source is a pure string at this point,
278 # else the coloring code makes a royal mess. This is in need of a
277 # else the coloring code makes a royal mess. This is in need of a
279 # serious refactoring, so that all of the ultratb and PyColorize code
278 # serious refactoring, so that all of the ultratb and PyColorize code
280 # is unicode-safe. So for now this is rather an ugly hack, but
279 # is unicode-safe. So for now this is rather an ugly hack, but
281 # necessary to at least have readable tracebacks. Improvements welcome!
280 # necessary to at least have readable tracebacks. Improvements welcome!
282 if type(line)==unicode:
281 if type(line)==unicode:
283 line = line.encode('utf-8', 'replace')
282 line = line.encode('utf-8', 'replace')
284
283
285 new_line, err = _line_format(line, 'str', scheme)
284 new_line, err = _line_format(line, 'str', scheme)
286 if not err: line = new_line
285 if not err: line = new_line
287
286
288 if i == lnum:
287 if i == lnum:
289 # This is the line with the error
288 # This is the line with the error
290 pad = numbers_width - len(str(i))
289 pad = numbers_width - len(str(i))
291 if pad >= 3:
290 if pad >= 3:
292 marker = '-'*(pad-3) + '-> '
291 marker = '-'*(pad-3) + '-> '
293 elif pad == 2:
292 elif pad == 2:
294 marker = '> '
293 marker = '> '
295 elif pad == 1:
294 elif pad == 1:
296 marker = '>'
295 marker = '>'
297 else:
296 else:
298 marker = ''
297 marker = ''
299 num = marker + str(i)
298 num = marker + str(i)
300 line = '%s%s%s %s%s' %(Colors.linenoEm, num,
299 line = '%s%s%s %s%s' %(Colors.linenoEm, num,
301 Colors.line, line, Colors.Normal)
300 Colors.line, line, Colors.Normal)
302 else:
301 else:
303 num = '%*s' % (numbers_width,i)
302 num = '%*s' % (numbers_width,i)
304 line = '%s%s%s %s' %(Colors.lineno, num,
303 line = '%s%s%s %s' %(Colors.lineno, num,
305 Colors.Normal, line)
304 Colors.Normal, line)
306
305
307 res.append(line)
306 res.append(line)
308 if lvals and i == lnum:
307 if lvals and i == lnum:
309 res.append(lvals + '\n')
308 res.append(lvals + '\n')
310 i = i + 1
309 i = i + 1
311 return res
310 return res
312
311
313
312
314 #---------------------------------------------------------------------------
313 #---------------------------------------------------------------------------
315 # Module classes
314 # Module classes
316 class TBTools(object):
315 class TBTools(object):
317 """Basic tools used by all traceback printer classes."""
316 """Basic tools used by all traceback printer classes."""
318
317
319 # Number of frames to skip when reporting tracebacks
318 # Number of frames to skip when reporting tracebacks
320 tb_offset = 0
319 tb_offset = 0
321
320
322 def __init__(self, color_scheme='NoColor', call_pdb=False, ostream=None):
321 def __init__(self, color_scheme='NoColor', call_pdb=False, ostream=None):
323 # Whether to call the interactive pdb debugger after printing
322 # Whether to call the interactive pdb debugger after printing
324 # tracebacks or not
323 # tracebacks or not
325 self.call_pdb = call_pdb
324 self.call_pdb = call_pdb
326
325
327 # Output stream to write to. Note that we store the original value in
326 # Output stream to write to. Note that we store the original value in
328 # a private attribute and then make the public ostream a property, so
327 # a private attribute and then make the public ostream a property, so
329 # that we can delay accessing io.Term.cout until runtime. The way
328 # that we can delay accessing io.Term.cout until runtime. The way
330 # things are written now, the Term.cout object is dynamically managed
329 # things are written now, the Term.cout object is dynamically managed
331 # so a reference to it should NEVER be stored statically. This
330 # so a reference to it should NEVER be stored statically. This
332 # property approach confines this detail to a single location, and all
331 # property approach confines this detail to a single location, and all
333 # subclasses can simply access self.ostream for writing.
332 # subclasses can simply access self.ostream for writing.
334 self._ostream = ostream
333 self._ostream = ostream
335
334
336 # Create color table
335 # Create color table
337 self.color_scheme_table = exception_colors()
336 self.color_scheme_table = exception_colors()
338
337
339 self.set_colors(color_scheme)
338 self.set_colors(color_scheme)
340 self.old_scheme = color_scheme # save initial value for toggles
339 self.old_scheme = color_scheme # save initial value for toggles
341
340
342 if call_pdb:
341 if call_pdb:
343 self.pdb = debugger.Pdb(self.color_scheme_table.active_scheme_name)
342 self.pdb = debugger.Pdb(self.color_scheme_table.active_scheme_name)
344 else:
343 else:
345 self.pdb = None
344 self.pdb = None
346
345
347 def _get_ostream(self):
346 def _get_ostream(self):
348 """Output stream that exceptions are written to.
347 """Output stream that exceptions are written to.
349
348
350 Valid values are:
349 Valid values are:
351
350
352 - None: the default, which means that IPython will dynamically resolve
351 - None: the default, which means that IPython will dynamically resolve
353 to io.Term.cout. This ensures compatibility with most tools, including
352 to io.Term.cout. This ensures compatibility with most tools, including
354 Windows (where plain stdout doesn't recognize ANSI escapes).
353 Windows (where plain stdout doesn't recognize ANSI escapes).
355
354
356 - Any object with 'write' and 'flush' attributes.
355 - Any object with 'write' and 'flush' attributes.
357 """
356 """
358 return io.Term.cout if self._ostream is None else self._ostream
357 return io.Term.cout if self._ostream is None else self._ostream
359
358
360 def _set_ostream(self, val):
359 def _set_ostream(self, val):
361 assert val is None or (hasattr(val, 'write') and hasattr(val, 'flush'))
360 assert val is None or (hasattr(val, 'write') and hasattr(val, 'flush'))
362 self._ostream = val
361 self._ostream = val
363
362
364 ostream = property(_get_ostream, _set_ostream)
363 ostream = property(_get_ostream, _set_ostream)
365
364
366 def set_colors(self,*args,**kw):
365 def set_colors(self,*args,**kw):
367 """Shorthand access to the color table scheme selector method."""
366 """Shorthand access to the color table scheme selector method."""
368
367
369 # Set own color table
368 # Set own color table
370 self.color_scheme_table.set_active_scheme(*args,**kw)
369 self.color_scheme_table.set_active_scheme(*args,**kw)
371 # for convenience, set Colors to the active scheme
370 # for convenience, set Colors to the active scheme
372 self.Colors = self.color_scheme_table.active_colors
371 self.Colors = self.color_scheme_table.active_colors
373 # Also set colors of debugger
372 # Also set colors of debugger
374 if hasattr(self,'pdb') and self.pdb is not None:
373 if hasattr(self,'pdb') and self.pdb is not None:
375 self.pdb.set_colors(*args,**kw)
374 self.pdb.set_colors(*args,**kw)
376
375
377 def color_toggle(self):
376 def color_toggle(self):
378 """Toggle between the currently active color scheme and NoColor."""
377 """Toggle between the currently active color scheme and NoColor."""
379
378
380 if self.color_scheme_table.active_scheme_name == 'NoColor':
379 if self.color_scheme_table.active_scheme_name == 'NoColor':
381 self.color_scheme_table.set_active_scheme(self.old_scheme)
380 self.color_scheme_table.set_active_scheme(self.old_scheme)
382 self.Colors = self.color_scheme_table.active_colors
381 self.Colors = self.color_scheme_table.active_colors
383 else:
382 else:
384 self.old_scheme = self.color_scheme_table.active_scheme_name
383 self.old_scheme = self.color_scheme_table.active_scheme_name
385 self.color_scheme_table.set_active_scheme('NoColor')
384 self.color_scheme_table.set_active_scheme('NoColor')
386 self.Colors = self.color_scheme_table.active_colors
385 self.Colors = self.color_scheme_table.active_colors
387
386
388 def stb2text(self, stb):
387 def stb2text(self, stb):
389 """Convert a structured traceback (a list) to a string."""
388 """Convert a structured traceback (a list) to a string."""
390 return '\n'.join(stb)
389 return '\n'.join(stb)
391
390
392 def text(self, etype, value, tb, tb_offset=None, context=5):
391 def text(self, etype, value, tb, tb_offset=None, context=5):
393 """Return formatted traceback.
392 """Return formatted traceback.
394
393
395 Subclasses may override this if they add extra arguments.
394 Subclasses may override this if they add extra arguments.
396 """
395 """
397 tb_list = self.structured_traceback(etype, value, tb,
396 tb_list = self.structured_traceback(etype, value, tb,
398 tb_offset, context)
397 tb_offset, context)
399 return self.stb2text(tb_list)
398 return self.stb2text(tb_list)
400
399
401 def structured_traceback(self, etype, evalue, tb, tb_offset=None,
400 def structured_traceback(self, etype, evalue, tb, tb_offset=None,
402 context=5, mode=None):
401 context=5, mode=None):
403 """Return a list of traceback frames.
402 """Return a list of traceback frames.
404
403
405 Must be implemented by each class.
404 Must be implemented by each class.
406 """
405 """
407 raise NotImplementedError()
406 raise NotImplementedError()
408
407
409
408
410 #---------------------------------------------------------------------------
409 #---------------------------------------------------------------------------
411 class ListTB(TBTools):
410 class ListTB(TBTools):
412 """Print traceback information from a traceback list, with optional color.
411 """Print traceback information from a traceback list, with optional color.
413
412
414 Calling: requires 3 arguments:
413 Calling: requires 3 arguments:
415 (etype, evalue, elist)
414 (etype, evalue, elist)
416 as would be obtained by:
415 as would be obtained by:
417 etype, evalue, tb = sys.exc_info()
416 etype, evalue, tb = sys.exc_info()
418 if tb:
417 if tb:
419 elist = traceback.extract_tb(tb)
418 elist = traceback.extract_tb(tb)
420 else:
419 else:
421 elist = None
420 elist = None
422
421
423 It can thus be used by programs which need to process the traceback before
422 It can thus be used by programs which need to process the traceback before
424 printing (such as console replacements based on the code module from the
423 printing (such as console replacements based on the code module from the
425 standard library).
424 standard library).
426
425
427 Because they are meant to be called without a full traceback (only a
426 Because they are meant to be called without a full traceback (only a
428 list), instances of this class can't call the interactive pdb debugger."""
427 list), instances of this class can't call the interactive pdb debugger."""
429
428
430 def __init__(self,color_scheme = 'NoColor', call_pdb=False, ostream=None):
429 def __init__(self,color_scheme = 'NoColor', call_pdb=False, ostream=None):
431 TBTools.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
430 TBTools.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
432 ostream=ostream)
431 ostream=ostream)
433
432
434 def __call__(self, etype, value, elist):
433 def __call__(self, etype, value, elist):
435 self.ostream.flush()
434 self.ostream.flush()
436 self.ostream.write(self.text(etype, value, elist))
435 self.ostream.write(self.text(etype, value, elist))
437 self.ostream.write('\n')
436 self.ostream.write('\n')
438
437
439 def structured_traceback(self, etype, value, elist, tb_offset=None,
438 def structured_traceback(self, etype, value, elist, tb_offset=None,
440 context=5):
439 context=5):
441 """Return a color formatted string with the traceback info.
440 """Return a color formatted string with the traceback info.
442
441
443 Parameters
442 Parameters
444 ----------
443 ----------
445 etype : exception type
444 etype : exception type
446 Type of the exception raised.
445 Type of the exception raised.
447
446
448 value : object
447 value : object
449 Data stored in the exception
448 Data stored in the exception
450
449
451 elist : list
450 elist : list
452 List of frames, see class docstring for details.
451 List of frames, see class docstring for details.
453
452
454 tb_offset : int, optional
453 tb_offset : int, optional
455 Number of frames in the traceback to skip. If not given, the
454 Number of frames in the traceback to skip. If not given, the
456 instance value is used (set in constructor).
455 instance value is used (set in constructor).
457
456
458 context : int, optional
457 context : int, optional
459 Number of lines of context information to print.
458 Number of lines of context information to print.
460
459
461 Returns
460 Returns
462 -------
461 -------
463 String with formatted exception.
462 String with formatted exception.
464 """
463 """
465 tb_offset = self.tb_offset if tb_offset is None else tb_offset
464 tb_offset = self.tb_offset if tb_offset is None else tb_offset
466 Colors = self.Colors
465 Colors = self.Colors
467 out_list = []
466 out_list = []
468 if elist:
467 if elist:
469
468
470 if tb_offset and len(elist) > tb_offset:
469 if tb_offset and len(elist) > tb_offset:
471 elist = elist[tb_offset:]
470 elist = elist[tb_offset:]
472
471
473 out_list.append('Traceback %s(most recent call last)%s:' %
472 out_list.append('Traceback %s(most recent call last)%s:' %
474 (Colors.normalEm, Colors.Normal) + '\n')
473 (Colors.normalEm, Colors.Normal) + '\n')
475 out_list.extend(self._format_list(elist))
474 out_list.extend(self._format_list(elist))
476 # The exception info should be a single entry in the list.
475 # The exception info should be a single entry in the list.
477 lines = ''.join(self._format_exception_only(etype, value))
476 lines = ''.join(self._format_exception_only(etype, value))
478 out_list.append(lines)
477 out_list.append(lines)
479
478
480 # Note: this code originally read:
479 # Note: this code originally read:
481
480
482 ## for line in lines[:-1]:
481 ## for line in lines[:-1]:
483 ## out_list.append(" "+line)
482 ## out_list.append(" "+line)
484 ## out_list.append(lines[-1])
483 ## out_list.append(lines[-1])
485
484
486 # This means it was indenting everything but the last line by a little
485 # This means it was indenting everything but the last line by a little
487 # bit. I've disabled this for now, but if we see ugliness somewhre we
486 # bit. I've disabled this for now, but if we see ugliness somewhre we
488 # can restore it.
487 # can restore it.
489
488
490 return out_list
489 return out_list
491
490
492 def _format_list(self, extracted_list):
491 def _format_list(self, extracted_list):
493 """Format a list of traceback entry tuples for printing.
492 """Format a list of traceback entry tuples for printing.
494
493
495 Given a list of tuples as returned by extract_tb() or
494 Given a list of tuples as returned by extract_tb() or
496 extract_stack(), return a list of strings ready for printing.
495 extract_stack(), return a list of strings ready for printing.
497 Each string in the resulting list corresponds to the item with the
496 Each string in the resulting list corresponds to the item with the
498 same index in the argument list. Each string ends in a newline;
497 same index in the argument list. Each string ends in a newline;
499 the strings may contain internal newlines as well, for those items
498 the strings may contain internal newlines as well, for those items
500 whose source text line is not None.
499 whose source text line is not None.
501
500
502 Lifted almost verbatim from traceback.py
501 Lifted almost verbatim from traceback.py
503 """
502 """
504
503
505 Colors = self.Colors
504 Colors = self.Colors
506 list = []
505 list = []
507 for filename, lineno, name, line in extracted_list[:-1]:
506 for filename, lineno, name, line in extracted_list[:-1]:
508 item = ' File %s"%s"%s, line %s%d%s, in %s%s%s\n' % \
507 item = ' File %s"%s"%s, line %s%d%s, in %s%s%s\n' % \
509 (Colors.filename, filename, Colors.Normal,
508 (Colors.filename, filename, Colors.Normal,
510 Colors.lineno, lineno, Colors.Normal,
509 Colors.lineno, lineno, Colors.Normal,
511 Colors.name, name, Colors.Normal)
510 Colors.name, name, Colors.Normal)
512 if line:
511 if line:
513 item = item + ' %s\n' % line.strip()
512 item = item + ' %s\n' % line.strip()
514 list.append(item)
513 list.append(item)
515 # Emphasize the last entry
514 # Emphasize the last entry
516 filename, lineno, name, line = extracted_list[-1]
515 filename, lineno, name, line = extracted_list[-1]
517 item = '%s File %s"%s"%s, line %s%d%s, in %s%s%s%s\n' % \
516 item = '%s File %s"%s"%s, line %s%d%s, in %s%s%s%s\n' % \
518 (Colors.normalEm,
517 (Colors.normalEm,
519 Colors.filenameEm, filename, Colors.normalEm,
518 Colors.filenameEm, filename, Colors.normalEm,
520 Colors.linenoEm, lineno, Colors.normalEm,
519 Colors.linenoEm, lineno, Colors.normalEm,
521 Colors.nameEm, name, Colors.normalEm,
520 Colors.nameEm, name, Colors.normalEm,
522 Colors.Normal)
521 Colors.Normal)
523 if line:
522 if line:
524 item = item + '%s %s%s\n' % (Colors.line, line.strip(),
523 item = item + '%s %s%s\n' % (Colors.line, line.strip(),
525 Colors.Normal)
524 Colors.Normal)
526 list.append(item)
525 list.append(item)
527 #from pprint import pformat; print 'LISTTB', pformat(list) # dbg
526 #from pprint import pformat; print 'LISTTB', pformat(list) # dbg
528 return list
527 return list
529
528
530 def _format_exception_only(self, etype, value):
529 def _format_exception_only(self, etype, value):
531 """Format the exception part of a traceback.
530 """Format the exception part of a traceback.
532
531
533 The arguments are the exception type and value such as given by
532 The arguments are the exception type and value such as given by
534 sys.exc_info()[:2]. The return value is a list of strings, each ending
533 sys.exc_info()[:2]. The return value is a list of strings, each ending
535 in a newline. Normally, the list contains a single string; however,
534 in a newline. Normally, the list contains a single string; however,
536 for SyntaxError exceptions, it contains several lines that (when
535 for SyntaxError exceptions, it contains several lines that (when
537 printed) display detailed information about where the syntax error
536 printed) display detailed information about where the syntax error
538 occurred. The message indicating which exception occurred is the
537 occurred. The message indicating which exception occurred is the
539 always last string in the list.
538 always last string in the list.
540
539
541 Also lifted nearly verbatim from traceback.py
540 Also lifted nearly verbatim from traceback.py
542 """
541 """
543
542
544 have_filedata = False
543 have_filedata = False
545 Colors = self.Colors
544 Colors = self.Colors
546 list = []
545 list = []
547 try:
546 try:
548 stype = Colors.excName + etype.__name__ + Colors.Normal
547 stype = Colors.excName + etype.__name__ + Colors.Normal
549 except AttributeError:
548 except AttributeError:
550 stype = etype # String exceptions don't get special coloring
549 stype = etype # String exceptions don't get special coloring
551 if value is None:
550 if value is None:
552 list.append( str(stype) + '\n')
551 list.append( str(stype) + '\n')
553 else:
552 else:
554 if etype is SyntaxError:
553 if etype is SyntaxError:
555 try:
554 try:
556 msg, (filename, lineno, offset, line) = value
555 msg, (filename, lineno, offset, line) = value
557 except:
556 except:
558 have_filedata = False
557 have_filedata = False
559 else:
558 else:
560 have_filedata = True
559 have_filedata = True
561 #print 'filename is',filename # dbg
560 #print 'filename is',filename # dbg
562 if not filename: filename = "<string>"
561 if not filename: filename = "<string>"
563 list.append('%s File %s"%s"%s, line %s%d%s\n' % \
562 list.append('%s File %s"%s"%s, line %s%d%s\n' % \
564 (Colors.normalEm,
563 (Colors.normalEm,
565 Colors.filenameEm, filename, Colors.normalEm,
564 Colors.filenameEm, filename, Colors.normalEm,
566 Colors.linenoEm, lineno, Colors.Normal ))
565 Colors.linenoEm, lineno, Colors.Normal ))
567 if line is not None:
566 if line is not None:
568 i = 0
567 i = 0
569 while i < len(line) and line[i].isspace():
568 while i < len(line) and line[i].isspace():
570 i = i+1
569 i = i+1
571 list.append('%s %s%s\n' % (Colors.line,
570 list.append('%s %s%s\n' % (Colors.line,
572 line.strip(),
571 line.strip(),
573 Colors.Normal))
572 Colors.Normal))
574 if offset is not None:
573 if offset is not None:
575 s = ' '
574 s = ' '
576 for c in line[i:offset-1]:
575 for c in line[i:offset-1]:
577 if c.isspace():
576 if c.isspace():
578 s = s + c
577 s = s + c
579 else:
578 else:
580 s = s + ' '
579 s = s + ' '
581 list.append('%s%s^%s\n' % (Colors.caret, s,
580 list.append('%s%s^%s\n' % (Colors.caret, s,
582 Colors.Normal) )
581 Colors.Normal) )
583 value = msg
582 value = msg
584 s = self._some_str(value)
583 s = self._some_str(value)
585 if s:
584 if s:
586 list.append('%s%s:%s %s\n' % (str(stype), Colors.excName,
585 list.append('%s%s:%s %s\n' % (str(stype), Colors.excName,
587 Colors.Normal, s))
586 Colors.Normal, s))
588 else:
587 else:
589 list.append('%s\n' % str(stype))
588 list.append('%s\n' % str(stype))
590
589
591 # sync with user hooks
590 # sync with user hooks
592 if have_filedata:
591 if have_filedata:
593 ipinst = ipapi.get()
592 ipinst = ipapi.get()
594 if ipinst is not None:
593 if ipinst is not None:
595 ipinst.hooks.synchronize_with_editor(filename, lineno, 0)
594 ipinst.hooks.synchronize_with_editor(filename, lineno, 0)
596
595
597 return list
596 return list
598
597
599 def get_exception_only(self, etype, value):
598 def get_exception_only(self, etype, value):
600 """Only print the exception type and message, without a traceback.
599 """Only print the exception type and message, without a traceback.
601
600
602 Parameters
601 Parameters
603 ----------
602 ----------
604 etype : exception type
603 etype : exception type
605 value : exception value
604 value : exception value
606 """
605 """
607 return ListTB.structured_traceback(self, etype, value, [])
606 return ListTB.structured_traceback(self, etype, value, [])
608
607
609
608
610 def show_exception_only(self, etype, evalue):
609 def show_exception_only(self, etype, evalue):
611 """Only print the exception type and message, without a traceback.
610 """Only print the exception type and message, without a traceback.
612
611
613 Parameters
612 Parameters
614 ----------
613 ----------
615 etype : exception type
614 etype : exception type
616 value : exception value
615 value : exception value
617 """
616 """
618 # This method needs to use __call__ from *this* class, not the one from
617 # This method needs to use __call__ from *this* class, not the one from
619 # a subclass whose signature or behavior may be different
618 # a subclass whose signature or behavior may be different
620 ostream = self.ostream
619 ostream = self.ostream
621 ostream.flush()
620 ostream.flush()
622 ostream.write('\n'.join(self.get_exception_only(etype, evalue)))
621 ostream.write('\n'.join(self.get_exception_only(etype, evalue)))
623 ostream.flush()
622 ostream.flush()
624
623
625 def _some_str(self, value):
624 def _some_str(self, value):
626 # Lifted from traceback.py
625 # Lifted from traceback.py
627 try:
626 try:
628 return str(value)
627 return str(value)
629 except:
628 except:
630 return '<unprintable %s object>' % type(value).__name__
629 return '<unprintable %s object>' % type(value).__name__
631
630
632 #----------------------------------------------------------------------------
631 #----------------------------------------------------------------------------
633 class VerboseTB(TBTools):
632 class VerboseTB(TBTools):
634 """A port of Ka-Ping Yee's cgitb.py module that outputs color text instead
633 """A port of Ka-Ping Yee's cgitb.py module that outputs color text instead
635 of HTML. Requires inspect and pydoc. Crazy, man.
634 of HTML. Requires inspect and pydoc. Crazy, man.
636
635
637 Modified version which optionally strips the topmost entries from the
636 Modified version which optionally strips the topmost entries from the
638 traceback, to be used with alternate interpreters (because their own code
637 traceback, to be used with alternate interpreters (because their own code
639 would appear in the traceback)."""
638 would appear in the traceback)."""
640
639
641 def __init__(self,color_scheme = 'Linux', call_pdb=False, ostream=None,
640 def __init__(self,color_scheme = 'Linux', call_pdb=False, ostream=None,
642 tb_offset=0, long_header=False, include_vars=True,
641 tb_offset=0, long_header=False, include_vars=True,
643 check_cache=None):
642 check_cache=None):
644 """Specify traceback offset, headers and color scheme.
643 """Specify traceback offset, headers and color scheme.
645
644
646 Define how many frames to drop from the tracebacks. Calling it with
645 Define how many frames to drop from the tracebacks. Calling it with
647 tb_offset=1 allows use of this handler in interpreters which will have
646 tb_offset=1 allows use of this handler in interpreters which will have
648 their own code at the top of the traceback (VerboseTB will first
647 their own code at the top of the traceback (VerboseTB will first
649 remove that frame before printing the traceback info)."""
648 remove that frame before printing the traceback info)."""
650 TBTools.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
649 TBTools.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
651 ostream=ostream)
650 ostream=ostream)
652 self.tb_offset = tb_offset
651 self.tb_offset = tb_offset
653 self.long_header = long_header
652 self.long_header = long_header
654 self.include_vars = include_vars
653 self.include_vars = include_vars
655 # By default we use linecache.checkcache, but the user can provide a
654 # By default we use linecache.checkcache, but the user can provide a
656 # different check_cache implementation. This is used by the IPython
655 # different check_cache implementation. This is used by the IPython
657 # kernel to provide tracebacks for interactive code that is cached,
656 # kernel to provide tracebacks for interactive code that is cached,
658 # by a compiler instance that flushes the linecache but preserves its
657 # by a compiler instance that flushes the linecache but preserves its
659 # own code cache.
658 # own code cache.
660 if check_cache is None:
659 if check_cache is None:
661 check_cache = linecache.checkcache
660 check_cache = linecache.checkcache
662 self.check_cache = check_cache
661 self.check_cache = check_cache
663
662
664 def structured_traceback(self, etype, evalue, etb, tb_offset=None,
663 def structured_traceback(self, etype, evalue, etb, tb_offset=None,
665 context=5):
664 context=5):
666 """Return a nice text document describing the traceback."""
665 """Return a nice text document describing the traceback."""
667
666
668 tb_offset = self.tb_offset if tb_offset is None else tb_offset
667 tb_offset = self.tb_offset if tb_offset is None else tb_offset
669
668
670 # some locals
669 # some locals
671 try:
670 try:
672 etype = etype.__name__
671 etype = etype.__name__
673 except AttributeError:
672 except AttributeError:
674 pass
673 pass
675 Colors = self.Colors # just a shorthand + quicker name lookup
674 Colors = self.Colors # just a shorthand + quicker name lookup
676 ColorsNormal = Colors.Normal # used a lot
675 ColorsNormal = Colors.Normal # used a lot
677 col_scheme = self.color_scheme_table.active_scheme_name
676 col_scheme = self.color_scheme_table.active_scheme_name
678 indent = ' '*INDENT_SIZE
677 indent = ' '*INDENT_SIZE
679 em_normal = '%s\n%s%s' % (Colors.valEm, indent,ColorsNormal)
678 em_normal = '%s\n%s%s' % (Colors.valEm, indent,ColorsNormal)
680 undefined = '%sundefined%s' % (Colors.em, ColorsNormal)
679 undefined = '%sundefined%s' % (Colors.em, ColorsNormal)
681 exc = '%s%s%s' % (Colors.excName,etype,ColorsNormal)
680 exc = '%s%s%s' % (Colors.excName,etype,ColorsNormal)
682
681
683 # some internal-use functions
682 # some internal-use functions
684 def text_repr(value):
683 def text_repr(value):
685 """Hopefully pretty robust repr equivalent."""
684 """Hopefully pretty robust repr equivalent."""
686 # this is pretty horrible but should always return *something*
685 # this is pretty horrible but should always return *something*
687 try:
686 try:
688 return pydoc.text.repr(value)
687 return pydoc.text.repr(value)
689 except KeyboardInterrupt:
688 except KeyboardInterrupt:
690 raise
689 raise
691 except:
690 except:
692 try:
691 try:
693 return repr(value)
692 return repr(value)
694 except KeyboardInterrupt:
693 except KeyboardInterrupt:
695 raise
694 raise
696 except:
695 except:
697 try:
696 try:
698 # all still in an except block so we catch
697 # all still in an except block so we catch
699 # getattr raising
698 # getattr raising
700 name = getattr(value, '__name__', None)
699 name = getattr(value, '__name__', None)
701 if name:
700 if name:
702 # ick, recursion
701 # ick, recursion
703 return text_repr(name)
702 return text_repr(name)
704 klass = getattr(value, '__class__', None)
703 klass = getattr(value, '__class__', None)
705 if klass:
704 if klass:
706 return '%s instance' % text_repr(klass)
705 return '%s instance' % text_repr(klass)
707 except KeyboardInterrupt:
706 except KeyboardInterrupt:
708 raise
707 raise
709 except:
708 except:
710 return 'UNRECOVERABLE REPR FAILURE'
709 return 'UNRECOVERABLE REPR FAILURE'
711 def eqrepr(value, repr=text_repr): return '=%s' % repr(value)
710 def eqrepr(value, repr=text_repr): return '=%s' % repr(value)
712 def nullrepr(value, repr=text_repr): return ''
711 def nullrepr(value, repr=text_repr): return ''
713
712
714 # meat of the code begins
713 # meat of the code begins
715 try:
714 try:
716 etype = etype.__name__
715 etype = etype.__name__
717 except AttributeError:
716 except AttributeError:
718 pass
717 pass
719
718
720 if self.long_header:
719 if self.long_header:
721 # Header with the exception type, python version, and date
720 # Header with the exception type, python version, and date
722 pyver = 'Python ' + string.split(sys.version)[0] + ': ' + sys.executable
721 pyver = 'Python ' + sys.version.split()[0] + ': ' + sys.executable
723 date = time.ctime(time.time())
722 date = time.ctime(time.time())
724
723
725 head = '%s%s%s\n%s%s%s\n%s' % (Colors.topline, '-'*75, ColorsNormal,
724 head = '%s%s%s\n%s%s%s\n%s' % (Colors.topline, '-'*75, ColorsNormal,
726 exc, ' '*(75-len(str(etype))-len(pyver)),
725 exc, ' '*(75-len(str(etype))-len(pyver)),
727 pyver, date.rjust(75) )
726 pyver, date.rjust(75) )
728 head += "\nA problem occured executing Python code. Here is the sequence of function"\
727 head += "\nA problem occured executing Python code. Here is the sequence of function"\
729 "\ncalls leading up to the error, with the most recent (innermost) call last."
728 "\ncalls leading up to the error, with the most recent (innermost) call last."
730 else:
729 else:
731 # Simplified header
730 # Simplified header
732 head = '%s%s%s\n%s%s' % (Colors.topline, '-'*75, ColorsNormal,exc,
731 head = '%s%s%s\n%s%s' % (Colors.topline, '-'*75, ColorsNormal,exc,
733 'Traceback (most recent call last)'.\
732 'Traceback (most recent call last)'.\
734 rjust(75 - len(str(etype)) ) )
733 rjust(75 - len(str(etype)) ) )
735 frames = []
734 frames = []
736 # Flush cache before calling inspect. This helps alleviate some of the
735 # Flush cache before calling inspect. This helps alleviate some of the
737 # problems with python 2.3's inspect.py.
736 # problems with python 2.3's inspect.py.
738 ##self.check_cache()
737 ##self.check_cache()
739 # Drop topmost frames if requested
738 # Drop topmost frames if requested
740 try:
739 try:
741 # Try the default getinnerframes and Alex's: Alex's fixes some
740 # Try the default getinnerframes and Alex's: Alex's fixes some
742 # problems, but it generates empty tracebacks for console errors
741 # problems, but it generates empty tracebacks for console errors
743 # (5 blanks lines) where none should be returned.
742 # (5 blanks lines) where none should be returned.
744 #records = inspect.getinnerframes(etb, context)[tb_offset:]
743 #records = inspect.getinnerframes(etb, context)[tb_offset:]
745 #print 'python records:', records # dbg
744 #print 'python records:', records # dbg
746 records = _fixed_getinnerframes(etb, context, tb_offset)
745 records = _fixed_getinnerframes(etb, context, tb_offset)
747 #print 'alex records:', records # dbg
746 #print 'alex records:', records # dbg
748 except:
747 except:
749
748
750 # FIXME: I've been getting many crash reports from python 2.3
749 # FIXME: I've been getting many crash reports from python 2.3
751 # users, traceable to inspect.py. If I can find a small test-case
750 # users, traceable to inspect.py. If I can find a small test-case
752 # to reproduce this, I should either write a better workaround or
751 # to reproduce this, I should either write a better workaround or
753 # file a bug report against inspect (if that's the real problem).
752 # file a bug report against inspect (if that's the real problem).
754 # So far, I haven't been able to find an isolated example to
753 # So far, I haven't been able to find an isolated example to
755 # reproduce the problem.
754 # reproduce the problem.
756 inspect_error()
755 inspect_error()
757 traceback.print_exc(file=self.ostream)
756 traceback.print_exc(file=self.ostream)
758 info('\nUnfortunately, your original traceback can not be constructed.\n')
757 info('\nUnfortunately, your original traceback can not be constructed.\n')
759 return ''
758 return ''
760
759
761 # build some color string templates outside these nested loops
760 # build some color string templates outside these nested loops
762 tpl_link = '%s%%s%s' % (Colors.filenameEm,ColorsNormal)
761 tpl_link = '%s%%s%s' % (Colors.filenameEm,ColorsNormal)
763 tpl_call = 'in %s%%s%s%%s%s' % (Colors.vName, Colors.valEm,
762 tpl_call = 'in %s%%s%s%%s%s' % (Colors.vName, Colors.valEm,
764 ColorsNormal)
763 ColorsNormal)
765 tpl_call_fail = 'in %s%%s%s(***failed resolving arguments***)%s' % \
764 tpl_call_fail = 'in %s%%s%s(***failed resolving arguments***)%s' % \
766 (Colors.vName, Colors.valEm, ColorsNormal)
765 (Colors.vName, Colors.valEm, ColorsNormal)
767 tpl_local_var = '%s%%s%s' % (Colors.vName, ColorsNormal)
766 tpl_local_var = '%s%%s%s' % (Colors.vName, ColorsNormal)
768 tpl_global_var = '%sglobal%s %s%%s%s' % (Colors.em, ColorsNormal,
767 tpl_global_var = '%sglobal%s %s%%s%s' % (Colors.em, ColorsNormal,
769 Colors.vName, ColorsNormal)
768 Colors.vName, ColorsNormal)
770 tpl_name_val = '%%s %s= %%s%s' % (Colors.valEm, ColorsNormal)
769 tpl_name_val = '%%s %s= %%s%s' % (Colors.valEm, ColorsNormal)
771 tpl_line = '%s%%s%s %%s' % (Colors.lineno, ColorsNormal)
770 tpl_line = '%s%%s%s %%s' % (Colors.lineno, ColorsNormal)
772 tpl_line_em = '%s%%s%s %%s%s' % (Colors.linenoEm,Colors.line,
771 tpl_line_em = '%s%%s%s %%s%s' % (Colors.linenoEm,Colors.line,
773 ColorsNormal)
772 ColorsNormal)
774
773
775 # now, loop over all records printing context and info
774 # now, loop over all records printing context and info
776 abspath = os.path.abspath
775 abspath = os.path.abspath
777 for frame, file, lnum, func, lines, index in records:
776 for frame, file, lnum, func, lines, index in records:
778 #print '*** record:',file,lnum,func,lines,index # dbg
777 #print '*** record:',file,lnum,func,lines,index # dbg
779 try:
778 try:
780 file = file and abspath(file) or '?'
779 file = file and abspath(file) or '?'
781 except OSError:
780 except OSError:
782 # if file is '<console>' or something not in the filesystem,
781 # if file is '<console>' or something not in the filesystem,
783 # the abspath call will throw an OSError. Just ignore it and
782 # the abspath call will throw an OSError. Just ignore it and
784 # keep the original file string.
783 # keep the original file string.
785 pass
784 pass
786 link = tpl_link % file
785 link = tpl_link % file
787 try:
786 try:
788 args, varargs, varkw, locals = inspect.getargvalues(frame)
787 args, varargs, varkw, locals = inspect.getargvalues(frame)
789 except:
788 except:
790 # This can happen due to a bug in python2.3. We should be
789 # This can happen due to a bug in python2.3. We should be
791 # able to remove this try/except when 2.4 becomes a
790 # able to remove this try/except when 2.4 becomes a
792 # requirement. Bug details at http://python.org/sf/1005466
791 # requirement. Bug details at http://python.org/sf/1005466
793 inspect_error()
792 inspect_error()
794 traceback.print_exc(file=self.ostream)
793 traceback.print_exc(file=self.ostream)
795 info("\nIPython's exception reporting continues...\n")
794 info("\nIPython's exception reporting continues...\n")
796
795
797 if func == '?':
796 if func == '?':
798 call = ''
797 call = ''
799 else:
798 else:
800 # Decide whether to include variable details or not
799 # Decide whether to include variable details or not
801 var_repr = self.include_vars and eqrepr or nullrepr
800 var_repr = self.include_vars and eqrepr or nullrepr
802 try:
801 try:
803 call = tpl_call % (func,inspect.formatargvalues(args,
802 call = tpl_call % (func,inspect.formatargvalues(args,
804 varargs, varkw,
803 varargs, varkw,
805 locals,formatvalue=var_repr))
804 locals,formatvalue=var_repr))
806 except KeyError:
805 except KeyError:
807 # This happens in situations like errors inside generator
806 # This happens in situations like errors inside generator
808 # expressions, where local variables are listed in the
807 # expressions, where local variables are listed in the
809 # line, but can't be extracted from the frame. I'm not
808 # line, but can't be extracted from the frame. I'm not
810 # 100% sure this isn't actually a bug in inspect itself,
809 # 100% sure this isn't actually a bug in inspect itself,
811 # but since there's no info for us to compute with, the
810 # but since there's no info for us to compute with, the
812 # best we can do is report the failure and move on. Here
811 # best we can do is report the failure and move on. Here
813 # we must *not* call any traceback construction again,
812 # we must *not* call any traceback construction again,
814 # because that would mess up use of %debug later on. So we
813 # because that would mess up use of %debug later on. So we
815 # simply report the failure and move on. The only
814 # simply report the failure and move on. The only
816 # limitation will be that this frame won't have locals
815 # limitation will be that this frame won't have locals
817 # listed in the call signature. Quite subtle problem...
816 # listed in the call signature. Quite subtle problem...
818 # I can't think of a good way to validate this in a unit
817 # I can't think of a good way to validate this in a unit
819 # test, but running a script consisting of:
818 # test, but running a script consisting of:
820 # dict( (k,v.strip()) for (k,v) in range(10) )
819 # dict( (k,v.strip()) for (k,v) in range(10) )
821 # will illustrate the error, if this exception catch is
820 # will illustrate the error, if this exception catch is
822 # disabled.
821 # disabled.
823 call = tpl_call_fail % func
822 call = tpl_call_fail % func
824
823
825 # Initialize a list of names on the current line, which the
824 # Initialize a list of names on the current line, which the
826 # tokenizer below will populate.
825 # tokenizer below will populate.
827 names = []
826 names = []
828
827
829 def tokeneater(token_type, token, start, end, line):
828 def tokeneater(token_type, token, start, end, line):
830 """Stateful tokeneater which builds dotted names.
829 """Stateful tokeneater which builds dotted names.
831
830
832 The list of names it appends to (from the enclosing scope) can
831 The list of names it appends to (from the enclosing scope) can
833 contain repeated composite names. This is unavoidable, since
832 contain repeated composite names. This is unavoidable, since
834 there is no way to disambguate partial dotted structures until
833 there is no way to disambguate partial dotted structures until
835 the full list is known. The caller is responsible for pruning
834 the full list is known. The caller is responsible for pruning
836 the final list of duplicates before using it."""
835 the final list of duplicates before using it."""
837
836
838 # build composite names
837 # build composite names
839 if token == '.':
838 if token == '.':
840 try:
839 try:
841 names[-1] += '.'
840 names[-1] += '.'
842 # store state so the next token is added for x.y.z names
841 # store state so the next token is added for x.y.z names
843 tokeneater.name_cont = True
842 tokeneater.name_cont = True
844 return
843 return
845 except IndexError:
844 except IndexError:
846 pass
845 pass
847 if token_type == tokenize.NAME and token not in keyword.kwlist:
846 if token_type == tokenize.NAME and token not in keyword.kwlist:
848 if tokeneater.name_cont:
847 if tokeneater.name_cont:
849 # Dotted names
848 # Dotted names
850 names[-1] += token
849 names[-1] += token
851 tokeneater.name_cont = False
850 tokeneater.name_cont = False
852 else:
851 else:
853 # Regular new names. We append everything, the caller
852 # Regular new names. We append everything, the caller
854 # will be responsible for pruning the list later. It's
853 # will be responsible for pruning the list later. It's
855 # very tricky to try to prune as we go, b/c composite
854 # very tricky to try to prune as we go, b/c composite
856 # names can fool us. The pruning at the end is easy
855 # names can fool us. The pruning at the end is easy
857 # to do (or the caller can print a list with repeated
856 # to do (or the caller can print a list with repeated
858 # names if so desired.
857 # names if so desired.
859 names.append(token)
858 names.append(token)
860 elif token_type == tokenize.NEWLINE:
859 elif token_type == tokenize.NEWLINE:
861 raise IndexError
860 raise IndexError
862 # we need to store a bit of state in the tokenizer to build
861 # we need to store a bit of state in the tokenizer to build
863 # dotted names
862 # dotted names
864 tokeneater.name_cont = False
863 tokeneater.name_cont = False
865
864
866 def linereader(file=file, lnum=[lnum], getline=linecache.getline):
865 def linereader(file=file, lnum=[lnum], getline=linecache.getline):
867 line = getline(file, lnum[0])
866 line = getline(file, lnum[0])
868 lnum[0] += 1
867 lnum[0] += 1
869 return line
868 return line
870
869
871 # Build the list of names on this line of code where the exception
870 # Build the list of names on this line of code where the exception
872 # occurred.
871 # occurred.
873 try:
872 try:
874 # This builds the names list in-place by capturing it from the
873 # This builds the names list in-place by capturing it from the
875 # enclosing scope.
874 # enclosing scope.
876 tokenize.tokenize(linereader, tokeneater)
875 tokenize.tokenize(linereader, tokeneater)
877 except IndexError:
876 except IndexError:
878 # signals exit of tokenizer
877 # signals exit of tokenizer
879 pass
878 pass
880 except tokenize.TokenError,msg:
879 except tokenize.TokenError,msg:
881 _m = ("An unexpected error occurred while tokenizing input\n"
880 _m = ("An unexpected error occurred while tokenizing input\n"
882 "The following traceback may be corrupted or invalid\n"
881 "The following traceback may be corrupted or invalid\n"
883 "The error message is: %s\n" % msg)
882 "The error message is: %s\n" % msg)
884 error(_m)
883 error(_m)
885
884
886 # prune names list of duplicates, but keep the right order
885 # prune names list of duplicates, but keep the right order
887 unique_names = uniq_stable(names)
886 unique_names = uniq_stable(names)
888
887
889 # Start loop over vars
888 # Start loop over vars
890 lvals = []
889 lvals = []
891 if self.include_vars:
890 if self.include_vars:
892 for name_full in unique_names:
891 for name_full in unique_names:
893 name_base = name_full.split('.',1)[0]
892 name_base = name_full.split('.',1)[0]
894 if name_base in frame.f_code.co_varnames:
893 if name_base in frame.f_code.co_varnames:
895 if locals.has_key(name_base):
894 if locals.has_key(name_base):
896 try:
895 try:
897 value = repr(eval(name_full,locals))
896 value = repr(eval(name_full,locals))
898 except:
897 except:
899 value = undefined
898 value = undefined
900 else:
899 else:
901 value = undefined
900 value = undefined
902 name = tpl_local_var % name_full
901 name = tpl_local_var % name_full
903 else:
902 else:
904 if frame.f_globals.has_key(name_base):
903 if frame.f_globals.has_key(name_base):
905 try:
904 try:
906 value = repr(eval(name_full,frame.f_globals))
905 value = repr(eval(name_full,frame.f_globals))
907 except:
906 except:
908 value = undefined
907 value = undefined
909 else:
908 else:
910 value = undefined
909 value = undefined
911 name = tpl_global_var % name_full
910 name = tpl_global_var % name_full
912 lvals.append(tpl_name_val % (name,value))
911 lvals.append(tpl_name_val % (name,value))
913 if lvals:
912 if lvals:
914 lvals = '%s%s' % (indent,em_normal.join(lvals))
913 lvals = '%s%s' % (indent,em_normal.join(lvals))
915 else:
914 else:
916 lvals = ''
915 lvals = ''
917
916
918 level = '%s %s\n' % (link,call)
917 level = '%s %s\n' % (link,call)
919
918
920 if index is None:
919 if index is None:
921 frames.append(level)
920 frames.append(level)
922 else:
921 else:
923 frames.append('%s%s' % (level,''.join(
922 frames.append('%s%s' % (level,''.join(
924 _format_traceback_lines(lnum,index,lines,Colors,lvals,
923 _format_traceback_lines(lnum,index,lines,Colors,lvals,
925 col_scheme))))
924 col_scheme))))
926
925
927 # Get (safely) a string form of the exception info
926 # Get (safely) a string form of the exception info
928 try:
927 try:
929 etype_str,evalue_str = map(str,(etype,evalue))
928 etype_str,evalue_str = map(str,(etype,evalue))
930 except:
929 except:
931 # User exception is improperly defined.
930 # User exception is improperly defined.
932 etype,evalue = str,sys.exc_info()[:2]
931 etype,evalue = str,sys.exc_info()[:2]
933 etype_str,evalue_str = map(str,(etype,evalue))
932 etype_str,evalue_str = map(str,(etype,evalue))
934 # ... and format it
933 # ... and format it
935 exception = ['%s%s%s: %s' % (Colors.excName, etype_str,
934 exception = ['%s%s%s: %s' % (Colors.excName, etype_str,
936 ColorsNormal, evalue_str)]
935 ColorsNormal, evalue_str)]
937 if type(evalue) is types.InstanceType:
936 if type(evalue) is types.InstanceType:
938 try:
937 try:
939 names = [w for w in dir(evalue) if isinstance(w, basestring)]
938 names = [w for w in dir(evalue) if isinstance(w, basestring)]
940 except:
939 except:
941 # Every now and then, an object with funny inernals blows up
940 # Every now and then, an object with funny inernals blows up
942 # when dir() is called on it. We do the best we can to report
941 # when dir() is called on it. We do the best we can to report
943 # the problem and continue
942 # the problem and continue
944 _m = '%sException reporting error (object with broken dir())%s:'
943 _m = '%sException reporting error (object with broken dir())%s:'
945 exception.append(_m % (Colors.excName,ColorsNormal))
944 exception.append(_m % (Colors.excName,ColorsNormal))
946 etype_str,evalue_str = map(str,sys.exc_info()[:2])
945 etype_str,evalue_str = map(str,sys.exc_info()[:2])
947 exception.append('%s%s%s: %s' % (Colors.excName,etype_str,
946 exception.append('%s%s%s: %s' % (Colors.excName,etype_str,
948 ColorsNormal, evalue_str))
947 ColorsNormal, evalue_str))
949 names = []
948 names = []
950 for name in names:
949 for name in names:
951 value = text_repr(getattr(evalue, name))
950 value = text_repr(getattr(evalue, name))
952 exception.append('\n%s%s = %s' % (indent, name, value))
951 exception.append('\n%s%s = %s' % (indent, name, value))
953
952
954 # vds: >>
953 # vds: >>
955 if records:
954 if records:
956 filepath, lnum = records[-1][1:3]
955 filepath, lnum = records[-1][1:3]
957 #print "file:", str(file), "linenb", str(lnum) # dbg
956 #print "file:", str(file), "linenb", str(lnum) # dbg
958 filepath = os.path.abspath(filepath)
957 filepath = os.path.abspath(filepath)
959 ipinst = ipapi.get()
958 ipinst = ipapi.get()
960 if ipinst is not None:
959 if ipinst is not None:
961 ipinst.hooks.synchronize_with_editor(filepath, lnum, 0)
960 ipinst.hooks.synchronize_with_editor(filepath, lnum, 0)
962 # vds: <<
961 # vds: <<
963
962
964 # return all our info assembled as a single string
963 # return all our info assembled as a single string
965 # return '%s\n\n%s\n%s' % (head,'\n'.join(frames),''.join(exception[0]) )
964 # return '%s\n\n%s\n%s' % (head,'\n'.join(frames),''.join(exception[0]) )
966 return [head] + frames + [''.join(exception[0])]
965 return [head] + frames + [''.join(exception[0])]
967
966
968 def debugger(self,force=False):
967 def debugger(self,force=False):
969 """Call up the pdb debugger if desired, always clean up the tb
968 """Call up the pdb debugger if desired, always clean up the tb
970 reference.
969 reference.
971
970
972 Keywords:
971 Keywords:
973
972
974 - force(False): by default, this routine checks the instance call_pdb
973 - force(False): by default, this routine checks the instance call_pdb
975 flag and does not actually invoke the debugger if the flag is false.
974 flag and does not actually invoke the debugger if the flag is false.
976 The 'force' option forces the debugger to activate even if the flag
975 The 'force' option forces the debugger to activate even if the flag
977 is false.
976 is false.
978
977
979 If the call_pdb flag is set, the pdb interactive debugger is
978 If the call_pdb flag is set, the pdb interactive debugger is
980 invoked. In all cases, the self.tb reference to the current traceback
979 invoked. In all cases, the self.tb reference to the current traceback
981 is deleted to prevent lingering references which hamper memory
980 is deleted to prevent lingering references which hamper memory
982 management.
981 management.
983
982
984 Note that each call to pdb() does an 'import readline', so if your app
983 Note that each call to pdb() does an 'import readline', so if your app
985 requires a special setup for the readline completers, you'll have to
984 requires a special setup for the readline completers, you'll have to
986 fix that by hand after invoking the exception handler."""
985 fix that by hand after invoking the exception handler."""
987
986
988 if force or self.call_pdb:
987 if force or self.call_pdb:
989 if self.pdb is None:
988 if self.pdb is None:
990 self.pdb = debugger.Pdb(
989 self.pdb = debugger.Pdb(
991 self.color_scheme_table.active_scheme_name)
990 self.color_scheme_table.active_scheme_name)
992 # the system displayhook may have changed, restore the original
991 # the system displayhook may have changed, restore the original
993 # for pdb
992 # for pdb
994 display_trap = DisplayTrap(hook=sys.__displayhook__)
993 display_trap = DisplayTrap(hook=sys.__displayhook__)
995 with display_trap:
994 with display_trap:
996 self.pdb.reset()
995 self.pdb.reset()
997 # Find the right frame so we don't pop up inside ipython itself
996 # Find the right frame so we don't pop up inside ipython itself
998 if hasattr(self,'tb') and self.tb is not None:
997 if hasattr(self,'tb') and self.tb is not None:
999 etb = self.tb
998 etb = self.tb
1000 else:
999 else:
1001 etb = self.tb = sys.last_traceback
1000 etb = self.tb = sys.last_traceback
1002 while self.tb is not None and self.tb.tb_next is not None:
1001 while self.tb is not None and self.tb.tb_next is not None:
1003 self.tb = self.tb.tb_next
1002 self.tb = self.tb.tb_next
1004 if etb and etb.tb_next:
1003 if etb and etb.tb_next:
1005 etb = etb.tb_next
1004 etb = etb.tb_next
1006 self.pdb.botframe = etb.tb_frame
1005 self.pdb.botframe = etb.tb_frame
1007 self.pdb.interaction(self.tb.tb_frame, self.tb)
1006 self.pdb.interaction(self.tb.tb_frame, self.tb)
1008
1007
1009 if hasattr(self,'tb'):
1008 if hasattr(self,'tb'):
1010 del self.tb
1009 del self.tb
1011
1010
1012 def handler(self, info=None):
1011 def handler(self, info=None):
1013 (etype, evalue, etb) = info or sys.exc_info()
1012 (etype, evalue, etb) = info or sys.exc_info()
1014 self.tb = etb
1013 self.tb = etb
1015 ostream = self.ostream
1014 ostream = self.ostream
1016 ostream.flush()
1015 ostream.flush()
1017 ostream.write(self.text(etype, evalue, etb))
1016 ostream.write(self.text(etype, evalue, etb))
1018 ostream.write('\n')
1017 ostream.write('\n')
1019 ostream.flush()
1018 ostream.flush()
1020
1019
1021 # Changed so an instance can just be called as VerboseTB_inst() and print
1020 # Changed so an instance can just be called as VerboseTB_inst() and print
1022 # out the right info on its own.
1021 # out the right info on its own.
1023 def __call__(self, etype=None, evalue=None, etb=None):
1022 def __call__(self, etype=None, evalue=None, etb=None):
1024 """This hook can replace sys.excepthook (for Python 2.1 or higher)."""
1023 """This hook can replace sys.excepthook (for Python 2.1 or higher)."""
1025 if etb is None:
1024 if etb is None:
1026 self.handler()
1025 self.handler()
1027 else:
1026 else:
1028 self.handler((etype, evalue, etb))
1027 self.handler((etype, evalue, etb))
1029 try:
1028 try:
1030 self.debugger()
1029 self.debugger()
1031 except KeyboardInterrupt:
1030 except KeyboardInterrupt:
1032 print "\nKeyboardInterrupt"
1031 print "\nKeyboardInterrupt"
1033
1032
1034 #----------------------------------------------------------------------------
1033 #----------------------------------------------------------------------------
1035 class FormattedTB(VerboseTB, ListTB):
1034 class FormattedTB(VerboseTB, ListTB):
1036 """Subclass ListTB but allow calling with a traceback.
1035 """Subclass ListTB but allow calling with a traceback.
1037
1036
1038 It can thus be used as a sys.excepthook for Python > 2.1.
1037 It can thus be used as a sys.excepthook for Python > 2.1.
1039
1038
1040 Also adds 'Context' and 'Verbose' modes, not available in ListTB.
1039 Also adds 'Context' and 'Verbose' modes, not available in ListTB.
1041
1040
1042 Allows a tb_offset to be specified. This is useful for situations where
1041 Allows a tb_offset to be specified. This is useful for situations where
1043 one needs to remove a number of topmost frames from the traceback (such as
1042 one needs to remove a number of topmost frames from the traceback (such as
1044 occurs with python programs that themselves execute other python code,
1043 occurs with python programs that themselves execute other python code,
1045 like Python shells). """
1044 like Python shells). """
1046
1045
1047 def __init__(self, mode='Plain', color_scheme='Linux', call_pdb=False,
1046 def __init__(self, mode='Plain', color_scheme='Linux', call_pdb=False,
1048 ostream=None,
1047 ostream=None,
1049 tb_offset=0, long_header=False, include_vars=False,
1048 tb_offset=0, long_header=False, include_vars=False,
1050 check_cache=None):
1049 check_cache=None):
1051
1050
1052 # NEVER change the order of this list. Put new modes at the end:
1051 # NEVER change the order of this list. Put new modes at the end:
1053 self.valid_modes = ['Plain','Context','Verbose']
1052 self.valid_modes = ['Plain','Context','Verbose']
1054 self.verbose_modes = self.valid_modes[1:3]
1053 self.verbose_modes = self.valid_modes[1:3]
1055
1054
1056 VerboseTB.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
1055 VerboseTB.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
1057 ostream=ostream, tb_offset=tb_offset,
1056 ostream=ostream, tb_offset=tb_offset,
1058 long_header=long_header, include_vars=include_vars,
1057 long_header=long_header, include_vars=include_vars,
1059 check_cache=check_cache)
1058 check_cache=check_cache)
1060
1059
1061 # Different types of tracebacks are joined with different separators to
1060 # Different types of tracebacks are joined with different separators to
1062 # form a single string. They are taken from this dict
1061 # form a single string. They are taken from this dict
1063 self._join_chars = dict(Plain='', Context='\n', Verbose='\n')
1062 self._join_chars = dict(Plain='', Context='\n', Verbose='\n')
1064 # set_mode also sets the tb_join_char attribute
1063 # set_mode also sets the tb_join_char attribute
1065 self.set_mode(mode)
1064 self.set_mode(mode)
1066
1065
1067 def _extract_tb(self,tb):
1066 def _extract_tb(self,tb):
1068 if tb:
1067 if tb:
1069 return traceback.extract_tb(tb)
1068 return traceback.extract_tb(tb)
1070 else:
1069 else:
1071 return None
1070 return None
1072
1071
1073 def structured_traceback(self, etype, value, tb, tb_offset=None, context=5):
1072 def structured_traceback(self, etype, value, tb, tb_offset=None, context=5):
1074 tb_offset = self.tb_offset if tb_offset is None else tb_offset
1073 tb_offset = self.tb_offset if tb_offset is None else tb_offset
1075 mode = self.mode
1074 mode = self.mode
1076 if mode in self.verbose_modes:
1075 if mode in self.verbose_modes:
1077 # Verbose modes need a full traceback
1076 # Verbose modes need a full traceback
1078 return VerboseTB.structured_traceback(
1077 return VerboseTB.structured_traceback(
1079 self, etype, value, tb, tb_offset, context
1078 self, etype, value, tb, tb_offset, context
1080 )
1079 )
1081 else:
1080 else:
1082 # We must check the source cache because otherwise we can print
1081 # We must check the source cache because otherwise we can print
1083 # out-of-date source code.
1082 # out-of-date source code.
1084 self.check_cache()
1083 self.check_cache()
1085 # Now we can extract and format the exception
1084 # Now we can extract and format the exception
1086 elist = self._extract_tb(tb)
1085 elist = self._extract_tb(tb)
1087 return ListTB.structured_traceback(
1086 return ListTB.structured_traceback(
1088 self, etype, value, elist, tb_offset, context
1087 self, etype, value, elist, tb_offset, context
1089 )
1088 )
1090
1089
1091 def stb2text(self, stb):
1090 def stb2text(self, stb):
1092 """Convert a structured traceback (a list) to a string."""
1091 """Convert a structured traceback (a list) to a string."""
1093 return self.tb_join_char.join(stb)
1092 return self.tb_join_char.join(stb)
1094
1093
1095
1094
1096 def set_mode(self,mode=None):
1095 def set_mode(self,mode=None):
1097 """Switch to the desired mode.
1096 """Switch to the desired mode.
1098
1097
1099 If mode is not specified, cycles through the available modes."""
1098 If mode is not specified, cycles through the available modes."""
1100
1099
1101 if not mode:
1100 if not mode:
1102 new_idx = ( self.valid_modes.index(self.mode) + 1 ) % \
1101 new_idx = ( self.valid_modes.index(self.mode) + 1 ) % \
1103 len(self.valid_modes)
1102 len(self.valid_modes)
1104 self.mode = self.valid_modes[new_idx]
1103 self.mode = self.valid_modes[new_idx]
1105 elif mode not in self.valid_modes:
1104 elif mode not in self.valid_modes:
1106 raise ValueError, 'Unrecognized mode in FormattedTB: <'+mode+'>\n'\
1105 raise ValueError, 'Unrecognized mode in FormattedTB: <'+mode+'>\n'\
1107 'Valid modes: '+str(self.valid_modes)
1106 'Valid modes: '+str(self.valid_modes)
1108 else:
1107 else:
1109 self.mode = mode
1108 self.mode = mode
1110 # include variable details only in 'Verbose' mode
1109 # include variable details only in 'Verbose' mode
1111 self.include_vars = (self.mode == self.valid_modes[2])
1110 self.include_vars = (self.mode == self.valid_modes[2])
1112 # Set the join character for generating text tracebacks
1111 # Set the join character for generating text tracebacks
1113 self.tb_join_char = self._join_chars[self.mode]
1112 self.tb_join_char = self._join_chars[self.mode]
1114
1113
1115 # some convenient shorcuts
1114 # some convenient shorcuts
1116 def plain(self):
1115 def plain(self):
1117 self.set_mode(self.valid_modes[0])
1116 self.set_mode(self.valid_modes[0])
1118
1117
1119 def context(self):
1118 def context(self):
1120 self.set_mode(self.valid_modes[1])
1119 self.set_mode(self.valid_modes[1])
1121
1120
1122 def verbose(self):
1121 def verbose(self):
1123 self.set_mode(self.valid_modes[2])
1122 self.set_mode(self.valid_modes[2])
1124
1123
1125 #----------------------------------------------------------------------------
1124 #----------------------------------------------------------------------------
1126 class AutoFormattedTB(FormattedTB):
1125 class AutoFormattedTB(FormattedTB):
1127 """A traceback printer which can be called on the fly.
1126 """A traceback printer which can be called on the fly.
1128
1127
1129 It will find out about exceptions by itself.
1128 It will find out about exceptions by itself.
1130
1129
1131 A brief example:
1130 A brief example:
1132
1131
1133 AutoTB = AutoFormattedTB(mode = 'Verbose',color_scheme='Linux')
1132 AutoTB = AutoFormattedTB(mode = 'Verbose',color_scheme='Linux')
1134 try:
1133 try:
1135 ...
1134 ...
1136 except:
1135 except:
1137 AutoTB() # or AutoTB(out=logfile) where logfile is an open file object
1136 AutoTB() # or AutoTB(out=logfile) where logfile is an open file object
1138 """
1137 """
1139
1138
1140 def __call__(self,etype=None,evalue=None,etb=None,
1139 def __call__(self,etype=None,evalue=None,etb=None,
1141 out=None,tb_offset=None):
1140 out=None,tb_offset=None):
1142 """Print out a formatted exception traceback.
1141 """Print out a formatted exception traceback.
1143
1142
1144 Optional arguments:
1143 Optional arguments:
1145 - out: an open file-like object to direct output to.
1144 - out: an open file-like object to direct output to.
1146
1145
1147 - tb_offset: the number of frames to skip over in the stack, on a
1146 - tb_offset: the number of frames to skip over in the stack, on a
1148 per-call basis (this overrides temporarily the instance's tb_offset
1147 per-call basis (this overrides temporarily the instance's tb_offset
1149 given at initialization time. """
1148 given at initialization time. """
1150
1149
1151
1150
1152 if out is None:
1151 if out is None:
1153 out = self.ostream
1152 out = self.ostream
1154 out.flush()
1153 out.flush()
1155 out.write(self.text(etype, evalue, etb, tb_offset))
1154 out.write(self.text(etype, evalue, etb, tb_offset))
1156 out.write('\n')
1155 out.write('\n')
1157 out.flush()
1156 out.flush()
1158 # FIXME: we should remove the auto pdb behavior from here and leave
1157 # FIXME: we should remove the auto pdb behavior from here and leave
1159 # that to the clients.
1158 # that to the clients.
1160 try:
1159 try:
1161 self.debugger()
1160 self.debugger()
1162 except KeyboardInterrupt:
1161 except KeyboardInterrupt:
1163 print "\nKeyboardInterrupt"
1162 print "\nKeyboardInterrupt"
1164
1163
1165 def structured_traceback(self, etype=None, value=None, tb=None,
1164 def structured_traceback(self, etype=None, value=None, tb=None,
1166 tb_offset=None, context=5):
1165 tb_offset=None, context=5):
1167 if etype is None:
1166 if etype is None:
1168 etype,value,tb = sys.exc_info()
1167 etype,value,tb = sys.exc_info()
1169 self.tb = tb
1168 self.tb = tb
1170 return FormattedTB.structured_traceback(
1169 return FormattedTB.structured_traceback(
1171 self, etype, value, tb, tb_offset, context)
1170 self, etype, value, tb, tb_offset, context)
1172
1171
1173 #---------------------------------------------------------------------------
1172 #---------------------------------------------------------------------------
1174
1173
1175 # A simple class to preserve Nathan's original functionality.
1174 # A simple class to preserve Nathan's original functionality.
1176 class ColorTB(FormattedTB):
1175 class ColorTB(FormattedTB):
1177 """Shorthand to initialize a FormattedTB in Linux colors mode."""
1176 """Shorthand to initialize a FormattedTB in Linux colors mode."""
1178 def __init__(self,color_scheme='Linux',call_pdb=0):
1177 def __init__(self,color_scheme='Linux',call_pdb=0):
1179 FormattedTB.__init__(self,color_scheme=color_scheme,
1178 FormattedTB.__init__(self,color_scheme=color_scheme,
1180 call_pdb=call_pdb)
1179 call_pdb=call_pdb)
1181
1180
1182
1181
1183 class SyntaxTB(ListTB):
1182 class SyntaxTB(ListTB):
1184 """Extension which holds some state: the last exception value"""
1183 """Extension which holds some state: the last exception value"""
1185
1184
1186 def __init__(self,color_scheme = 'NoColor'):
1185 def __init__(self,color_scheme = 'NoColor'):
1187 ListTB.__init__(self,color_scheme)
1186 ListTB.__init__(self,color_scheme)
1188 self.last_syntax_error = None
1187 self.last_syntax_error = None
1189
1188
1190 def __call__(self, etype, value, elist):
1189 def __call__(self, etype, value, elist):
1191 self.last_syntax_error = value
1190 self.last_syntax_error = value
1192 ListTB.__call__(self,etype,value,elist)
1191 ListTB.__call__(self,etype,value,elist)
1193
1192
1194 def clear_err_state(self):
1193 def clear_err_state(self):
1195 """Return the current error state and clear it"""
1194 """Return the current error state and clear it"""
1196 e = self.last_syntax_error
1195 e = self.last_syntax_error
1197 self.last_syntax_error = None
1196 self.last_syntax_error = None
1198 return e
1197 return e
1199
1198
1200 def stb2text(self, stb):
1199 def stb2text(self, stb):
1201 """Convert a structured traceback (a list) to a string."""
1200 """Convert a structured traceback (a list) to a string."""
1202 return ''.join(stb)
1201 return ''.join(stb)
1203
1202
1204
1203
1205 #----------------------------------------------------------------------------
1204 #----------------------------------------------------------------------------
1206 # module testing (minimal)
1205 # module testing (minimal)
1207 if __name__ == "__main__":
1206 if __name__ == "__main__":
1208 def spam(c, (d, e)):
1207 def spam(c, (d, e)):
1209 x = c + d
1208 x = c + d
1210 y = c * d
1209 y = c * d
1211 foo(x, y)
1210 foo(x, y)
1212
1211
1213 def foo(a, b, bar=1):
1212 def foo(a, b, bar=1):
1214 eggs(a, b + bar)
1213 eggs(a, b + bar)
1215
1214
1216 def eggs(f, g, z=globals()):
1215 def eggs(f, g, z=globals()):
1217 h = f + g
1216 h = f + g
1218 i = f - g
1217 i = f - g
1219 return h / i
1218 return h / i
1220
1219
1221 print ''
1220 print ''
1222 print '*** Before ***'
1221 print '*** Before ***'
1223 try:
1222 try:
1224 print spam(1, (2, 3))
1223 print spam(1, (2, 3))
1225 except:
1224 except:
1226 traceback.print_exc()
1225 traceback.print_exc()
1227 print ''
1226 print ''
1228
1227
1229 handler = ColorTB()
1228 handler = ColorTB()
1230 print '*** ColorTB ***'
1229 print '*** ColorTB ***'
1231 try:
1230 try:
1232 print spam(1, (2, 3))
1231 print spam(1, (2, 3))
1233 except:
1232 except:
1234 apply(handler, sys.exc_info() )
1233 apply(handler, sys.exc_info() )
1235 print ''
1234 print ''
1236
1235
1237 handler = VerboseTB()
1236 handler = VerboseTB()
1238 print '*** VerboseTB ***'
1237 print '*** VerboseTB ***'
1239 try:
1238 try:
1240 print spam(1, (2, 3))
1239 print spam(1, (2, 3))
1241 except:
1240 except:
1242 apply(handler, sys.exc_info() )
1241 apply(handler, sys.exc_info() )
1243 print ''
1242 print ''
1244
1243
@@ -1,275 +1,274 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """String interpolation for Python (by Ka-Ping Yee, 14 Feb 2000).
2 """String interpolation for Python (by Ka-Ping Yee, 14 Feb 2000).
3
3
4 This module lets you quickly and conveniently interpolate values into
4 This module lets you quickly and conveniently interpolate values into
5 strings (in the flavour of Perl or Tcl, but with less extraneous
5 strings (in the flavour of Perl or Tcl, but with less extraneous
6 punctuation). You get a bit more power than in the other languages,
6 punctuation). You get a bit more power than in the other languages,
7 because this module allows subscripting, slicing, function calls,
7 because this module allows subscripting, slicing, function calls,
8 attribute lookup, or arbitrary expressions. Variables and expressions
8 attribute lookup, or arbitrary expressions. Variables and expressions
9 are evaluated in the namespace of the caller.
9 are evaluated in the namespace of the caller.
10
10
11 The itpl() function returns the result of interpolating a string, and
11 The itpl() function returns the result of interpolating a string, and
12 printpl() prints out an interpolated string. Here are some examples:
12 printpl() prints out an interpolated string. Here are some examples:
13
13
14 from Itpl import printpl
14 from Itpl import printpl
15 printpl("Here is a $string.")
15 printpl("Here is a $string.")
16 printpl("Here is a $module.member.")
16 printpl("Here is a $module.member.")
17 printpl("Here is an $object.member.")
17 printpl("Here is an $object.member.")
18 printpl("Here is a $functioncall(with, arguments).")
18 printpl("Here is a $functioncall(with, arguments).")
19 printpl("Here is an ${arbitrary + expression}.")
19 printpl("Here is an ${arbitrary + expression}.")
20 printpl("Here is an $array[3] member.")
20 printpl("Here is an $array[3] member.")
21 printpl("Here is a $dictionary['member'].")
21 printpl("Here is a $dictionary['member'].")
22
22
23 The filter() function filters a file object so that output through it
23 The filter() function filters a file object so that output through it
24 is interpolated. This lets you produce the illusion that Python knows
24 is interpolated. This lets you produce the illusion that Python knows
25 how to do interpolation:
25 how to do interpolation:
26
26
27 import Itpl
27 import Itpl
28 sys.stdout = Itpl.filter()
28 sys.stdout = Itpl.filter()
29 f = "fancy"
29 f = "fancy"
30 print "Is this not $f?"
30 print "Is this not $f?"
31 print "Standard output has been replaced with a $sys.stdout object."
31 print "Standard output has been replaced with a $sys.stdout object."
32 sys.stdout = Itpl.unfilter()
32 sys.stdout = Itpl.unfilter()
33 print "Okay, back $to $normal."
33 print "Okay, back $to $normal."
34
34
35 Under the hood, the Itpl class represents a string that knows how to
35 Under the hood, the Itpl class represents a string that knows how to
36 interpolate values. An instance of the class parses the string once
36 interpolate values. An instance of the class parses the string once
37 upon initialization; the evaluation and substitution can then be done
37 upon initialization; the evaluation and substitution can then be done
38 each time the instance is evaluated with str(instance). For example:
38 each time the instance is evaluated with str(instance). For example:
39
39
40 from Itpl import Itpl
40 from Itpl import Itpl
41 s = Itpl("Here is $foo.")
41 s = Itpl("Here is $foo.")
42 foo = 5
42 foo = 5
43 print str(s)
43 print str(s)
44 foo = "bar"
44 foo = "bar"
45 print str(s)
45 print str(s)
46 """
46 """
47
47
48 #*****************************************************************************
48 #*****************************************************************************
49 #
49 #
50 # Copyright (c) 2001 Ka-Ping Yee <ping@lfw.org>
50 # Copyright (c) 2001 Ka-Ping Yee <ping@lfw.org>
51 #
51 #
52 #
52 #
53 # Published under the terms of the MIT license, hereby reproduced:
53 # Published under the terms of the MIT license, hereby reproduced:
54 #
54 #
55 # Permission is hereby granted, free of charge, to any person obtaining a copy
55 # Permission is hereby granted, free of charge, to any person obtaining a copy
56 # of this software and associated documentation files (the "Software"), to
56 # of this software and associated documentation files (the "Software"), to
57 # deal in the Software without restriction, including without limitation the
57 # deal in the Software without restriction, including without limitation the
58 # rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
58 # rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
59 # sell copies of the Software, and to permit persons to whom the Software is
59 # sell copies of the Software, and to permit persons to whom the Software is
60 # furnished to do so, subject to the following conditions:
60 # furnished to do so, subject to the following conditions:
61 #
61 #
62 # The above copyright notice and this permission notice shall be included in
62 # The above copyright notice and this permission notice shall be included in
63 # all copies or substantial portions of the Software.
63 # all copies or substantial portions of the Software.
64 #
64 #
65 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
65 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
66 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
66 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
67 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
67 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
68 # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
68 # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
69 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
69 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
70 # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
70 # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
71 # IN THE SOFTWARE.
71 # IN THE SOFTWARE.
72 #
72 #
73 #*****************************************************************************
73 #*****************************************************************************
74
74
75 __author__ = 'Ka-Ping Yee <ping@lfw.org>'
75 __author__ = 'Ka-Ping Yee <ping@lfw.org>'
76 __license__ = 'MIT'
76 __license__ = 'MIT'
77
77
78 import string
79 import sys
78 import sys
80 from tokenize import tokenprog
79 from tokenize import tokenprog
81
80
82 class ItplError(ValueError):
81 class ItplError(ValueError):
83 def __init__(self, text, pos):
82 def __init__(self, text, pos):
84 self.text = text
83 self.text = text
85 self.pos = pos
84 self.pos = pos
86 def __str__(self):
85 def __str__(self):
87 return "unfinished expression in %s at char %d" % (
86 return "unfinished expression in %s at char %d" % (
88 repr(self.text), self.pos)
87 repr(self.text), self.pos)
89
88
90 def matchorfail(text, pos):
89 def matchorfail(text, pos):
91 match = tokenprog.match(text, pos)
90 match = tokenprog.match(text, pos)
92 if match is None:
91 if match is None:
93 raise ItplError(text, pos)
92 raise ItplError(text, pos)
94 return match, match.end()
93 return match, match.end()
95
94
96 class Itpl:
95 class Itpl:
97 """Class representing a string with interpolation abilities.
96 """Class representing a string with interpolation abilities.
98
97
99 Upon creation, an instance works out what parts of the format
98 Upon creation, an instance works out what parts of the format
100 string are literal and what parts need to be evaluated. The
99 string are literal and what parts need to be evaluated. The
101 evaluation and substitution happens in the namespace of the
100 evaluation and substitution happens in the namespace of the
102 caller when str(instance) is called."""
101 caller when str(instance) is called."""
103
102
104 def __init__(self, format,codec='utf_8',encoding_errors='backslashreplace'):
103 def __init__(self, format,codec='utf_8',encoding_errors='backslashreplace'):
105 """The single mandatory argument to this constructor is a format
104 """The single mandatory argument to this constructor is a format
106 string.
105 string.
107
106
108 The format string is parsed according to the following rules:
107 The format string is parsed according to the following rules:
109
108
110 1. A dollar sign and a name, possibly followed by any of:
109 1. A dollar sign and a name, possibly followed by any of:
111 - an open-paren, and anything up to the matching paren
110 - an open-paren, and anything up to the matching paren
112 - an open-bracket, and anything up to the matching bracket
111 - an open-bracket, and anything up to the matching bracket
113 - a period and a name
112 - a period and a name
114 any number of times, is evaluated as a Python expression.
113 any number of times, is evaluated as a Python expression.
115
114
116 2. A dollar sign immediately followed by an open-brace, and
115 2. A dollar sign immediately followed by an open-brace, and
117 anything up to the matching close-brace, is evaluated as
116 anything up to the matching close-brace, is evaluated as
118 a Python expression.
117 a Python expression.
119
118
120 3. Outside of the expressions described in the above two rules,
119 3. Outside of the expressions described in the above two rules,
121 two dollar signs in a row give you one literal dollar sign.
120 two dollar signs in a row give you one literal dollar sign.
122
121
123 Optional arguments:
122 Optional arguments:
124
123
125 - codec('utf_8'): a string containing the name of a valid Python
124 - codec('utf_8'): a string containing the name of a valid Python
126 codec.
125 codec.
127
126
128 - encoding_errors('backslashreplace'): a string with a valid error handling
127 - encoding_errors('backslashreplace'): a string with a valid error handling
129 policy. See the codecs module documentation for details.
128 policy. See the codecs module documentation for details.
130
129
131 These are used to encode the format string if a call to str() fails on
130 These are used to encode the format string if a call to str() fails on
132 the expanded result."""
131 the expanded result."""
133
132
134 if not isinstance(format,basestring):
133 if not isinstance(format,basestring):
135 raise TypeError, "needs string initializer"
134 raise TypeError, "needs string initializer"
136 self.format = format
135 self.format = format
137 self.codec = codec
136 self.codec = codec
138 self.encoding_errors = encoding_errors
137 self.encoding_errors = encoding_errors
139
138
140 namechars = "abcdefghijklmnopqrstuvwxyz" \
139 namechars = "abcdefghijklmnopqrstuvwxyz" \
141 "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_";
140 "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_";
142 chunks = []
141 chunks = []
143 pos = 0
142 pos = 0
144
143
145 while 1:
144 while 1:
146 dollar = format.find("$", pos)
145 dollar = format.find("$", pos)
147 if dollar < 0: break
146 if dollar < 0: break
148 nextchar = format[dollar+1]
147 nextchar = format[dollar+1]
149
148
150 if nextchar == "{":
149 if nextchar == "{":
151 chunks.append((0, format[pos:dollar]))
150 chunks.append((0, format[pos:dollar]))
152 pos, level = dollar+2, 1
151 pos, level = dollar+2, 1
153 while level:
152 while level:
154 match, pos = matchorfail(format, pos)
153 match, pos = matchorfail(format, pos)
155 tstart, tend = match.regs[3]
154 tstart, tend = match.regs[3]
156 token = format[tstart:tend]
155 token = format[tstart:tend]
157 if token == "{": level = level+1
156 if token == "{": level = level+1
158 elif token == "}": level = level-1
157 elif token == "}": level = level-1
159 chunks.append((1, format[dollar+2:pos-1]))
158 chunks.append((1, format[dollar+2:pos-1]))
160
159
161 elif nextchar in namechars:
160 elif nextchar in namechars:
162 chunks.append((0, format[pos:dollar]))
161 chunks.append((0, format[pos:dollar]))
163 match, pos = matchorfail(format, dollar+1)
162 match, pos = matchorfail(format, dollar+1)
164 while pos < len(format):
163 while pos < len(format):
165 if format[pos] == "." and \
164 if format[pos] == "." and \
166 pos+1 < len(format) and format[pos+1] in namechars:
165 pos+1 < len(format) and format[pos+1] in namechars:
167 match, pos = matchorfail(format, pos+1)
166 match, pos = matchorfail(format, pos+1)
168 elif format[pos] in "([":
167 elif format[pos] in "([":
169 pos, level = pos+1, 1
168 pos, level = pos+1, 1
170 while level:
169 while level:
171 match, pos = matchorfail(format, pos)
170 match, pos = matchorfail(format, pos)
172 tstart, tend = match.regs[3]
171 tstart, tend = match.regs[3]
173 token = format[tstart:tend]
172 token = format[tstart:tend]
174 if token[0] in "([": level = level+1
173 if token[0] in "([": level = level+1
175 elif token[0] in ")]": level = level-1
174 elif token[0] in ")]": level = level-1
176 else: break
175 else: break
177 chunks.append((1, format[dollar+1:pos]))
176 chunks.append((1, format[dollar+1:pos]))
178
177
179 else:
178 else:
180 chunks.append((0, format[pos:dollar+1]))
179 chunks.append((0, format[pos:dollar+1]))
181 pos = dollar + 1 + (nextchar == "$")
180 pos = dollar + 1 + (nextchar == "$")
182
181
183 if pos < len(format): chunks.append((0, format[pos:]))
182 if pos < len(format): chunks.append((0, format[pos:]))
184 self.chunks = chunks
183 self.chunks = chunks
185
184
186 def __repr__(self):
185 def __repr__(self):
187 return "<Itpl %s >" % repr(self.format)
186 return "<Itpl %s >" % repr(self.format)
188
187
189 def _str(self,glob,loc):
188 def _str(self,glob,loc):
190 """Evaluate to a string in the given globals/locals.
189 """Evaluate to a string in the given globals/locals.
191
190
192 The final output is built by calling str(), but if this fails, the
191 The final output is built by calling str(), but if this fails, the
193 result is encoded with the instance's codec and error handling policy,
192 result is encoded with the instance's codec and error handling policy,
194 via a call to out.encode(self.codec,self.encoding_errors)"""
193 via a call to out.encode(self.codec,self.encoding_errors)"""
195 result = []
194 result = []
196 app = result.append
195 app = result.append
197 for live, chunk in self.chunks:
196 for live, chunk in self.chunks:
198 if live: app(str(eval(chunk,glob,loc)))
197 if live: app(str(eval(chunk,glob,loc)))
199 else: app(chunk)
198 else: app(chunk)
200 out = ''.join(result)
199 out = ''.join(result)
201 try:
200 try:
202 return str(out)
201 return str(out)
203 except UnicodeError:
202 except UnicodeError:
204 return out.encode(self.codec,self.encoding_errors)
203 return out.encode(self.codec,self.encoding_errors)
205
204
206 def __str__(self):
205 def __str__(self):
207 """Evaluate and substitute the appropriate parts of the string."""
206 """Evaluate and substitute the appropriate parts of the string."""
208
207
209 # We need to skip enough frames to get to the actual caller outside of
208 # We need to skip enough frames to get to the actual caller outside of
210 # Itpl.
209 # Itpl.
211 frame = sys._getframe(1)
210 frame = sys._getframe(1)
212 while frame.f_globals["__name__"] == __name__: frame = frame.f_back
211 while frame.f_globals["__name__"] == __name__: frame = frame.f_back
213 loc, glob = frame.f_locals, frame.f_globals
212 loc, glob = frame.f_locals, frame.f_globals
214
213
215 return self._str(glob,loc)
214 return self._str(glob,loc)
216
215
217 class ItplNS(Itpl):
216 class ItplNS(Itpl):
218 """Class representing a string with interpolation abilities.
217 """Class representing a string with interpolation abilities.
219
218
220 This inherits from Itpl, but at creation time a namespace is provided
219 This inherits from Itpl, but at creation time a namespace is provided
221 where the evaluation will occur. The interpolation becomes a bit more
220 where the evaluation will occur. The interpolation becomes a bit more
222 efficient, as no traceback needs to be extracte. It also allows the
221 efficient, as no traceback needs to be extracte. It also allows the
223 caller to supply a different namespace for the interpolation to occur than
222 caller to supply a different namespace for the interpolation to occur than
224 its own."""
223 its own."""
225
224
226 def __init__(self, format,globals,locals=None,
225 def __init__(self, format,globals,locals=None,
227 codec='utf_8',encoding_errors='backslashreplace'):
226 codec='utf_8',encoding_errors='backslashreplace'):
228 """ItplNS(format,globals[,locals]) -> interpolating string instance.
227 """ItplNS(format,globals[,locals]) -> interpolating string instance.
229
228
230 This constructor, besides a format string, takes a globals dictionary
229 This constructor, besides a format string, takes a globals dictionary
231 and optionally a locals (which defaults to globals if not provided).
230 and optionally a locals (which defaults to globals if not provided).
232
231
233 For further details, see the Itpl constructor."""
232 For further details, see the Itpl constructor."""
234
233
235 if locals is None:
234 if locals is None:
236 locals = globals
235 locals = globals
237 self.globals = globals
236 self.globals = globals
238 self.locals = locals
237 self.locals = locals
239 Itpl.__init__(self,format,codec,encoding_errors)
238 Itpl.__init__(self,format,codec,encoding_errors)
240
239
241 def __str__(self):
240 def __str__(self):
242 """Evaluate and substitute the appropriate parts of the string."""
241 """Evaluate and substitute the appropriate parts of the string."""
243 return self._str(self.globals,self.locals)
242 return self._str(self.globals,self.locals)
244
243
245 def __repr__(self):
244 def __repr__(self):
246 return "<ItplNS %s >" % repr(self.format)
245 return "<ItplNS %s >" % repr(self.format)
247
246
248 # utilities for fast printing
247 # utilities for fast printing
249 def itpl(text): return str(Itpl(text))
248 def itpl(text): return str(Itpl(text))
250 def printpl(text): print itpl(text)
249 def printpl(text): print itpl(text)
251 # versions with namespace
250 # versions with namespace
252 def itplns(text,globals,locals=None): return str(ItplNS(text,globals,locals))
251 def itplns(text,globals,locals=None): return str(ItplNS(text,globals,locals))
253 def printplns(text,globals,locals=None): print itplns(text,globals,locals)
252 def printplns(text,globals,locals=None): print itplns(text,globals,locals)
254
253
255 class ItplFile:
254 class ItplFile:
256 """A file object that filters each write() through an interpolator."""
255 """A file object that filters each write() through an interpolator."""
257 def __init__(self, file): self.file = file
256 def __init__(self, file): self.file = file
258 def __repr__(self): return "<interpolated " + repr(self.file) + ">"
257 def __repr__(self): return "<interpolated " + repr(self.file) + ">"
259 def __getattr__(self, attr): return getattr(self.file, attr)
258 def __getattr__(self, attr): return getattr(self.file, attr)
260 def write(self, text): self.file.write(str(Itpl(text)))
259 def write(self, text): self.file.write(str(Itpl(text)))
261
260
262 def filter(file=sys.stdout):
261 def filter(file=sys.stdout):
263 """Return an ItplFile that filters writes to the given file object.
262 """Return an ItplFile that filters writes to the given file object.
264
263
265 'file = filter(file)' replaces 'file' with a filtered object that
264 'file = filter(file)' replaces 'file' with a filtered object that
266 has a write() method. When called with no argument, this creates
265 has a write() method. When called with no argument, this creates
267 a filter to sys.stdout."""
266 a filter to sys.stdout."""
268 return ItplFile(file)
267 return ItplFile(file)
269
268
270 def unfilter(ifile=None):
269 def unfilter(ifile=None):
271 """Return the original file that corresponds to the given ItplFile.
270 """Return the original file that corresponds to the given ItplFile.
272
271
273 'file = unfilter(file)' undoes the effect of 'file = filter(file)'.
272 'file = unfilter(file)' undoes the effect of 'file = filter(file)'.
274 'sys.stdout = unfilter()' undoes the effect of 'sys.stdout = filter()'."""
273 'sys.stdout = unfilter()' undoes the effect of 'sys.stdout = filter()'."""
275 return ifile and ifile.file or sys.stdout.file
274 return ifile and ifile.file or sys.stdout.file
@@ -1,1845 +1,1843 b''
1 """Pexpect is a Python module for spawning child applications and controlling
1 """Pexpect is a Python module for spawning child applications and controlling
2 them automatically. Pexpect can be used for automating interactive applications
2 them automatically. Pexpect can be used for automating interactive applications
3 such as ssh, ftp, passwd, telnet, etc. It can be used to a automate setup
3 such as ssh, ftp, passwd, telnet, etc. It can be used to a automate setup
4 scripts for duplicating software package installations on different servers. It
4 scripts for duplicating software package installations on different servers. It
5 can be used for automated software testing. Pexpect is in the spirit of Don
5 can be used for automated software testing. Pexpect is in the spirit of Don
6 Libes' Expect, but Pexpect is pure Python. Other Expect-like modules for Python
6 Libes' Expect, but Pexpect is pure Python. Other Expect-like modules for Python
7 require TCL and Expect or require C extensions to be compiled. Pexpect does not
7 require TCL and Expect or require C extensions to be compiled. Pexpect does not
8 use C, Expect, or TCL extensions. It should work on any platform that supports
8 use C, Expect, or TCL extensions. It should work on any platform that supports
9 the standard Python pty module. The Pexpect interface focuses on ease of use so
9 the standard Python pty module. The Pexpect interface focuses on ease of use so
10 that simple tasks are easy.
10 that simple tasks are easy.
11
11
12 There are two main interfaces to Pexpect -- the function, run() and the class,
12 There are two main interfaces to Pexpect -- the function, run() and the class,
13 spawn. You can call the run() function to execute a command and return the
13 spawn. You can call the run() function to execute a command and return the
14 output. This is a handy replacement for os.system().
14 output. This is a handy replacement for os.system().
15
15
16 For example::
16 For example::
17
17
18 pexpect.run('ls -la')
18 pexpect.run('ls -la')
19
19
20 The more powerful interface is the spawn class. You can use this to spawn an
20 The more powerful interface is the spawn class. You can use this to spawn an
21 external child command and then interact with the child by sending lines and
21 external child command and then interact with the child by sending lines and
22 expecting responses.
22 expecting responses.
23
23
24 For example::
24 For example::
25
25
26 child = pexpect.spawn('scp foo myname@host.example.com:.')
26 child = pexpect.spawn('scp foo myname@host.example.com:.')
27 child.expect ('Password:')
27 child.expect ('Password:')
28 child.sendline (mypassword)
28 child.sendline (mypassword)
29
29
30 This works even for commands that ask for passwords or other input outside of
30 This works even for commands that ask for passwords or other input outside of
31 the normal stdio streams.
31 the normal stdio streams.
32
32
33 Credits: Noah Spurrier, Richard Holden, Marco Molteni, Kimberley Burchett,
33 Credits: Noah Spurrier, Richard Holden, Marco Molteni, Kimberley Burchett,
34 Robert Stone, Hartmut Goebel, Chad Schroeder, Erick Tryzelaar, Dave Kirby, Ids
34 Robert Stone, Hartmut Goebel, Chad Schroeder, Erick Tryzelaar, Dave Kirby, Ids
35 vander Molen, George Todd, Noel Taylor, Nicolas D. Cesar, Alexander Gattin,
35 vander Molen, George Todd, Noel Taylor, Nicolas D. Cesar, Alexander Gattin,
36 Geoffrey Marshall, Francisco Lourenco, Glen Mabey, Karthik Gurusamy, Fernando
36 Geoffrey Marshall, Francisco Lourenco, Glen Mabey, Karthik Gurusamy, Fernando
37 Perez, Corey Minyard, Jon Cohen, Guillaume Chazarain, Andrew Ryan, Nick
37 Perez, Corey Minyard, Jon Cohen, Guillaume Chazarain, Andrew Ryan, Nick
38 Craig-Wood, Andrew Stone, Jorgen Grahn (Let me know if I forgot anyone.)
38 Craig-Wood, Andrew Stone, Jorgen Grahn (Let me know if I forgot anyone.)
39
39
40 Free, open source, and all that good stuff.
40 Free, open source, and all that good stuff.
41
41
42 Permission is hereby granted, free of charge, to any person obtaining a copy of
42 Permission is hereby granted, free of charge, to any person obtaining a copy of
43 this software and associated documentation files (the "Software"), to deal in
43 this software and associated documentation files (the "Software"), to deal in
44 the Software without restriction, including without limitation the rights to
44 the Software without restriction, including without limitation the rights to
45 use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
45 use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
46 of the Software, and to permit persons to whom the Software is furnished to do
46 of the Software, and to permit persons to whom the Software is furnished to do
47 so, subject to the following conditions:
47 so, subject to the following conditions:
48
48
49 The above copyright notice and this permission notice shall be included in all
49 The above copyright notice and this permission notice shall be included in all
50 copies or substantial portions of the Software.
50 copies or substantial portions of the Software.
51
51
52 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
52 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
53 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
53 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
54 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
54 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
55 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
55 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
56 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
56 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
57 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
57 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
58 SOFTWARE.
58 SOFTWARE.
59
59
60 Pexpect Copyright (c) 2008 Noah Spurrier
60 Pexpect Copyright (c) 2008 Noah Spurrier
61 http://pexpect.sourceforge.net/
61 http://pexpect.sourceforge.net/
62
62
63 $Id: pexpect.py 507 2007-12-27 02:40:52Z noah $
63 $Id: pexpect.py 507 2007-12-27 02:40:52Z noah $
64 """
64 """
65
65
66 try:
66 try:
67 import os, sys, time
67 import os, sys, time
68 import select
68 import select
69 import string
70 import re
69 import re
71 import struct
70 import struct
72 import resource
71 import resource
73 import types
72 import types
74 import pty
73 import pty
75 import tty
74 import tty
76 import termios
75 import termios
77 import fcntl
76 import fcntl
78 import errno
77 import errno
79 import traceback
78 import traceback
80 import signal
79 import signal
81 except ImportError, e:
80 except ImportError, e:
82 raise ImportError (str(e) + """
81 raise ImportError (str(e) + """
83
82
84 A critical module was not found. Probably this operating system does not
83 A critical module was not found. Probably this operating system does not
85 support it. Pexpect is intended for UNIX-like operating systems.""")
84 support it. Pexpect is intended for UNIX-like operating systems.""")
86
85
87 __version__ = '2.3'
86 __version__ = '2.3'
88 __revision__ = '$Revision: 399 $'
87 __revision__ = '$Revision: 399 $'
89 __all__ = ['ExceptionPexpect', 'EOF', 'TIMEOUT', 'spawn', 'run', 'which',
88 __all__ = ['ExceptionPexpect', 'EOF', 'TIMEOUT', 'spawn', 'run', 'which',
90 'split_command_line', '__version__', '__revision__']
89 'split_command_line', '__version__', '__revision__']
91
90
92 # Exception classes used by this module.
91 # Exception classes used by this module.
93 class ExceptionPexpect(Exception):
92 class ExceptionPexpect(Exception):
94
93
95 """Base class for all exceptions raised by this module.
94 """Base class for all exceptions raised by this module.
96 """
95 """
97
96
98 def __init__(self, value):
97 def __init__(self, value):
99
98
100 self.value = value
99 self.value = value
101
100
102 def __str__(self):
101 def __str__(self):
103
102
104 return str(self.value)
103 return str(self.value)
105
104
106 def get_trace(self):
105 def get_trace(self):
107
106
108 """This returns an abbreviated stack trace with lines that only concern
107 """This returns an abbreviated stack trace with lines that only concern
109 the caller. In other words, the stack trace inside the Pexpect module
108 the caller. In other words, the stack trace inside the Pexpect module
110 is not included. """
109 is not included. """
111
110
112 tblist = traceback.extract_tb(sys.exc_info()[2])
111 tblist = traceback.extract_tb(sys.exc_info()[2])
113 #tblist = filter(self.__filter_not_pexpect, tblist)
112 #tblist = filter(self.__filter_not_pexpect, tblist)
114 tblist = [item for item in tblist if self.__filter_not_pexpect(item)]
113 tblist = [item for item in tblist if self.__filter_not_pexpect(item)]
115 tblist = traceback.format_list(tblist)
114 tblist = traceback.format_list(tblist)
116 return ''.join(tblist)
115 return ''.join(tblist)
117
116
118 def __filter_not_pexpect(self, trace_list_item):
117 def __filter_not_pexpect(self, trace_list_item):
119
118
120 """This returns True if list item 0 the string 'pexpect.py' in it. """
119 """This returns True if list item 0 the string 'pexpect.py' in it. """
121
120
122 if trace_list_item[0].find('pexpect.py') == -1:
121 if trace_list_item[0].find('pexpect.py') == -1:
123 return True
122 return True
124 else:
123 else:
125 return False
124 return False
126
125
127 class EOF(ExceptionPexpect):
126 class EOF(ExceptionPexpect):
128
127
129 """Raised when EOF is read from a child. This usually means the child has exited."""
128 """Raised when EOF is read from a child. This usually means the child has exited."""
130
129
131 class TIMEOUT(ExceptionPexpect):
130 class TIMEOUT(ExceptionPexpect):
132
131
133 """Raised when a read time exceeds the timeout. """
132 """Raised when a read time exceeds the timeout. """
134
133
135 ##class TIMEOUT_PATTERN(TIMEOUT):
134 ##class TIMEOUT_PATTERN(TIMEOUT):
136 ## """Raised when the pattern match time exceeds the timeout.
135 ## """Raised when the pattern match time exceeds the timeout.
137 ## This is different than a read TIMEOUT because the child process may
136 ## This is different than a read TIMEOUT because the child process may
138 ## give output, thus never give a TIMEOUT, but the output
137 ## give output, thus never give a TIMEOUT, but the output
139 ## may never match a pattern.
138 ## may never match a pattern.
140 ## """
139 ## """
141 ##class MAXBUFFER(ExceptionPexpect):
140 ##class MAXBUFFER(ExceptionPexpect):
142 ## """Raised when a scan buffer fills before matching an expected pattern."""
141 ## """Raised when a scan buffer fills before matching an expected pattern."""
143
142
144 def run (command, timeout=-1, withexitstatus=False, events=None, extra_args=None, logfile=None, cwd=None, env=None):
143 def run (command, timeout=-1, withexitstatus=False, events=None, extra_args=None, logfile=None, cwd=None, env=None):
145
144
146 """
145 """
147 This function runs the given command; waits for it to finish; then
146 This function runs the given command; waits for it to finish; then
148 returns all output as a string. STDERR is included in output. If the full
147 returns all output as a string. STDERR is included in output. If the full
149 path to the command is not given then the path is searched.
148 path to the command is not given then the path is searched.
150
149
151 Note that lines are terminated by CR/LF (\\r\\n) combination even on
150 Note that lines are terminated by CR/LF (\\r\\n) combination even on
152 UNIX-like systems because this is the standard for pseudo ttys. If you set
151 UNIX-like systems because this is the standard for pseudo ttys. If you set
153 'withexitstatus' to true, then run will return a tuple of (command_output,
152 'withexitstatus' to true, then run will return a tuple of (command_output,
154 exitstatus). If 'withexitstatus' is false then this returns just
153 exitstatus). If 'withexitstatus' is false then this returns just
155 command_output.
154 command_output.
156
155
157 The run() function can often be used instead of creating a spawn instance.
156 The run() function can often be used instead of creating a spawn instance.
158 For example, the following code uses spawn::
157 For example, the following code uses spawn::
159
158
160 from pexpect import *
159 from pexpect import *
161 child = spawn('scp foo myname@host.example.com:.')
160 child = spawn('scp foo myname@host.example.com:.')
162 child.expect ('(?i)password')
161 child.expect ('(?i)password')
163 child.sendline (mypassword)
162 child.sendline (mypassword)
164
163
165 The previous code can be replace with the following::
164 The previous code can be replace with the following::
166
165
167 from pexpect import *
166 from pexpect import *
168 run ('scp foo myname@host.example.com:.', events={'(?i)password': mypassword})
167 run ('scp foo myname@host.example.com:.', events={'(?i)password': mypassword})
169
168
170 Examples
169 Examples
171 ========
170 ========
172
171
173 Start the apache daemon on the local machine::
172 Start the apache daemon on the local machine::
174
173
175 from pexpect import *
174 from pexpect import *
176 run ("/usr/local/apache/bin/apachectl start")
175 run ("/usr/local/apache/bin/apachectl start")
177
176
178 Check in a file using SVN::
177 Check in a file using SVN::
179
178
180 from pexpect import *
179 from pexpect import *
181 run ("svn ci -m 'automatic commit' my_file.py")
180 run ("svn ci -m 'automatic commit' my_file.py")
182
181
183 Run a command and capture exit status::
182 Run a command and capture exit status::
184
183
185 from pexpect import *
184 from pexpect import *
186 (command_output, exitstatus) = run ('ls -l /bin', withexitstatus=1)
185 (command_output, exitstatus) = run ('ls -l /bin', withexitstatus=1)
187
186
188 Tricky Examples
187 Tricky Examples
189 ===============
188 ===============
190
189
191 The following will run SSH and execute 'ls -l' on the remote machine. The
190 The following will run SSH and execute 'ls -l' on the remote machine. The
192 password 'secret' will be sent if the '(?i)password' pattern is ever seen::
191 password 'secret' will be sent if the '(?i)password' pattern is ever seen::
193
192
194 run ("ssh username@machine.example.com 'ls -l'", events={'(?i)password':'secret\\n'})
193 run ("ssh username@machine.example.com 'ls -l'", events={'(?i)password':'secret\\n'})
195
194
196 This will start mencoder to rip a video from DVD. This will also display
195 This will start mencoder to rip a video from DVD. This will also display
197 progress ticks every 5 seconds as it runs. For example::
196 progress ticks every 5 seconds as it runs. For example::
198
197
199 from pexpect import *
198 from pexpect import *
200 def print_ticks(d):
199 def print_ticks(d):
201 print d['event_count'],
200 print d['event_count'],
202 run ("mencoder dvd://1 -o video.avi -oac copy -ovc copy", events={TIMEOUT:print_ticks}, timeout=5)
201 run ("mencoder dvd://1 -o video.avi -oac copy -ovc copy", events={TIMEOUT:print_ticks}, timeout=5)
203
202
204 The 'events' argument should be a dictionary of patterns and responses.
203 The 'events' argument should be a dictionary of patterns and responses.
205 Whenever one of the patterns is seen in the command out run() will send the
204 Whenever one of the patterns is seen in the command out run() will send the
206 associated response string. Note that you should put newlines in your
205 associated response string. Note that you should put newlines in your
207 string if Enter is necessary. The responses may also contain callback
206 string if Enter is necessary. The responses may also contain callback
208 functions. Any callback is function that takes a dictionary as an argument.
207 functions. Any callback is function that takes a dictionary as an argument.
209 The dictionary contains all the locals from the run() function, so you can
208 The dictionary contains all the locals from the run() function, so you can
210 access the child spawn object or any other variable defined in run()
209 access the child spawn object or any other variable defined in run()
211 (event_count, child, and extra_args are the most useful). A callback may
210 (event_count, child, and extra_args are the most useful). A callback may
212 return True to stop the current run process otherwise run() continues until
211 return True to stop the current run process otherwise run() continues until
213 the next event. A callback may also return a string which will be sent to
212 the next event. A callback may also return a string which will be sent to
214 the child. 'extra_args' is not used by directly run(). It provides a way to
213 the child. 'extra_args' is not used by directly run(). It provides a way to
215 pass data to a callback function through run() through the locals
214 pass data to a callback function through run() through the locals
216 dictionary passed to a callback. """
215 dictionary passed to a callback. """
217
216
218 if timeout == -1:
217 if timeout == -1:
219 child = spawn(command, maxread=2000, logfile=logfile, cwd=cwd, env=env)
218 child = spawn(command, maxread=2000, logfile=logfile, cwd=cwd, env=env)
220 else:
219 else:
221 child = spawn(command, timeout=timeout, maxread=2000, logfile=logfile, cwd=cwd, env=env)
220 child = spawn(command, timeout=timeout, maxread=2000, logfile=logfile, cwd=cwd, env=env)
222 if events is not None:
221 if events is not None:
223 patterns = events.keys()
222 patterns = events.keys()
224 responses = events.values()
223 responses = events.values()
225 else:
224 else:
226 patterns=None # We assume that EOF or TIMEOUT will save us.
225 patterns=None # We assume that EOF or TIMEOUT will save us.
227 responses=None
226 responses=None
228 child_result_list = []
227 child_result_list = []
229 event_count = 0
228 event_count = 0
230 while 1:
229 while 1:
231 try:
230 try:
232 index = child.expect (patterns)
231 index = child.expect (patterns)
233 if type(child.after) in types.StringTypes:
232 if type(child.after) in types.StringTypes:
234 child_result_list.append(child.before + child.after)
233 child_result_list.append(child.before + child.after)
235 else: # child.after may have been a TIMEOUT or EOF, so don't cat those.
234 else: # child.after may have been a TIMEOUT or EOF, so don't cat those.
236 child_result_list.append(child.before)
235 child_result_list.append(child.before)
237 if type(responses[index]) in types.StringTypes:
236 if type(responses[index]) in types.StringTypes:
238 child.send(responses[index])
237 child.send(responses[index])
239 elif type(responses[index]) is types.FunctionType:
238 elif type(responses[index]) is types.FunctionType:
240 callback_result = responses[index](locals())
239 callback_result = responses[index](locals())
241 sys.stdout.flush()
240 sys.stdout.flush()
242 if type(callback_result) in types.StringTypes:
241 if type(callback_result) in types.StringTypes:
243 child.send(callback_result)
242 child.send(callback_result)
244 elif callback_result:
243 elif callback_result:
245 break
244 break
246 else:
245 else:
247 raise TypeError ('The callback must be a string or function type.')
246 raise TypeError ('The callback must be a string or function type.')
248 event_count = event_count + 1
247 event_count = event_count + 1
249 except TIMEOUT, e:
248 except TIMEOUT, e:
250 child_result_list.append(child.before)
249 child_result_list.append(child.before)
251 break
250 break
252 except EOF, e:
251 except EOF, e:
253 child_result_list.append(child.before)
252 child_result_list.append(child.before)
254 break
253 break
255 child_result = ''.join(child_result_list)
254 child_result = ''.join(child_result_list)
256 if withexitstatus:
255 if withexitstatus:
257 child.close()
256 child.close()
258 return (child_result, child.exitstatus)
257 return (child_result, child.exitstatus)
259 else:
258 else:
260 return child_result
259 return child_result
261
260
262 class spawn (object):
261 class spawn (object):
263
262
264 """This is the main class interface for Pexpect. Use this class to start
263 """This is the main class interface for Pexpect. Use this class to start
265 and control child applications. """
264 and control child applications. """
266
265
267 def __init__(self, command, args=[], timeout=30, maxread=2000, searchwindowsize=None, logfile=None, cwd=None, env=None):
266 def __init__(self, command, args=[], timeout=30, maxread=2000, searchwindowsize=None, logfile=None, cwd=None, env=None):
268
267
269 """This is the constructor. The command parameter may be a string that
268 """This is the constructor. The command parameter may be a string that
270 includes a command and any arguments to the command. For example::
269 includes a command and any arguments to the command. For example::
271
270
272 child = pexpect.spawn ('/usr/bin/ftp')
271 child = pexpect.spawn ('/usr/bin/ftp')
273 child = pexpect.spawn ('/usr/bin/ssh user@example.com')
272 child = pexpect.spawn ('/usr/bin/ssh user@example.com')
274 child = pexpect.spawn ('ls -latr /tmp')
273 child = pexpect.spawn ('ls -latr /tmp')
275
274
276 You may also construct it with a list of arguments like so::
275 You may also construct it with a list of arguments like so::
277
276
278 child = pexpect.spawn ('/usr/bin/ftp', [])
277 child = pexpect.spawn ('/usr/bin/ftp', [])
279 child = pexpect.spawn ('/usr/bin/ssh', ['user@example.com'])
278 child = pexpect.spawn ('/usr/bin/ssh', ['user@example.com'])
280 child = pexpect.spawn ('ls', ['-latr', '/tmp'])
279 child = pexpect.spawn ('ls', ['-latr', '/tmp'])
281
280
282 After this the child application will be created and will be ready to
281 After this the child application will be created and will be ready to
283 talk to. For normal use, see expect() and send() and sendline().
282 talk to. For normal use, see expect() and send() and sendline().
284
283
285 Remember that Pexpect does NOT interpret shell meta characters such as
284 Remember that Pexpect does NOT interpret shell meta characters such as
286 redirect, pipe, or wild cards (>, |, or *). This is a common mistake.
285 redirect, pipe, or wild cards (>, |, or *). This is a common mistake.
287 If you want to run a command and pipe it through another command then
286 If you want to run a command and pipe it through another command then
288 you must also start a shell. For example::
287 you must also start a shell. For example::
289
288
290 child = pexpect.spawn('/bin/bash -c "ls -l | grep LOG > log_list.txt"')
289 child = pexpect.spawn('/bin/bash -c "ls -l | grep LOG > log_list.txt"')
291 child.expect(pexpect.EOF)
290 child.expect(pexpect.EOF)
292
291
293 The second form of spawn (where you pass a list of arguments) is useful
292 The second form of spawn (where you pass a list of arguments) is useful
294 in situations where you wish to spawn a command and pass it its own
293 in situations where you wish to spawn a command and pass it its own
295 argument list. This can make syntax more clear. For example, the
294 argument list. This can make syntax more clear. For example, the
296 following is equivalent to the previous example::
295 following is equivalent to the previous example::
297
296
298 shell_cmd = 'ls -l | grep LOG > log_list.txt'
297 shell_cmd = 'ls -l | grep LOG > log_list.txt'
299 child = pexpect.spawn('/bin/bash', ['-c', shell_cmd])
298 child = pexpect.spawn('/bin/bash', ['-c', shell_cmd])
300 child.expect(pexpect.EOF)
299 child.expect(pexpect.EOF)
301
300
302 The maxread attribute sets the read buffer size. This is maximum number
301 The maxread attribute sets the read buffer size. This is maximum number
303 of bytes that Pexpect will try to read from a TTY at one time. Setting
302 of bytes that Pexpect will try to read from a TTY at one time. Setting
304 the maxread size to 1 will turn off buffering. Setting the maxread
303 the maxread size to 1 will turn off buffering. Setting the maxread
305 value higher may help performance in cases where large amounts of
304 value higher may help performance in cases where large amounts of
306 output are read back from the child. This feature is useful in
305 output are read back from the child. This feature is useful in
307 conjunction with searchwindowsize.
306 conjunction with searchwindowsize.
308
307
309 The searchwindowsize attribute sets the how far back in the incomming
308 The searchwindowsize attribute sets the how far back in the incomming
310 seach buffer Pexpect will search for pattern matches. Every time
309 seach buffer Pexpect will search for pattern matches. Every time
311 Pexpect reads some data from the child it will append the data to the
310 Pexpect reads some data from the child it will append the data to the
312 incomming buffer. The default is to search from the beginning of the
311 incomming buffer. The default is to search from the beginning of the
313 imcomming buffer each time new data is read from the child. But this is
312 imcomming buffer each time new data is read from the child. But this is
314 very inefficient if you are running a command that generates a large
313 very inefficient if you are running a command that generates a large
315 amount of data where you want to match The searchwindowsize does not
314 amount of data where you want to match The searchwindowsize does not
316 effect the size of the incomming data buffer. You will still have
315 effect the size of the incomming data buffer. You will still have
317 access to the full buffer after expect() returns.
316 access to the full buffer after expect() returns.
318
317
319 The logfile member turns on or off logging. All input and output will
318 The logfile member turns on or off logging. All input and output will
320 be copied to the given file object. Set logfile to None to stop
319 be copied to the given file object. Set logfile to None to stop
321 logging. This is the default. Set logfile to sys.stdout to echo
320 logging. This is the default. Set logfile to sys.stdout to echo
322 everything to standard output. The logfile is flushed after each write.
321 everything to standard output. The logfile is flushed after each write.
323
322
324 Example log input and output to a file::
323 Example log input and output to a file::
325
324
326 child = pexpect.spawn('some_command')
325 child = pexpect.spawn('some_command')
327 fout = file('mylog.txt','w')
326 fout = file('mylog.txt','w')
328 child.logfile = fout
327 child.logfile = fout
329
328
330 Example log to stdout::
329 Example log to stdout::
331
330
332 child = pexpect.spawn('some_command')
331 child = pexpect.spawn('some_command')
333 child.logfile = sys.stdout
332 child.logfile = sys.stdout
334
333
335 The logfile_read and logfile_send members can be used to separately log
334 The logfile_read and logfile_send members can be used to separately log
336 the input from the child and output sent to the child. Sometimes you
335 the input from the child and output sent to the child. Sometimes you
337 don't want to see everything you write to the child. You only want to
336 don't want to see everything you write to the child. You only want to
338 log what the child sends back. For example::
337 log what the child sends back. For example::
339
338
340 child = pexpect.spawn('some_command')
339 child = pexpect.spawn('some_command')
341 child.logfile_read = sys.stdout
340 child.logfile_read = sys.stdout
342
341
343 To separately log output sent to the child use logfile_send::
342 To separately log output sent to the child use logfile_send::
344
343
345 self.logfile_send = fout
344 self.logfile_send = fout
346
345
347 The delaybeforesend helps overcome a weird behavior that many users
346 The delaybeforesend helps overcome a weird behavior that many users
348 were experiencing. The typical problem was that a user would expect() a
347 were experiencing. The typical problem was that a user would expect() a
349 "Password:" prompt and then immediately call sendline() to send the
348 "Password:" prompt and then immediately call sendline() to send the
350 password. The user would then see that their password was echoed back
349 password. The user would then see that their password was echoed back
351 to them. Passwords don't normally echo. The problem is caused by the
350 to them. Passwords don't normally echo. The problem is caused by the
352 fact that most applications print out the "Password" prompt and then
351 fact that most applications print out the "Password" prompt and then
353 turn off stdin echo, but if you send your password before the
352 turn off stdin echo, but if you send your password before the
354 application turned off echo, then you get your password echoed.
353 application turned off echo, then you get your password echoed.
355 Normally this wouldn't be a problem when interacting with a human at a
354 Normally this wouldn't be a problem when interacting with a human at a
356 real keyboard. If you introduce a slight delay just before writing then
355 real keyboard. If you introduce a slight delay just before writing then
357 this seems to clear up the problem. This was such a common problem for
356 this seems to clear up the problem. This was such a common problem for
358 many users that I decided that the default pexpect behavior should be
357 many users that I decided that the default pexpect behavior should be
359 to sleep just before writing to the child application. 1/20th of a
358 to sleep just before writing to the child application. 1/20th of a
360 second (50 ms) seems to be enough to clear up the problem. You can set
359 second (50 ms) seems to be enough to clear up the problem. You can set
361 delaybeforesend to 0 to return to the old behavior. Most Linux machines
360 delaybeforesend to 0 to return to the old behavior. Most Linux machines
362 don't like this to be below 0.03. I don't know why.
361 don't like this to be below 0.03. I don't know why.
363
362
364 Note that spawn is clever about finding commands on your path.
363 Note that spawn is clever about finding commands on your path.
365 It uses the same logic that "which" uses to find executables.
364 It uses the same logic that "which" uses to find executables.
366
365
367 If you wish to get the exit status of the child you must call the
366 If you wish to get the exit status of the child you must call the
368 close() method. The exit or signal status of the child will be stored
367 close() method. The exit or signal status of the child will be stored
369 in self.exitstatus or self.signalstatus. If the child exited normally
368 in self.exitstatus or self.signalstatus. If the child exited normally
370 then exitstatus will store the exit return code and signalstatus will
369 then exitstatus will store the exit return code and signalstatus will
371 be None. If the child was terminated abnormally with a signal then
370 be None. If the child was terminated abnormally with a signal then
372 signalstatus will store the signal value and exitstatus will be None.
371 signalstatus will store the signal value and exitstatus will be None.
373 If you need more detail you can also read the self.status member which
372 If you need more detail you can also read the self.status member which
374 stores the status returned by os.waitpid. You can interpret this using
373 stores the status returned by os.waitpid. You can interpret this using
375 os.WIFEXITED/os.WEXITSTATUS or os.WIFSIGNALED/os.TERMSIG. """
374 os.WIFEXITED/os.WEXITSTATUS or os.WIFSIGNALED/os.TERMSIG. """
376
375
377 self.STDIN_FILENO = pty.STDIN_FILENO
376 self.STDIN_FILENO = pty.STDIN_FILENO
378 self.STDOUT_FILENO = pty.STDOUT_FILENO
377 self.STDOUT_FILENO = pty.STDOUT_FILENO
379 self.STDERR_FILENO = pty.STDERR_FILENO
378 self.STDERR_FILENO = pty.STDERR_FILENO
380 self.stdin = sys.stdin
379 self.stdin = sys.stdin
381 self.stdout = sys.stdout
380 self.stdout = sys.stdout
382 self.stderr = sys.stderr
381 self.stderr = sys.stderr
383
382
384 self.searcher = None
383 self.searcher = None
385 self.ignorecase = False
384 self.ignorecase = False
386 self.before = None
385 self.before = None
387 self.after = None
386 self.after = None
388 self.match = None
387 self.match = None
389 self.match_index = None
388 self.match_index = None
390 self.terminated = True
389 self.terminated = True
391 self.exitstatus = None
390 self.exitstatus = None
392 self.signalstatus = None
391 self.signalstatus = None
393 self.status = None # status returned by os.waitpid
392 self.status = None # status returned by os.waitpid
394 self.flag_eof = False
393 self.flag_eof = False
395 self.pid = None
394 self.pid = None
396 self.child_fd = -1 # initially closed
395 self.child_fd = -1 # initially closed
397 self.timeout = timeout
396 self.timeout = timeout
398 self.delimiter = EOF
397 self.delimiter = EOF
399 self.logfile = logfile
398 self.logfile = logfile
400 self.logfile_read = None # input from child (read_nonblocking)
399 self.logfile_read = None # input from child (read_nonblocking)
401 self.logfile_send = None # output to send (send, sendline)
400 self.logfile_send = None # output to send (send, sendline)
402 self.maxread = maxread # max bytes to read at one time into buffer
401 self.maxread = maxread # max bytes to read at one time into buffer
403 self.buffer = '' # This is the read buffer. See maxread.
402 self.buffer = '' # This is the read buffer. See maxread.
404 self.searchwindowsize = searchwindowsize # Anything before searchwindowsize point is preserved, but not searched.
403 self.searchwindowsize = searchwindowsize # Anything before searchwindowsize point is preserved, but not searched.
405 # Most Linux machines don't like delaybeforesend to be below 0.03 (30 ms).
404 # Most Linux machines don't like delaybeforesend to be below 0.03 (30 ms).
406 self.delaybeforesend = 0.05 # Sets sleep time used just before sending data to child. Time in seconds.
405 self.delaybeforesend = 0.05 # Sets sleep time used just before sending data to child. Time in seconds.
407 self.delayafterclose = 0.1 # Sets delay in close() method to allow kernel time to update process status. Time in seconds.
406 self.delayafterclose = 0.1 # Sets delay in close() method to allow kernel time to update process status. Time in seconds.
408 self.delayafterterminate = 0.1 # Sets delay in terminate() method to allow kernel time to update process status. Time in seconds.
407 self.delayafterterminate = 0.1 # Sets delay in terminate() method to allow kernel time to update process status. Time in seconds.
409 self.softspace = False # File-like object.
408 self.softspace = False # File-like object.
410 self.name = '<' + repr(self) + '>' # File-like object.
409 self.name = '<' + repr(self) + '>' # File-like object.
411 self.encoding = None # File-like object.
410 self.encoding = None # File-like object.
412 self.closed = True # File-like object.
411 self.closed = True # File-like object.
413 self.cwd = cwd
412 self.cwd = cwd
414 self.env = env
413 self.env = env
415 self.__irix_hack = (sys.platform.lower().find('irix')>=0) # This flags if we are running on irix
414 self.__irix_hack = (sys.platform.lower().find('irix')>=0) # This flags if we are running on irix
416 # Solaris uses internal __fork_pty(). All others use pty.fork().
415 # Solaris uses internal __fork_pty(). All others use pty.fork().
417 if (sys.platform.lower().find('solaris')>=0) or (sys.platform.lower().find('sunos5')>=0):
416 if (sys.platform.lower().find('solaris')>=0) or (sys.platform.lower().find('sunos5')>=0):
418 self.use_native_pty_fork = False
417 self.use_native_pty_fork = False
419 else:
418 else:
420 self.use_native_pty_fork = True
419 self.use_native_pty_fork = True
421
420
422
421
423 # allow dummy instances for subclasses that may not use command or args.
422 # allow dummy instances for subclasses that may not use command or args.
424 if command is None:
423 if command is None:
425 self.command = None
424 self.command = None
426 self.args = None
425 self.args = None
427 self.name = '<pexpect factory incomplete>'
426 self.name = '<pexpect factory incomplete>'
428 else:
427 else:
429 self._spawn (command, args)
428 self._spawn (command, args)
430
429
431 def __del__(self):
430 def __del__(self):
432
431
433 """This makes sure that no system resources are left open. Python only
432 """This makes sure that no system resources are left open. Python only
434 garbage collects Python objects. OS file descriptors are not Python
433 garbage collects Python objects. OS file descriptors are not Python
435 objects, so they must be handled explicitly. If the child file
434 objects, so they must be handled explicitly. If the child file
436 descriptor was opened outside of this class (passed to the constructor)
435 descriptor was opened outside of this class (passed to the constructor)
437 then this does not close it. """
436 then this does not close it. """
438
437
439 if not self.closed:
438 if not self.closed:
440 # It is possible for __del__ methods to execute during the
439 # It is possible for __del__ methods to execute during the
441 # teardown of the Python VM itself. Thus self.close() may
440 # teardown of the Python VM itself. Thus self.close() may
442 # trigger an exception because os.close may be None.
441 # trigger an exception because os.close may be None.
443 # -- Fernando Perez
442 # -- Fernando Perez
444 try:
443 try:
445 self.close()
444 self.close()
446 except AttributeError:
445 except AttributeError:
447 pass
446 pass
448
447
449 def __str__(self):
448 def __str__(self):
450
449
451 """This returns a human-readable string that represents the state of
450 """This returns a human-readable string that represents the state of
452 the object. """
451 the object. """
453
452
454 s = []
453 s = []
455 s.append(repr(self))
454 s.append(repr(self))
456 s.append('version: ' + __version__ + ' (' + __revision__ + ')')
455 s.append('version: ' + __version__ + ' (' + __revision__ + ')')
457 s.append('command: ' + str(self.command))
456 s.append('command: ' + str(self.command))
458 s.append('args: ' + str(self.args))
457 s.append('args: ' + str(self.args))
459 s.append('searcher: ' + str(self.searcher))
458 s.append('searcher: ' + str(self.searcher))
460 s.append('buffer (last 100 chars): ' + str(self.buffer)[-100:])
459 s.append('buffer (last 100 chars): ' + str(self.buffer)[-100:])
461 s.append('before (last 100 chars): ' + str(self.before)[-100:])
460 s.append('before (last 100 chars): ' + str(self.before)[-100:])
462 s.append('after: ' + str(self.after))
461 s.append('after: ' + str(self.after))
463 s.append('match: ' + str(self.match))
462 s.append('match: ' + str(self.match))
464 s.append('match_index: ' + str(self.match_index))
463 s.append('match_index: ' + str(self.match_index))
465 s.append('exitstatus: ' + str(self.exitstatus))
464 s.append('exitstatus: ' + str(self.exitstatus))
466 s.append('flag_eof: ' + str(self.flag_eof))
465 s.append('flag_eof: ' + str(self.flag_eof))
467 s.append('pid: ' + str(self.pid))
466 s.append('pid: ' + str(self.pid))
468 s.append('child_fd: ' + str(self.child_fd))
467 s.append('child_fd: ' + str(self.child_fd))
469 s.append('closed: ' + str(self.closed))
468 s.append('closed: ' + str(self.closed))
470 s.append('timeout: ' + str(self.timeout))
469 s.append('timeout: ' + str(self.timeout))
471 s.append('delimiter: ' + str(self.delimiter))
470 s.append('delimiter: ' + str(self.delimiter))
472 s.append('logfile: ' + str(self.logfile))
471 s.append('logfile: ' + str(self.logfile))
473 s.append('logfile_read: ' + str(self.logfile_read))
472 s.append('logfile_read: ' + str(self.logfile_read))
474 s.append('logfile_send: ' + str(self.logfile_send))
473 s.append('logfile_send: ' + str(self.logfile_send))
475 s.append('maxread: ' + str(self.maxread))
474 s.append('maxread: ' + str(self.maxread))
476 s.append('ignorecase: ' + str(self.ignorecase))
475 s.append('ignorecase: ' + str(self.ignorecase))
477 s.append('searchwindowsize: ' + str(self.searchwindowsize))
476 s.append('searchwindowsize: ' + str(self.searchwindowsize))
478 s.append('delaybeforesend: ' + str(self.delaybeforesend))
477 s.append('delaybeforesend: ' + str(self.delaybeforesend))
479 s.append('delayafterclose: ' + str(self.delayafterclose))
478 s.append('delayafterclose: ' + str(self.delayafterclose))
480 s.append('delayafterterminate: ' + str(self.delayafterterminate))
479 s.append('delayafterterminate: ' + str(self.delayafterterminate))
481 return '\n'.join(s)
480 return '\n'.join(s)
482
481
483 def _spawn(self,command,args=[]):
482 def _spawn(self,command,args=[]):
484
483
485 """This starts the given command in a child process. This does all the
484 """This starts the given command in a child process. This does all the
486 fork/exec type of stuff for a pty. This is called by __init__. If args
485 fork/exec type of stuff for a pty. This is called by __init__. If args
487 is empty then command will be parsed (split on spaces) and args will be
486 is empty then command will be parsed (split on spaces) and args will be
488 set to parsed arguments. """
487 set to parsed arguments. """
489
488
490 # The pid and child_fd of this object get set by this method.
489 # The pid and child_fd of this object get set by this method.
491 # Note that it is difficult for this method to fail.
490 # Note that it is difficult for this method to fail.
492 # You cannot detect if the child process cannot start.
491 # You cannot detect if the child process cannot start.
493 # So the only way you can tell if the child process started
492 # So the only way you can tell if the child process started
494 # or not is to try to read from the file descriptor. If you get
493 # or not is to try to read from the file descriptor. If you get
495 # EOF immediately then it means that the child is already dead.
494 # EOF immediately then it means that the child is already dead.
496 # That may not necessarily be bad because you may haved spawned a child
495 # That may not necessarily be bad because you may haved spawned a child
497 # that performs some task; creates no stdout output; and then dies.
496 # that performs some task; creates no stdout output; and then dies.
498
497
499 # If command is an int type then it may represent a file descriptor.
498 # If command is an int type then it may represent a file descriptor.
500 if type(command) == type(0):
499 if type(command) == type(0):
501 raise ExceptionPexpect ('Command is an int type. If this is a file descriptor then maybe you want to use fdpexpect.fdspawn which takes an existing file descriptor instead of a command string.')
500 raise ExceptionPexpect ('Command is an int type. If this is a file descriptor then maybe you want to use fdpexpect.fdspawn which takes an existing file descriptor instead of a command string.')
502
501
503 if type (args) != type([]):
502 if type (args) != type([]):
504 raise TypeError ('The argument, args, must be a list.')
503 raise TypeError ('The argument, args, must be a list.')
505
504
506 if args == []:
505 if args == []:
507 self.args = split_command_line(command)
506 self.args = split_command_line(command)
508 self.command = self.args[0]
507 self.command = self.args[0]
509 else:
508 else:
510 self.args = args[:] # work with a copy
509 self.args = args[:] # work with a copy
511 self.args.insert (0, command)
510 self.args.insert (0, command)
512 self.command = command
511 self.command = command
513
512
514 command_with_path = which(self.command)
513 command_with_path = which(self.command)
515 if command_with_path is None:
514 if command_with_path is None:
516 raise ExceptionPexpect ('The command was not found or was not executable: %s.' % self.command)
515 raise ExceptionPexpect ('The command was not found or was not executable: %s.' % self.command)
517 self.command = command_with_path
516 self.command = command_with_path
518 self.args[0] = self.command
517 self.args[0] = self.command
519
518
520 self.name = '<' + ' '.join (self.args) + '>'
519 self.name = '<' + ' '.join (self.args) + '>'
521
520
522 assert self.pid is None, 'The pid member should be None.'
521 assert self.pid is None, 'The pid member should be None.'
523 assert self.command is not None, 'The command member should not be None.'
522 assert self.command is not None, 'The command member should not be None.'
524
523
525 if self.use_native_pty_fork:
524 if self.use_native_pty_fork:
526 try:
525 try:
527 self.pid, self.child_fd = pty.fork()
526 self.pid, self.child_fd = pty.fork()
528 except OSError, e:
527 except OSError, e:
529 raise ExceptionPexpect('Error! pty.fork() failed: ' + str(e))
528 raise ExceptionPexpect('Error! pty.fork() failed: ' + str(e))
530 else: # Use internal __fork_pty
529 else: # Use internal __fork_pty
531 self.pid, self.child_fd = self.__fork_pty()
530 self.pid, self.child_fd = self.__fork_pty()
532
531
533 if self.pid == 0: # Child
532 if self.pid == 0: # Child
534 try:
533 try:
535 self.child_fd = sys.stdout.fileno() # used by setwinsize()
534 self.child_fd = sys.stdout.fileno() # used by setwinsize()
536 self.setwinsize(24, 80)
535 self.setwinsize(24, 80)
537 except:
536 except:
538 # Some platforms do not like setwinsize (Cygwin).
537 # Some platforms do not like setwinsize (Cygwin).
539 # This will cause problem when running applications that
538 # This will cause problem when running applications that
540 # are very picky about window size.
539 # are very picky about window size.
541 # This is a serious limitation, but not a show stopper.
540 # This is a serious limitation, but not a show stopper.
542 pass
541 pass
543 # Do not allow child to inherit open file descriptors from parent.
542 # Do not allow child to inherit open file descriptors from parent.
544 max_fd = resource.getrlimit(resource.RLIMIT_NOFILE)[0]
543 max_fd = resource.getrlimit(resource.RLIMIT_NOFILE)[0]
545 for i in range (3, max_fd):
544 for i in range (3, max_fd):
546 try:
545 try:
547 os.close (i)
546 os.close (i)
548 except OSError:
547 except OSError:
549 pass
548 pass
550
549
551 # I don't know why this works, but ignoring SIGHUP fixes a
550 # I don't know why this works, but ignoring SIGHUP fixes a
552 # problem when trying to start a Java daemon with sudo
551 # problem when trying to start a Java daemon with sudo
553 # (specifically, Tomcat).
552 # (specifically, Tomcat).
554 signal.signal(signal.SIGHUP, signal.SIG_IGN)
553 signal.signal(signal.SIGHUP, signal.SIG_IGN)
555
554
556 if self.cwd is not None:
555 if self.cwd is not None:
557 os.chdir(self.cwd)
556 os.chdir(self.cwd)
558 if self.env is None:
557 if self.env is None:
559 os.execv(self.command, self.args)
558 os.execv(self.command, self.args)
560 else:
559 else:
561 os.execvpe(self.command, self.args, self.env)
560 os.execvpe(self.command, self.args, self.env)
562
561
563 # Parent
562 # Parent
564 self.terminated = False
563 self.terminated = False
565 self.closed = False
564 self.closed = False
566
565
567 def __fork_pty(self):
566 def __fork_pty(self):
568
567
569 """This implements a substitute for the forkpty system call. This
568 """This implements a substitute for the forkpty system call. This
570 should be more portable than the pty.fork() function. Specifically,
569 should be more portable than the pty.fork() function. Specifically,
571 this should work on Solaris.
570 this should work on Solaris.
572
571
573 Modified 10.06.05 by Geoff Marshall: Implemented __fork_pty() method to
572 Modified 10.06.05 by Geoff Marshall: Implemented __fork_pty() method to
574 resolve the issue with Python's pty.fork() not supporting Solaris,
573 resolve the issue with Python's pty.fork() not supporting Solaris,
575 particularly ssh. Based on patch to posixmodule.c authored by Noah
574 particularly ssh. Based on patch to posixmodule.c authored by Noah
576 Spurrier::
575 Spurrier::
577
576
578 http://mail.python.org/pipermail/python-dev/2003-May/035281.html
577 http://mail.python.org/pipermail/python-dev/2003-May/035281.html
579
578
580 """
579 """
581
580
582 parent_fd, child_fd = os.openpty()
581 parent_fd, child_fd = os.openpty()
583 if parent_fd < 0 or child_fd < 0:
582 if parent_fd < 0 or child_fd < 0:
584 raise ExceptionPexpect, "Error! Could not open pty with os.openpty()."
583 raise ExceptionPexpect, "Error! Could not open pty with os.openpty()."
585
584
586 pid = os.fork()
585 pid = os.fork()
587 if pid < 0:
586 if pid < 0:
588 raise ExceptionPexpect, "Error! Failed os.fork()."
587 raise ExceptionPexpect, "Error! Failed os.fork()."
589 elif pid == 0:
588 elif pid == 0:
590 # Child.
589 # Child.
591 os.close(parent_fd)
590 os.close(parent_fd)
592 self.__pty_make_controlling_tty(child_fd)
591 self.__pty_make_controlling_tty(child_fd)
593
592
594 os.dup2(child_fd, 0)
593 os.dup2(child_fd, 0)
595 os.dup2(child_fd, 1)
594 os.dup2(child_fd, 1)
596 os.dup2(child_fd, 2)
595 os.dup2(child_fd, 2)
597
596
598 if child_fd > 2:
597 if child_fd > 2:
599 os.close(child_fd)
598 os.close(child_fd)
600 else:
599 else:
601 # Parent.
600 # Parent.
602 os.close(child_fd)
601 os.close(child_fd)
603
602
604 return pid, parent_fd
603 return pid, parent_fd
605
604
606 def __pty_make_controlling_tty(self, tty_fd):
605 def __pty_make_controlling_tty(self, tty_fd):
607
606
608 """This makes the pseudo-terminal the controlling tty. This should be
607 """This makes the pseudo-terminal the controlling tty. This should be
609 more portable than the pty.fork() function. Specifically, this should
608 more portable than the pty.fork() function. Specifically, this should
610 work on Solaris. """
609 work on Solaris. """
611
610
612 child_name = os.ttyname(tty_fd)
611 child_name = os.ttyname(tty_fd)
613
612
614 # Disconnect from controlling tty if still connected.
613 # Disconnect from controlling tty if still connected.
615 fd = os.open("/dev/tty", os.O_RDWR | os.O_NOCTTY);
614 fd = os.open("/dev/tty", os.O_RDWR | os.O_NOCTTY);
616 if fd >= 0:
615 if fd >= 0:
617 os.close(fd)
616 os.close(fd)
618
617
619 os.setsid()
618 os.setsid()
620
619
621 # Verify we are disconnected from controlling tty
620 # Verify we are disconnected from controlling tty
622 try:
621 try:
623 fd = os.open("/dev/tty", os.O_RDWR | os.O_NOCTTY);
622 fd = os.open("/dev/tty", os.O_RDWR | os.O_NOCTTY);
624 if fd >= 0:
623 if fd >= 0:
625 os.close(fd)
624 os.close(fd)
626 raise ExceptionPexpect, "Error! We are not disconnected from a controlling tty."
625 raise ExceptionPexpect, "Error! We are not disconnected from a controlling tty."
627 except:
626 except:
628 # Good! We are disconnected from a controlling tty.
627 # Good! We are disconnected from a controlling tty.
629 pass
628 pass
630
629
631 # Verify we can open child pty.
630 # Verify we can open child pty.
632 fd = os.open(child_name, os.O_RDWR);
631 fd = os.open(child_name, os.O_RDWR);
633 if fd < 0:
632 if fd < 0:
634 raise ExceptionPexpect, "Error! Could not open child pty, " + child_name
633 raise ExceptionPexpect, "Error! Could not open child pty, " + child_name
635 else:
634 else:
636 os.close(fd)
635 os.close(fd)
637
636
638 # Verify we now have a controlling tty.
637 # Verify we now have a controlling tty.
639 fd = os.open("/dev/tty", os.O_WRONLY)
638 fd = os.open("/dev/tty", os.O_WRONLY)
640 if fd < 0:
639 if fd < 0:
641 raise ExceptionPexpect, "Error! Could not open controlling tty, /dev/tty"
640 raise ExceptionPexpect, "Error! Could not open controlling tty, /dev/tty"
642 else:
641 else:
643 os.close(fd)
642 os.close(fd)
644
643
645 def fileno (self): # File-like object.
644 def fileno (self): # File-like object.
646
645
647 """This returns the file descriptor of the pty for the child.
646 """This returns the file descriptor of the pty for the child.
648 """
647 """
649
648
650 return self.child_fd
649 return self.child_fd
651
650
652 def close (self, force=True): # File-like object.
651 def close (self, force=True): # File-like object.
653
652
654 """This closes the connection with the child application. Note that
653 """This closes the connection with the child application. Note that
655 calling close() more than once is valid. This emulates standard Python
654 calling close() more than once is valid. This emulates standard Python
656 behavior with files. Set force to True if you want to make sure that
655 behavior with files. Set force to True if you want to make sure that
657 the child is terminated (SIGKILL is sent if the child ignores SIGHUP
656 the child is terminated (SIGKILL is sent if the child ignores SIGHUP
658 and SIGINT). """
657 and SIGINT). """
659
658
660 if not self.closed:
659 if not self.closed:
661 self.flush()
660 self.flush()
662 os.close (self.child_fd)
661 os.close (self.child_fd)
663 time.sleep(self.delayafterclose) # Give kernel time to update process status.
662 time.sleep(self.delayafterclose) # Give kernel time to update process status.
664 if self.isalive():
663 if self.isalive():
665 if not self.terminate(force):
664 if not self.terminate(force):
666 raise ExceptionPexpect ('close() could not terminate the child using terminate()')
665 raise ExceptionPexpect ('close() could not terminate the child using terminate()')
667 self.child_fd = -1
666 self.child_fd = -1
668 self.closed = True
667 self.closed = True
669 #self.pid = None
668 #self.pid = None
670
669
671 def flush (self): # File-like object.
670 def flush (self): # File-like object.
672
671
673 """This does nothing. It is here to support the interface for a
672 """This does nothing. It is here to support the interface for a
674 File-like object. """
673 File-like object. """
675
674
676 pass
675 pass
677
676
678 def isatty (self): # File-like object.
677 def isatty (self): # File-like object.
679
678
680 """This returns True if the file descriptor is open and connected to a
679 """This returns True if the file descriptor is open and connected to a
681 tty(-like) device, else False. """
680 tty(-like) device, else False. """
682
681
683 return os.isatty(self.child_fd)
682 return os.isatty(self.child_fd)
684
683
685 def waitnoecho (self, timeout=-1):
684 def waitnoecho (self, timeout=-1):
686
685
687 """This waits until the terminal ECHO flag is set False. This returns
686 """This waits until the terminal ECHO flag is set False. This returns
688 True if the echo mode is off. This returns False if the ECHO flag was
687 True if the echo mode is off. This returns False if the ECHO flag was
689 not set False before the timeout. This can be used to detect when the
688 not set False before the timeout. This can be used to detect when the
690 child is waiting for a password. Usually a child application will turn
689 child is waiting for a password. Usually a child application will turn
691 off echo mode when it is waiting for the user to enter a password. For
690 off echo mode when it is waiting for the user to enter a password. For
692 example, instead of expecting the "password:" prompt you can wait for
691 example, instead of expecting the "password:" prompt you can wait for
693 the child to set ECHO off::
692 the child to set ECHO off::
694
693
695 p = pexpect.spawn ('ssh user@example.com')
694 p = pexpect.spawn ('ssh user@example.com')
696 p.waitnoecho()
695 p.waitnoecho()
697 p.sendline(mypassword)
696 p.sendline(mypassword)
698
697
699 If timeout is None then this method to block forever until ECHO flag is
698 If timeout is None then this method to block forever until ECHO flag is
700 False.
699 False.
701
700
702 """
701 """
703
702
704 if timeout == -1:
703 if timeout == -1:
705 timeout = self.timeout
704 timeout = self.timeout
706 if timeout is not None:
705 if timeout is not None:
707 end_time = time.time() + timeout
706 end_time = time.time() + timeout
708 while True:
707 while True:
709 if not self.getecho():
708 if not self.getecho():
710 return True
709 return True
711 if timeout < 0 and timeout is not None:
710 if timeout < 0 and timeout is not None:
712 return False
711 return False
713 if timeout is not None:
712 if timeout is not None:
714 timeout = end_time - time.time()
713 timeout = end_time - time.time()
715 time.sleep(0.1)
714 time.sleep(0.1)
716
715
717 def getecho (self):
716 def getecho (self):
718
717
719 """This returns the terminal echo mode. This returns True if echo is
718 """This returns the terminal echo mode. This returns True if echo is
720 on or False if echo is off. Child applications that are expecting you
719 on or False if echo is off. Child applications that are expecting you
721 to enter a password often set ECHO False. See waitnoecho(). """
720 to enter a password often set ECHO False. See waitnoecho(). """
722
721
723 attr = termios.tcgetattr(self.child_fd)
722 attr = termios.tcgetattr(self.child_fd)
724 if attr[3] & termios.ECHO:
723 if attr[3] & termios.ECHO:
725 return True
724 return True
726 return False
725 return False
727
726
728 def setecho (self, state):
727 def setecho (self, state):
729
728
730 """This sets the terminal echo mode on or off. Note that anything the
729 """This sets the terminal echo mode on or off. Note that anything the
731 child sent before the echo will be lost, so you should be sure that
730 child sent before the echo will be lost, so you should be sure that
732 your input buffer is empty before you call setecho(). For example, the
731 your input buffer is empty before you call setecho(). For example, the
733 following will work as expected::
732 following will work as expected::
734
733
735 p = pexpect.spawn('cat')
734 p = pexpect.spawn('cat')
736 p.sendline ('1234') # We will see this twice (once from tty echo and again from cat).
735 p.sendline ('1234') # We will see this twice (once from tty echo and again from cat).
737 p.expect (['1234'])
736 p.expect (['1234'])
738 p.expect (['1234'])
737 p.expect (['1234'])
739 p.setecho(False) # Turn off tty echo
738 p.setecho(False) # Turn off tty echo
740 p.sendline ('abcd') # We will set this only once (echoed by cat).
739 p.sendline ('abcd') # We will set this only once (echoed by cat).
741 p.sendline ('wxyz') # We will set this only once (echoed by cat)
740 p.sendline ('wxyz') # We will set this only once (echoed by cat)
742 p.expect (['abcd'])
741 p.expect (['abcd'])
743 p.expect (['wxyz'])
742 p.expect (['wxyz'])
744
743
745 The following WILL NOT WORK because the lines sent before the setecho
744 The following WILL NOT WORK because the lines sent before the setecho
746 will be lost::
745 will be lost::
747
746
748 p = pexpect.spawn('cat')
747 p = pexpect.spawn('cat')
749 p.sendline ('1234') # We will see this twice (once from tty echo and again from cat).
748 p.sendline ('1234') # We will see this twice (once from tty echo and again from cat).
750 p.setecho(False) # Turn off tty echo
749 p.setecho(False) # Turn off tty echo
751 p.sendline ('abcd') # We will set this only once (echoed by cat).
750 p.sendline ('abcd') # We will set this only once (echoed by cat).
752 p.sendline ('wxyz') # We will set this only once (echoed by cat)
751 p.sendline ('wxyz') # We will set this only once (echoed by cat)
753 p.expect (['1234'])
752 p.expect (['1234'])
754 p.expect (['1234'])
753 p.expect (['1234'])
755 p.expect (['abcd'])
754 p.expect (['abcd'])
756 p.expect (['wxyz'])
755 p.expect (['wxyz'])
757 """
756 """
758
757
759 self.child_fd
758 self.child_fd
760 attr = termios.tcgetattr(self.child_fd)
759 attr = termios.tcgetattr(self.child_fd)
761 if state:
760 if state:
762 attr[3] = attr[3] | termios.ECHO
761 attr[3] = attr[3] | termios.ECHO
763 else:
762 else:
764 attr[3] = attr[3] & ~termios.ECHO
763 attr[3] = attr[3] & ~termios.ECHO
765 # I tried TCSADRAIN and TCSAFLUSH, but these were inconsistent
764 # I tried TCSADRAIN and TCSAFLUSH, but these were inconsistent
766 # and blocked on some platforms. TCSADRAIN is probably ideal if it worked.
765 # and blocked on some platforms. TCSADRAIN is probably ideal if it worked.
767 termios.tcsetattr(self.child_fd, termios.TCSANOW, attr)
766 termios.tcsetattr(self.child_fd, termios.TCSANOW, attr)
768
767
769 def read_nonblocking (self, size = 1, timeout = -1):
768 def read_nonblocking (self, size = 1, timeout = -1):
770
769
771 """This reads at most size characters from the child application. It
770 """This reads at most size characters from the child application. It
772 includes a timeout. If the read does not complete within the timeout
771 includes a timeout. If the read does not complete within the timeout
773 period then a TIMEOUT exception is raised. If the end of file is read
772 period then a TIMEOUT exception is raised. If the end of file is read
774 then an EOF exception will be raised. If a log file was set using
773 then an EOF exception will be raised. If a log file was set using
775 setlog() then all data will also be written to the log file.
774 setlog() then all data will also be written to the log file.
776
775
777 If timeout is None then the read may block indefinitely. If timeout is -1
776 If timeout is None then the read may block indefinitely. If timeout is -1
778 then the self.timeout value is used. If timeout is 0 then the child is
777 then the self.timeout value is used. If timeout is 0 then the child is
779 polled and if there was no data immediately ready then this will raise
778 polled and if there was no data immediately ready then this will raise
780 a TIMEOUT exception.
779 a TIMEOUT exception.
781
780
782 The timeout refers only to the amount of time to read at least one
781 The timeout refers only to the amount of time to read at least one
783 character. This is not effected by the 'size' parameter, so if you call
782 character. This is not effected by the 'size' parameter, so if you call
784 read_nonblocking(size=100, timeout=30) and only one character is
783 read_nonblocking(size=100, timeout=30) and only one character is
785 available right away then one character will be returned immediately.
784 available right away then one character will be returned immediately.
786 It will not wait for 30 seconds for another 99 characters to come in.
785 It will not wait for 30 seconds for another 99 characters to come in.
787
786
788 This is a wrapper around os.read(). It uses select.select() to
787 This is a wrapper around os.read(). It uses select.select() to
789 implement the timeout. """
788 implement the timeout. """
790
789
791 if self.closed:
790 if self.closed:
792 raise ValueError ('I/O operation on closed file in read_nonblocking().')
791 raise ValueError ('I/O operation on closed file in read_nonblocking().')
793
792
794 if timeout == -1:
793 if timeout == -1:
795 timeout = self.timeout
794 timeout = self.timeout
796
795
797 # Note that some systems such as Solaris do not give an EOF when
796 # Note that some systems such as Solaris do not give an EOF when
798 # the child dies. In fact, you can still try to read
797 # the child dies. In fact, you can still try to read
799 # from the child_fd -- it will block forever or until TIMEOUT.
798 # from the child_fd -- it will block forever or until TIMEOUT.
800 # For this case, I test isalive() before doing any reading.
799 # For this case, I test isalive() before doing any reading.
801 # If isalive() is false, then I pretend that this is the same as EOF.
800 # If isalive() is false, then I pretend that this is the same as EOF.
802 if not self.isalive():
801 if not self.isalive():
803 r,w,e = self.__select([self.child_fd], [], [], 0) # timeout of 0 means "poll"
802 r,w,e = self.__select([self.child_fd], [], [], 0) # timeout of 0 means "poll"
804 if not r:
803 if not r:
805 self.flag_eof = True
804 self.flag_eof = True
806 raise EOF ('End Of File (EOF) in read_nonblocking(). Braindead platform.')
805 raise EOF ('End Of File (EOF) in read_nonblocking(). Braindead platform.')
807 elif self.__irix_hack:
806 elif self.__irix_hack:
808 # This is a hack for Irix. It seems that Irix requires a long delay before checking isalive.
807 # This is a hack for Irix. It seems that Irix requires a long delay before checking isalive.
809 # This adds a 2 second delay, but only when the child is terminated.
808 # This adds a 2 second delay, but only when the child is terminated.
810 r, w, e = self.__select([self.child_fd], [], [], 2)
809 r, w, e = self.__select([self.child_fd], [], [], 2)
811 if not r and not self.isalive():
810 if not r and not self.isalive():
812 self.flag_eof = True
811 self.flag_eof = True
813 raise EOF ('End Of File (EOF) in read_nonblocking(). Pokey platform.')
812 raise EOF ('End Of File (EOF) in read_nonblocking(). Pokey platform.')
814
813
815 r,w,e = self.__select([self.child_fd], [], [], timeout)
814 r,w,e = self.__select([self.child_fd], [], [], timeout)
816
815
817 if not r:
816 if not r:
818 if not self.isalive():
817 if not self.isalive():
819 # Some platforms, such as Irix, will claim that their processes are alive;
818 # Some platforms, such as Irix, will claim that their processes are alive;
820 # then timeout on the select; and then finally admit that they are not alive.
819 # then timeout on the select; and then finally admit that they are not alive.
821 self.flag_eof = True
820 self.flag_eof = True
822 raise EOF ('End of File (EOF) in read_nonblocking(). Very pokey platform.')
821 raise EOF ('End of File (EOF) in read_nonblocking(). Very pokey platform.')
823 else:
822 else:
824 raise TIMEOUT ('Timeout exceeded in read_nonblocking().')
823 raise TIMEOUT ('Timeout exceeded in read_nonblocking().')
825
824
826 if self.child_fd in r:
825 if self.child_fd in r:
827 try:
826 try:
828 s = os.read(self.child_fd, size)
827 s = os.read(self.child_fd, size)
829 except OSError, e: # Linux does this
828 except OSError, e: # Linux does this
830 self.flag_eof = True
829 self.flag_eof = True
831 raise EOF ('End Of File (EOF) in read_nonblocking(). Exception style platform.')
830 raise EOF ('End Of File (EOF) in read_nonblocking(). Exception style platform.')
832 if s == '': # BSD style
831 if s == '': # BSD style
833 self.flag_eof = True
832 self.flag_eof = True
834 raise EOF ('End Of File (EOF) in read_nonblocking(). Empty string style platform.')
833 raise EOF ('End Of File (EOF) in read_nonblocking(). Empty string style platform.')
835
834
836 if self.logfile is not None:
835 if self.logfile is not None:
837 self.logfile.write (s)
836 self.logfile.write (s)
838 self.logfile.flush()
837 self.logfile.flush()
839 if self.logfile_read is not None:
838 if self.logfile_read is not None:
840 self.logfile_read.write (s)
839 self.logfile_read.write (s)
841 self.logfile_read.flush()
840 self.logfile_read.flush()
842
841
843 return s
842 return s
844
843
845 raise ExceptionPexpect ('Reached an unexpected state in read_nonblocking().')
844 raise ExceptionPexpect ('Reached an unexpected state in read_nonblocking().')
846
845
847 def read (self, size = -1): # File-like object.
846 def read (self, size = -1): # File-like object.
848
847
849 """This reads at most "size" bytes from the file (less if the read hits
848 """This reads at most "size" bytes from the file (less if the read hits
850 EOF before obtaining size bytes). If the size argument is negative or
849 EOF before obtaining size bytes). If the size argument is negative or
851 omitted, read all data until EOF is reached. The bytes are returned as
850 omitted, read all data until EOF is reached. The bytes are returned as
852 a string object. An empty string is returned when EOF is encountered
851 a string object. An empty string is returned when EOF is encountered
853 immediately. """
852 immediately. """
854
853
855 if size == 0:
854 if size == 0:
856 return ''
855 return ''
857 if size < 0:
856 if size < 0:
858 self.expect (self.delimiter) # delimiter default is EOF
857 self.expect (self.delimiter) # delimiter default is EOF
859 return self.before
858 return self.before
860
859
861 # I could have done this more directly by not using expect(), but
860 # I could have done this more directly by not using expect(), but
862 # I deliberately decided to couple read() to expect() so that
861 # I deliberately decided to couple read() to expect() so that
863 # I would catch any bugs early and ensure consistant behavior.
862 # I would catch any bugs early and ensure consistant behavior.
864 # It's a little less efficient, but there is less for me to
863 # It's a little less efficient, but there is less for me to
865 # worry about if I have to later modify read() or expect().
864 # worry about if I have to later modify read() or expect().
866 # Note, it's OK if size==-1 in the regex. That just means it
865 # Note, it's OK if size==-1 in the regex. That just means it
867 # will never match anything in which case we stop only on EOF.
866 # will never match anything in which case we stop only on EOF.
868 cre = re.compile('.{%d}' % size, re.DOTALL)
867 cre = re.compile('.{%d}' % size, re.DOTALL)
869 index = self.expect ([cre, self.delimiter]) # delimiter default is EOF
868 index = self.expect ([cre, self.delimiter]) # delimiter default is EOF
870 if index == 0:
869 if index == 0:
871 return self.after ### self.before should be ''. Should I assert this?
870 return self.after ### self.before should be ''. Should I assert this?
872 return self.before
871 return self.before
873
872
874 def readline (self, size = -1): # File-like object.
873 def readline (self, size = -1): # File-like object.
875
874
876 """This reads and returns one entire line. A trailing newline is kept
875 """This reads and returns one entire line. A trailing newline is kept
877 in the string, but may be absent when a file ends with an incomplete
876 in the string, but may be absent when a file ends with an incomplete
878 line. Note: This readline() looks for a \\r\\n pair even on UNIX
877 line. Note: This readline() looks for a \\r\\n pair even on UNIX
879 because this is what the pseudo tty device returns. So contrary to what
878 because this is what the pseudo tty device returns. So contrary to what
880 you may expect you will receive the newline as \\r\\n. An empty string
879 you may expect you will receive the newline as \\r\\n. An empty string
881 is returned when EOF is hit immediately. Currently, the size argument is
880 is returned when EOF is hit immediately. Currently, the size argument is
882 mostly ignored, so this behavior is not standard for a file-like
881 mostly ignored, so this behavior is not standard for a file-like
883 object. If size is 0 then an empty string is returned. """
882 object. If size is 0 then an empty string is returned. """
884
883
885 if size == 0:
884 if size == 0:
886 return ''
885 return ''
887 index = self.expect (['\r\n', self.delimiter]) # delimiter default is EOF
886 index = self.expect (['\r\n', self.delimiter]) # delimiter default is EOF
888 if index == 0:
887 if index == 0:
889 return self.before + '\r\n'
888 return self.before + '\r\n'
890 else:
889 else:
891 return self.before
890 return self.before
892
891
893 def __iter__ (self): # File-like object.
892 def __iter__ (self): # File-like object.
894
893
895 """This is to support iterators over a file-like object.
894 """This is to support iterators over a file-like object.
896 """
895 """
897
896
898 return self
897 return self
899
898
900 def next (self): # File-like object.
899 def next (self): # File-like object.
901
900
902 """This is to support iterators over a file-like object.
901 """This is to support iterators over a file-like object.
903 """
902 """
904
903
905 result = self.readline()
904 result = self.readline()
906 if result == "":
905 if result == "":
907 raise StopIteration
906 raise StopIteration
908 return result
907 return result
909
908
910 def readlines (self, sizehint = -1): # File-like object.
909 def readlines (self, sizehint = -1): # File-like object.
911
910
912 """This reads until EOF using readline() and returns a list containing
911 """This reads until EOF using readline() and returns a list containing
913 the lines thus read. The optional "sizehint" argument is ignored. """
912 the lines thus read. The optional "sizehint" argument is ignored. """
914
913
915 lines = []
914 lines = []
916 while True:
915 while True:
917 line = self.readline()
916 line = self.readline()
918 if not line:
917 if not line:
919 break
918 break
920 lines.append(line)
919 lines.append(line)
921 return lines
920 return lines
922
921
923 def write(self, s): # File-like object.
922 def write(self, s): # File-like object.
924
923
925 """This is similar to send() except that there is no return value.
924 """This is similar to send() except that there is no return value.
926 """
925 """
927
926
928 self.send (s)
927 self.send (s)
929
928
930 def writelines (self, sequence): # File-like object.
929 def writelines (self, sequence): # File-like object.
931
930
932 """This calls write() for each element in the sequence. The sequence
931 """This calls write() for each element in the sequence. The sequence
933 can be any iterable object producing strings, typically a list of
932 can be any iterable object producing strings, typically a list of
934 strings. This does not add line separators There is no return value.
933 strings. This does not add line separators There is no return value.
935 """
934 """
936
935
937 for s in sequence:
936 for s in sequence:
938 self.write (s)
937 self.write (s)
939
938
940 def send(self, s):
939 def send(self, s):
941
940
942 """This sends a string to the child process. This returns the number of
941 """This sends a string to the child process. This returns the number of
943 bytes written. If a log file was set then the data is also written to
942 bytes written. If a log file was set then the data is also written to
944 the log. """
943 the log. """
945
944
946 time.sleep(self.delaybeforesend)
945 time.sleep(self.delaybeforesend)
947 if self.logfile is not None:
946 if self.logfile is not None:
948 self.logfile.write (s)
947 self.logfile.write (s)
949 self.logfile.flush()
948 self.logfile.flush()
950 if self.logfile_send is not None:
949 if self.logfile_send is not None:
951 self.logfile_send.write (s)
950 self.logfile_send.write (s)
952 self.logfile_send.flush()
951 self.logfile_send.flush()
953 c = os.write(self.child_fd, s)
952 c = os.write(self.child_fd, s)
954 return c
953 return c
955
954
956 def sendline(self, s=''):
955 def sendline(self, s=''):
957
956
958 """This is like send(), but it adds a line feed (os.linesep). This
957 """This is like send(), but it adds a line feed (os.linesep). This
959 returns the number of bytes written. """
958 returns the number of bytes written. """
960
959
961 n = self.send(s)
960 n = self.send(s)
962 n = n + self.send (os.linesep)
961 n = n + self.send (os.linesep)
963 return n
962 return n
964
963
965 def sendcontrol(self, char):
964 def sendcontrol(self, char):
966
965
967 """This sends a control character to the child such as Ctrl-C or
966 """This sends a control character to the child such as Ctrl-C or
968 Ctrl-D. For example, to send a Ctrl-G (ASCII 7)::
967 Ctrl-D. For example, to send a Ctrl-G (ASCII 7)::
969
968
970 child.sendcontrol('g')
969 child.sendcontrol('g')
971
970
972 See also, sendintr() and sendeof().
971 See also, sendintr() and sendeof().
973 """
972 """
974
973
975 char = char.lower()
974 char = char.lower()
976 a = ord(char)
975 a = ord(char)
977 if a>=97 and a<=122:
976 if a>=97 and a<=122:
978 a = a - ord('a') + 1
977 a = a - ord('a') + 1
979 return self.send (chr(a))
978 return self.send (chr(a))
980 d = {'@':0, '`':0,
979 d = {'@':0, '`':0,
981 '[':27, '{':27,
980 '[':27, '{':27,
982 '\\':28, '|':28,
981 '\\':28, '|':28,
983 ']':29, '}': 29,
982 ']':29, '}': 29,
984 '^':30, '~':30,
983 '^':30, '~':30,
985 '_':31,
984 '_':31,
986 '?':127}
985 '?':127}
987 if char not in d:
986 if char not in d:
988 return 0
987 return 0
989 return self.send (chr(d[char]))
988 return self.send (chr(d[char]))
990
989
991 def sendeof(self):
990 def sendeof(self):
992
991
993 """This sends an EOF to the child. This sends a character which causes
992 """This sends an EOF to the child. This sends a character which causes
994 the pending parent output buffer to be sent to the waiting child
993 the pending parent output buffer to be sent to the waiting child
995 program without waiting for end-of-line. If it is the first character
994 program without waiting for end-of-line. If it is the first character
996 of the line, the read() in the user program returns 0, which signifies
995 of the line, the read() in the user program returns 0, which signifies
997 end-of-file. This means to work as expected a sendeof() has to be
996 end-of-file. This means to work as expected a sendeof() has to be
998 called at the beginning of a line. This method does not send a newline.
997 called at the beginning of a line. This method does not send a newline.
999 It is the responsibility of the caller to ensure the eof is sent at the
998 It is the responsibility of the caller to ensure the eof is sent at the
1000 beginning of a line. """
999 beginning of a line. """
1001
1000
1002 ### Hmmm... how do I send an EOF?
1001 ### Hmmm... how do I send an EOF?
1003 ###C if ((m = write(pty, *buf, p - *buf)) < 0)
1002 ###C if ((m = write(pty, *buf, p - *buf)) < 0)
1004 ###C return (errno == EWOULDBLOCK) ? n : -1;
1003 ###C return (errno == EWOULDBLOCK) ? n : -1;
1005 #fd = sys.stdin.fileno()
1004 #fd = sys.stdin.fileno()
1006 #old = termios.tcgetattr(fd) # remember current state
1005 #old = termios.tcgetattr(fd) # remember current state
1007 #attr = termios.tcgetattr(fd)
1006 #attr = termios.tcgetattr(fd)
1008 #attr[3] = attr[3] | termios.ICANON # ICANON must be set to recognize EOF
1007 #attr[3] = attr[3] | termios.ICANON # ICANON must be set to recognize EOF
1009 #try: # use try/finally to ensure state gets restored
1008 #try: # use try/finally to ensure state gets restored
1010 # termios.tcsetattr(fd, termios.TCSADRAIN, attr)
1009 # termios.tcsetattr(fd, termios.TCSADRAIN, attr)
1011 # if hasattr(termios, 'CEOF'):
1010 # if hasattr(termios, 'CEOF'):
1012 # os.write (self.child_fd, '%c' % termios.CEOF)
1011 # os.write (self.child_fd, '%c' % termios.CEOF)
1013 # else:
1012 # else:
1014 # # Silly platform does not define CEOF so assume CTRL-D
1013 # # Silly platform does not define CEOF so assume CTRL-D
1015 # os.write (self.child_fd, '%c' % 4)
1014 # os.write (self.child_fd, '%c' % 4)
1016 #finally: # restore state
1015 #finally: # restore state
1017 # termios.tcsetattr(fd, termios.TCSADRAIN, old)
1016 # termios.tcsetattr(fd, termios.TCSADRAIN, old)
1018 if hasattr(termios, 'VEOF'):
1017 if hasattr(termios, 'VEOF'):
1019 char = termios.tcgetattr(self.child_fd)[6][termios.VEOF]
1018 char = termios.tcgetattr(self.child_fd)[6][termios.VEOF]
1020 else:
1019 else:
1021 # platform does not define VEOF so assume CTRL-D
1020 # platform does not define VEOF so assume CTRL-D
1022 char = chr(4)
1021 char = chr(4)
1023 self.send(char)
1022 self.send(char)
1024
1023
1025 def sendintr(self):
1024 def sendintr(self):
1026
1025
1027 """This sends a SIGINT to the child. It does not require
1026 """This sends a SIGINT to the child. It does not require
1028 the SIGINT to be the first character on a line. """
1027 the SIGINT to be the first character on a line. """
1029
1028
1030 if hasattr(termios, 'VINTR'):
1029 if hasattr(termios, 'VINTR'):
1031 char = termios.tcgetattr(self.child_fd)[6][termios.VINTR]
1030 char = termios.tcgetattr(self.child_fd)[6][termios.VINTR]
1032 else:
1031 else:
1033 # platform does not define VINTR so assume CTRL-C
1032 # platform does not define VINTR so assume CTRL-C
1034 char = chr(3)
1033 char = chr(3)
1035 self.send (char)
1034 self.send (char)
1036
1035
1037 def eof (self):
1036 def eof (self):
1038
1037
1039 """This returns True if the EOF exception was ever raised.
1038 """This returns True if the EOF exception was ever raised.
1040 """
1039 """
1041
1040
1042 return self.flag_eof
1041 return self.flag_eof
1043
1042
1044 def terminate(self, force=False):
1043 def terminate(self, force=False):
1045
1044
1046 """This forces a child process to terminate. It starts nicely with
1045 """This forces a child process to terminate. It starts nicely with
1047 SIGHUP and SIGINT. If "force" is True then moves onto SIGKILL. This
1046 SIGHUP and SIGINT. If "force" is True then moves onto SIGKILL. This
1048 returns True if the child was terminated. This returns False if the
1047 returns True if the child was terminated. This returns False if the
1049 child could not be terminated. """
1048 child could not be terminated. """
1050
1049
1051 if not self.isalive():
1050 if not self.isalive():
1052 return True
1051 return True
1053 try:
1052 try:
1054 self.kill(signal.SIGHUP)
1053 self.kill(signal.SIGHUP)
1055 time.sleep(self.delayafterterminate)
1054 time.sleep(self.delayafterterminate)
1056 if not self.isalive():
1055 if not self.isalive():
1057 return True
1056 return True
1058 self.kill(signal.SIGCONT)
1057 self.kill(signal.SIGCONT)
1059 time.sleep(self.delayafterterminate)
1058 time.sleep(self.delayafterterminate)
1060 if not self.isalive():
1059 if not self.isalive():
1061 return True
1060 return True
1062 self.kill(signal.SIGINT)
1061 self.kill(signal.SIGINT)
1063 time.sleep(self.delayafterterminate)
1062 time.sleep(self.delayafterterminate)
1064 if not self.isalive():
1063 if not self.isalive():
1065 return True
1064 return True
1066 if force:
1065 if force:
1067 self.kill(signal.SIGKILL)
1066 self.kill(signal.SIGKILL)
1068 time.sleep(self.delayafterterminate)
1067 time.sleep(self.delayafterterminate)
1069 if not self.isalive():
1068 if not self.isalive():
1070 return True
1069 return True
1071 else:
1070 else:
1072 return False
1071 return False
1073 return False
1072 return False
1074 except OSError, e:
1073 except OSError, e:
1075 # I think there are kernel timing issues that sometimes cause
1074 # I think there are kernel timing issues that sometimes cause
1076 # this to happen. I think isalive() reports True, but the
1075 # this to happen. I think isalive() reports True, but the
1077 # process is dead to the kernel.
1076 # process is dead to the kernel.
1078 # Make one last attempt to see if the kernel is up to date.
1077 # Make one last attempt to see if the kernel is up to date.
1079 time.sleep(self.delayafterterminate)
1078 time.sleep(self.delayafterterminate)
1080 if not self.isalive():
1079 if not self.isalive():
1081 return True
1080 return True
1082 else:
1081 else:
1083 return False
1082 return False
1084
1083
1085 def wait(self):
1084 def wait(self):
1086
1085
1087 """This waits until the child exits. This is a blocking call. This will
1086 """This waits until the child exits. This is a blocking call. This will
1088 not read any data from the child, so this will block forever if the
1087 not read any data from the child, so this will block forever if the
1089 child has unread output and has terminated. In other words, the child
1088 child has unread output and has terminated. In other words, the child
1090 may have printed output then called exit(); but, technically, the child
1089 may have printed output then called exit(); but, technically, the child
1091 is still alive until its output is read. """
1090 is still alive until its output is read. """
1092
1091
1093 if self.isalive():
1092 if self.isalive():
1094 pid, status = os.waitpid(self.pid, 0)
1093 pid, status = os.waitpid(self.pid, 0)
1095 else:
1094 else:
1096 raise ExceptionPexpect ('Cannot wait for dead child process.')
1095 raise ExceptionPexpect ('Cannot wait for dead child process.')
1097 self.exitstatus = os.WEXITSTATUS(status)
1096 self.exitstatus = os.WEXITSTATUS(status)
1098 if os.WIFEXITED (status):
1097 if os.WIFEXITED (status):
1099 self.status = status
1098 self.status = status
1100 self.exitstatus = os.WEXITSTATUS(status)
1099 self.exitstatus = os.WEXITSTATUS(status)
1101 self.signalstatus = None
1100 self.signalstatus = None
1102 self.terminated = True
1101 self.terminated = True
1103 elif os.WIFSIGNALED (status):
1102 elif os.WIFSIGNALED (status):
1104 self.status = status
1103 self.status = status
1105 self.exitstatus = None
1104 self.exitstatus = None
1106 self.signalstatus = os.WTERMSIG(status)
1105 self.signalstatus = os.WTERMSIG(status)
1107 self.terminated = True
1106 self.terminated = True
1108 elif os.WIFSTOPPED (status):
1107 elif os.WIFSTOPPED (status):
1109 raise ExceptionPexpect ('Wait was called for a child process that is stopped. This is not supported. Is some other process attempting job control with our child pid?')
1108 raise ExceptionPexpect ('Wait was called for a child process that is stopped. This is not supported. Is some other process attempting job control with our child pid?')
1110 return self.exitstatus
1109 return self.exitstatus
1111
1110
1112 def isalive(self):
1111 def isalive(self):
1113
1112
1114 """This tests if the child process is running or not. This is
1113 """This tests if the child process is running or not. This is
1115 non-blocking. If the child was terminated then this will read the
1114 non-blocking. If the child was terminated then this will read the
1116 exitstatus or signalstatus of the child. This returns True if the child
1115 exitstatus or signalstatus of the child. This returns True if the child
1117 process appears to be running or False if not. It can take literally
1116 process appears to be running or False if not. It can take literally
1118 SECONDS for Solaris to return the right status. """
1117 SECONDS for Solaris to return the right status. """
1119
1118
1120 if self.terminated:
1119 if self.terminated:
1121 return False
1120 return False
1122
1121
1123 if self.flag_eof:
1122 if self.flag_eof:
1124 # This is for Linux, which requires the blocking form of waitpid to get
1123 # This is for Linux, which requires the blocking form of waitpid to get
1125 # status of a defunct process. This is super-lame. The flag_eof would have
1124 # status of a defunct process. This is super-lame. The flag_eof would have
1126 # been set in read_nonblocking(), so this should be safe.
1125 # been set in read_nonblocking(), so this should be safe.
1127 waitpid_options = 0
1126 waitpid_options = 0
1128 else:
1127 else:
1129 waitpid_options = os.WNOHANG
1128 waitpid_options = os.WNOHANG
1130
1129
1131 try:
1130 try:
1132 pid, status = os.waitpid(self.pid, waitpid_options)
1131 pid, status = os.waitpid(self.pid, waitpid_options)
1133 except OSError, e: # No child processes
1132 except OSError, e: # No child processes
1134 if e[0] == errno.ECHILD:
1133 if e[0] == errno.ECHILD:
1135 raise ExceptionPexpect ('isalive() encountered condition where "terminated" is 0, but there was no child process. Did someone else call waitpid() on our process?')
1134 raise ExceptionPexpect ('isalive() encountered condition where "terminated" is 0, but there was no child process. Did someone else call waitpid() on our process?')
1136 else:
1135 else:
1137 raise e
1136 raise e
1138
1137
1139 # I have to do this twice for Solaris. I can't even believe that I figured this out...
1138 # I have to do this twice for Solaris. I can't even believe that I figured this out...
1140 # If waitpid() returns 0 it means that no child process wishes to
1139 # If waitpid() returns 0 it means that no child process wishes to
1141 # report, and the value of status is undefined.
1140 # report, and the value of status is undefined.
1142 if pid == 0:
1141 if pid == 0:
1143 try:
1142 try:
1144 pid, status = os.waitpid(self.pid, waitpid_options) ### os.WNOHANG) # Solaris!
1143 pid, status = os.waitpid(self.pid, waitpid_options) ### os.WNOHANG) # Solaris!
1145 except OSError, e: # This should never happen...
1144 except OSError, e: # This should never happen...
1146 if e[0] == errno.ECHILD:
1145 if e[0] == errno.ECHILD:
1147 raise ExceptionPexpect ('isalive() encountered condition that should never happen. There was no child process. Did someone else call waitpid() on our process?')
1146 raise ExceptionPexpect ('isalive() encountered condition that should never happen. There was no child process. Did someone else call waitpid() on our process?')
1148 else:
1147 else:
1149 raise e
1148 raise e
1150
1149
1151 # If pid is still 0 after two calls to waitpid() then
1150 # If pid is still 0 after two calls to waitpid() then
1152 # the process really is alive. This seems to work on all platforms, except
1151 # the process really is alive. This seems to work on all platforms, except
1153 # for Irix which seems to require a blocking call on waitpid or select, so I let read_nonblocking
1152 # for Irix which seems to require a blocking call on waitpid or select, so I let read_nonblocking
1154 # take care of this situation (unfortunately, this requires waiting through the timeout).
1153 # take care of this situation (unfortunately, this requires waiting through the timeout).
1155 if pid == 0:
1154 if pid == 0:
1156 return True
1155 return True
1157
1156
1158 if pid == 0:
1157 if pid == 0:
1159 return True
1158 return True
1160
1159
1161 if os.WIFEXITED (status):
1160 if os.WIFEXITED (status):
1162 self.status = status
1161 self.status = status
1163 self.exitstatus = os.WEXITSTATUS(status)
1162 self.exitstatus = os.WEXITSTATUS(status)
1164 self.signalstatus = None
1163 self.signalstatus = None
1165 self.terminated = True
1164 self.terminated = True
1166 elif os.WIFSIGNALED (status):
1165 elif os.WIFSIGNALED (status):
1167 self.status = status
1166 self.status = status
1168 self.exitstatus = None
1167 self.exitstatus = None
1169 self.signalstatus = os.WTERMSIG(status)
1168 self.signalstatus = os.WTERMSIG(status)
1170 self.terminated = True
1169 self.terminated = True
1171 elif os.WIFSTOPPED (status):
1170 elif os.WIFSTOPPED (status):
1172 raise ExceptionPexpect ('isalive() encountered condition where child process is stopped. This is not supported. Is some other process attempting job control with our child pid?')
1171 raise ExceptionPexpect ('isalive() encountered condition where child process is stopped. This is not supported. Is some other process attempting job control with our child pid?')
1173 return False
1172 return False
1174
1173
1175 def kill(self, sig):
1174 def kill(self, sig):
1176
1175
1177 """This sends the given signal to the child application. In keeping
1176 """This sends the given signal to the child application. In keeping
1178 with UNIX tradition it has a misleading name. It does not necessarily
1177 with UNIX tradition it has a misleading name. It does not necessarily
1179 kill the child unless you send the right signal. """
1178 kill the child unless you send the right signal. """
1180
1179
1181 # Same as os.kill, but the pid is given for you.
1180 # Same as os.kill, but the pid is given for you.
1182 if self.isalive():
1181 if self.isalive():
1183 os.kill(self.pid, sig)
1182 os.kill(self.pid, sig)
1184
1183
1185 def compile_pattern_list(self, patterns):
1184 def compile_pattern_list(self, patterns):
1186
1185
1187 """This compiles a pattern-string or a list of pattern-strings.
1186 """This compiles a pattern-string or a list of pattern-strings.
1188 Patterns must be a StringType, EOF, TIMEOUT, SRE_Pattern, or a list of
1187 Patterns must be a StringType, EOF, TIMEOUT, SRE_Pattern, or a list of
1189 those. Patterns may also be None which results in an empty list (you
1188 those. Patterns may also be None which results in an empty list (you
1190 might do this if waiting for an EOF or TIMEOUT condition without
1189 might do this if waiting for an EOF or TIMEOUT condition without
1191 expecting any pattern).
1190 expecting any pattern).
1192
1191
1193 This is used by expect() when calling expect_list(). Thus expect() is
1192 This is used by expect() when calling expect_list(). Thus expect() is
1194 nothing more than::
1193 nothing more than::
1195
1194
1196 cpl = self.compile_pattern_list(pl)
1195 cpl = self.compile_pattern_list(pl)
1197 return self.expect_list(cpl, timeout)
1196 return self.expect_list(cpl, timeout)
1198
1197
1199 If you are using expect() within a loop it may be more
1198 If you are using expect() within a loop it may be more
1200 efficient to compile the patterns first and then call expect_list().
1199 efficient to compile the patterns first and then call expect_list().
1201 This avoid calls in a loop to compile_pattern_list()::
1200 This avoid calls in a loop to compile_pattern_list()::
1202
1201
1203 cpl = self.compile_pattern_list(my_pattern)
1202 cpl = self.compile_pattern_list(my_pattern)
1204 while some_condition:
1203 while some_condition:
1205 ...
1204 ...
1206 i = self.expect_list(clp, timeout)
1205 i = self.expect_list(clp, timeout)
1207 ...
1206 ...
1208 """
1207 """
1209
1208
1210 if patterns is None:
1209 if patterns is None:
1211 return []
1210 return []
1212 if type(patterns) is not types.ListType:
1211 if type(patterns) is not types.ListType:
1213 patterns = [patterns]
1212 patterns = [patterns]
1214
1213
1215 compile_flags = re.DOTALL # Allow dot to match \n
1214 compile_flags = re.DOTALL # Allow dot to match \n
1216 if self.ignorecase:
1215 if self.ignorecase:
1217 compile_flags = compile_flags | re.IGNORECASE
1216 compile_flags = compile_flags | re.IGNORECASE
1218 compiled_pattern_list = []
1217 compiled_pattern_list = []
1219 for p in patterns:
1218 for p in patterns:
1220 if type(p) in types.StringTypes:
1219 if type(p) in types.StringTypes:
1221 compiled_pattern_list.append(re.compile(p, compile_flags))
1220 compiled_pattern_list.append(re.compile(p, compile_flags))
1222 elif p is EOF:
1221 elif p is EOF:
1223 compiled_pattern_list.append(EOF)
1222 compiled_pattern_list.append(EOF)
1224 elif p is TIMEOUT:
1223 elif p is TIMEOUT:
1225 compiled_pattern_list.append(TIMEOUT)
1224 compiled_pattern_list.append(TIMEOUT)
1226 elif type(p) is type(re.compile('')):
1225 elif type(p) is type(re.compile('')):
1227 compiled_pattern_list.append(p)
1226 compiled_pattern_list.append(p)
1228 else:
1227 else:
1229 raise TypeError ('Argument must be one of StringTypes, EOF, TIMEOUT, SRE_Pattern, or a list of those type. %s' % str(type(p)))
1228 raise TypeError ('Argument must be one of StringTypes, EOF, TIMEOUT, SRE_Pattern, or a list of those type. %s' % str(type(p)))
1230
1229
1231 return compiled_pattern_list
1230 return compiled_pattern_list
1232
1231
1233 def expect(self, pattern, timeout = -1, searchwindowsize=None):
1232 def expect(self, pattern, timeout = -1, searchwindowsize=None):
1234
1233
1235 """This seeks through the stream until a pattern is matched. The
1234 """This seeks through the stream until a pattern is matched. The
1236 pattern is overloaded and may take several types. The pattern can be a
1235 pattern is overloaded and may take several types. The pattern can be a
1237 StringType, EOF, a compiled re, or a list of any of those types.
1236 StringType, EOF, a compiled re, or a list of any of those types.
1238 Strings will be compiled to re types. This returns the index into the
1237 Strings will be compiled to re types. This returns the index into the
1239 pattern list. If the pattern was not a list this returns index 0 on a
1238 pattern list. If the pattern was not a list this returns index 0 on a
1240 successful match. This may raise exceptions for EOF or TIMEOUT. To
1239 successful match. This may raise exceptions for EOF or TIMEOUT. To
1241 avoid the EOF or TIMEOUT exceptions add EOF or TIMEOUT to the pattern
1240 avoid the EOF or TIMEOUT exceptions add EOF or TIMEOUT to the pattern
1242 list. That will cause expect to match an EOF or TIMEOUT condition
1241 list. That will cause expect to match an EOF or TIMEOUT condition
1243 instead of raising an exception.
1242 instead of raising an exception.
1244
1243
1245 If you pass a list of patterns and more than one matches, the first match
1244 If you pass a list of patterns and more than one matches, the first match
1246 in the stream is chosen. If more than one pattern matches at that point,
1245 in the stream is chosen. If more than one pattern matches at that point,
1247 the leftmost in the pattern list is chosen. For example::
1246 the leftmost in the pattern list is chosen. For example::
1248
1247
1249 # the input is 'foobar'
1248 # the input is 'foobar'
1250 index = p.expect (['bar', 'foo', 'foobar'])
1249 index = p.expect (['bar', 'foo', 'foobar'])
1251 # returns 1 ('foo') even though 'foobar' is a "better" match
1250 # returns 1 ('foo') even though 'foobar' is a "better" match
1252
1251
1253 Please note, however, that buffering can affect this behavior, since
1252 Please note, however, that buffering can affect this behavior, since
1254 input arrives in unpredictable chunks. For example::
1253 input arrives in unpredictable chunks. For example::
1255
1254
1256 # the input is 'foobar'
1255 # the input is 'foobar'
1257 index = p.expect (['foobar', 'foo'])
1256 index = p.expect (['foobar', 'foo'])
1258 # returns 0 ('foobar') if all input is available at once,
1257 # returns 0 ('foobar') if all input is available at once,
1259 # but returs 1 ('foo') if parts of the final 'bar' arrive late
1258 # but returs 1 ('foo') if parts of the final 'bar' arrive late
1260
1259
1261 After a match is found the instance attributes 'before', 'after' and
1260 After a match is found the instance attributes 'before', 'after' and
1262 'match' will be set. You can see all the data read before the match in
1261 'match' will be set. You can see all the data read before the match in
1263 'before'. You can see the data that was matched in 'after'. The
1262 'before'. You can see the data that was matched in 'after'. The
1264 re.MatchObject used in the re match will be in 'match'. If an error
1263 re.MatchObject used in the re match will be in 'match'. If an error
1265 occurred then 'before' will be set to all the data read so far and
1264 occurred then 'before' will be set to all the data read so far and
1266 'after' and 'match' will be None.
1265 'after' and 'match' will be None.
1267
1266
1268 If timeout is -1 then timeout will be set to the self.timeout value.
1267 If timeout is -1 then timeout will be set to the self.timeout value.
1269
1268
1270 A list entry may be EOF or TIMEOUT instead of a string. This will
1269 A list entry may be EOF or TIMEOUT instead of a string. This will
1271 catch these exceptions and return the index of the list entry instead
1270 catch these exceptions and return the index of the list entry instead
1272 of raising the exception. The attribute 'after' will be set to the
1271 of raising the exception. The attribute 'after' will be set to the
1273 exception type. The attribute 'match' will be None. This allows you to
1272 exception type. The attribute 'match' will be None. This allows you to
1274 write code like this::
1273 write code like this::
1275
1274
1276 index = p.expect (['good', 'bad', pexpect.EOF, pexpect.TIMEOUT])
1275 index = p.expect (['good', 'bad', pexpect.EOF, pexpect.TIMEOUT])
1277 if index == 0:
1276 if index == 0:
1278 do_something()
1277 do_something()
1279 elif index == 1:
1278 elif index == 1:
1280 do_something_else()
1279 do_something_else()
1281 elif index == 2:
1280 elif index == 2:
1282 do_some_other_thing()
1281 do_some_other_thing()
1283 elif index == 3:
1282 elif index == 3:
1284 do_something_completely_different()
1283 do_something_completely_different()
1285
1284
1286 instead of code like this::
1285 instead of code like this::
1287
1286
1288 try:
1287 try:
1289 index = p.expect (['good', 'bad'])
1288 index = p.expect (['good', 'bad'])
1290 if index == 0:
1289 if index == 0:
1291 do_something()
1290 do_something()
1292 elif index == 1:
1291 elif index == 1:
1293 do_something_else()
1292 do_something_else()
1294 except EOF:
1293 except EOF:
1295 do_some_other_thing()
1294 do_some_other_thing()
1296 except TIMEOUT:
1295 except TIMEOUT:
1297 do_something_completely_different()
1296 do_something_completely_different()
1298
1297
1299 These two forms are equivalent. It all depends on what you want. You
1298 These two forms are equivalent. It all depends on what you want. You
1300 can also just expect the EOF if you are waiting for all output of a
1299 can also just expect the EOF if you are waiting for all output of a
1301 child to finish. For example::
1300 child to finish. For example::
1302
1301
1303 p = pexpect.spawn('/bin/ls')
1302 p = pexpect.spawn('/bin/ls')
1304 p.expect (pexpect.EOF)
1303 p.expect (pexpect.EOF)
1305 print p.before
1304 print p.before
1306
1305
1307 If you are trying to optimize for speed then see expect_list().
1306 If you are trying to optimize for speed then see expect_list().
1308 """
1307 """
1309
1308
1310 compiled_pattern_list = self.compile_pattern_list(pattern)
1309 compiled_pattern_list = self.compile_pattern_list(pattern)
1311 return self.expect_list(compiled_pattern_list, timeout, searchwindowsize)
1310 return self.expect_list(compiled_pattern_list, timeout, searchwindowsize)
1312
1311
1313 def expect_list(self, pattern_list, timeout = -1, searchwindowsize = -1):
1312 def expect_list(self, pattern_list, timeout = -1, searchwindowsize = -1):
1314
1313
1315 """This takes a list of compiled regular expressions and returns the
1314 """This takes a list of compiled regular expressions and returns the
1316 index into the pattern_list that matched the child output. The list may
1315 index into the pattern_list that matched the child output. The list may
1317 also contain EOF or TIMEOUT (which are not compiled regular
1316 also contain EOF or TIMEOUT (which are not compiled regular
1318 expressions). This method is similar to the expect() method except that
1317 expressions). This method is similar to the expect() method except that
1319 expect_list() does not recompile the pattern list on every call. This
1318 expect_list() does not recompile the pattern list on every call. This
1320 may help if you are trying to optimize for speed, otherwise just use
1319 may help if you are trying to optimize for speed, otherwise just use
1321 the expect() method. This is called by expect(). If timeout==-1 then
1320 the expect() method. This is called by expect(). If timeout==-1 then
1322 the self.timeout value is used. If searchwindowsize==-1 then the
1321 the self.timeout value is used. If searchwindowsize==-1 then the
1323 self.searchwindowsize value is used. """
1322 self.searchwindowsize value is used. """
1324
1323
1325 return self.expect_loop(searcher_re(pattern_list), timeout, searchwindowsize)
1324 return self.expect_loop(searcher_re(pattern_list), timeout, searchwindowsize)
1326
1325
1327 def expect_exact(self, pattern_list, timeout = -1, searchwindowsize = -1):
1326 def expect_exact(self, pattern_list, timeout = -1, searchwindowsize = -1):
1328
1327
1329 """This is similar to expect(), but uses plain string matching instead
1328 """This is similar to expect(), but uses plain string matching instead
1330 of compiled regular expressions in 'pattern_list'. The 'pattern_list'
1329 of compiled regular expressions in 'pattern_list'. The 'pattern_list'
1331 may be a string; a list or other sequence of strings; or TIMEOUT and
1330 may be a string; a list or other sequence of strings; or TIMEOUT and
1332 EOF.
1331 EOF.
1333
1332
1334 This call might be faster than expect() for two reasons: string
1333 This call might be faster than expect() for two reasons: string
1335 searching is faster than RE matching and it is possible to limit the
1334 searching is faster than RE matching and it is possible to limit the
1336 search to just the end of the input buffer.
1335 search to just the end of the input buffer.
1337
1336
1338 This method is also useful when you don't want to have to worry about
1337 This method is also useful when you don't want to have to worry about
1339 escaping regular expression characters that you want to match."""
1338 escaping regular expression characters that you want to match."""
1340
1339
1341 if type(pattern_list) in types.StringTypes or pattern_list in (TIMEOUT, EOF):
1340 if type(pattern_list) in types.StringTypes or pattern_list in (TIMEOUT, EOF):
1342 pattern_list = [pattern_list]
1341 pattern_list = [pattern_list]
1343 return self.expect_loop(searcher_string(pattern_list), timeout, searchwindowsize)
1342 return self.expect_loop(searcher_string(pattern_list), timeout, searchwindowsize)
1344
1343
1345 def expect_loop(self, searcher, timeout = -1, searchwindowsize = -1):
1344 def expect_loop(self, searcher, timeout = -1, searchwindowsize = -1):
1346
1345
1347 """This is the common loop used inside expect. The 'searcher' should be
1346 """This is the common loop used inside expect. The 'searcher' should be
1348 an instance of searcher_re or searcher_string, which describes how and what
1347 an instance of searcher_re or searcher_string, which describes how and what
1349 to search for in the input.
1348 to search for in the input.
1350
1349
1351 See expect() for other arguments, return value and exceptions. """
1350 See expect() for other arguments, return value and exceptions. """
1352
1351
1353 self.searcher = searcher
1352 self.searcher = searcher
1354
1353
1355 if timeout == -1:
1354 if timeout == -1:
1356 timeout = self.timeout
1355 timeout = self.timeout
1357 if timeout is not None:
1356 if timeout is not None:
1358 end_time = time.time() + timeout
1357 end_time = time.time() + timeout
1359 if searchwindowsize == -1:
1358 if searchwindowsize == -1:
1360 searchwindowsize = self.searchwindowsize
1359 searchwindowsize = self.searchwindowsize
1361
1360
1362 try:
1361 try:
1363 incoming = self.buffer
1362 incoming = self.buffer
1364 freshlen = len(incoming)
1363 freshlen = len(incoming)
1365 while True: # Keep reading until exception or return.
1364 while True: # Keep reading until exception or return.
1366 index = searcher.search(incoming, freshlen, searchwindowsize)
1365 index = searcher.search(incoming, freshlen, searchwindowsize)
1367 if index >= 0:
1366 if index >= 0:
1368 self.buffer = incoming[searcher.end : ]
1367 self.buffer = incoming[searcher.end : ]
1369 self.before = incoming[ : searcher.start]
1368 self.before = incoming[ : searcher.start]
1370 self.after = incoming[searcher.start : searcher.end]
1369 self.after = incoming[searcher.start : searcher.end]
1371 self.match = searcher.match
1370 self.match = searcher.match
1372 self.match_index = index
1371 self.match_index = index
1373 return self.match_index
1372 return self.match_index
1374 # No match at this point
1373 # No match at this point
1375 if timeout < 0 and timeout is not None:
1374 if timeout < 0 and timeout is not None:
1376 raise TIMEOUT ('Timeout exceeded in expect_any().')
1375 raise TIMEOUT ('Timeout exceeded in expect_any().')
1377 # Still have time left, so read more data
1376 # Still have time left, so read more data
1378 c = self.read_nonblocking (self.maxread, timeout)
1377 c = self.read_nonblocking (self.maxread, timeout)
1379 freshlen = len(c)
1378 freshlen = len(c)
1380 time.sleep (0.0001)
1379 time.sleep (0.0001)
1381 incoming = incoming + c
1380 incoming = incoming + c
1382 if timeout is not None:
1381 if timeout is not None:
1383 timeout = end_time - time.time()
1382 timeout = end_time - time.time()
1384 except EOF, e:
1383 except EOF, e:
1385 self.buffer = ''
1384 self.buffer = ''
1386 self.before = incoming
1385 self.before = incoming
1387 self.after = EOF
1386 self.after = EOF
1388 index = searcher.eof_index
1387 index = searcher.eof_index
1389 if index >= 0:
1388 if index >= 0:
1390 self.match = EOF
1389 self.match = EOF
1391 self.match_index = index
1390 self.match_index = index
1392 return self.match_index
1391 return self.match_index
1393 else:
1392 else:
1394 self.match = None
1393 self.match = None
1395 self.match_index = None
1394 self.match_index = None
1396 raise EOF (str(e) + '\n' + str(self))
1395 raise EOF (str(e) + '\n' + str(self))
1397 except TIMEOUT, e:
1396 except TIMEOUT, e:
1398 self.buffer = incoming
1397 self.buffer = incoming
1399 self.before = incoming
1398 self.before = incoming
1400 self.after = TIMEOUT
1399 self.after = TIMEOUT
1401 index = searcher.timeout_index
1400 index = searcher.timeout_index
1402 if index >= 0:
1401 if index >= 0:
1403 self.match = TIMEOUT
1402 self.match = TIMEOUT
1404 self.match_index = index
1403 self.match_index = index
1405 return self.match_index
1404 return self.match_index
1406 else:
1405 else:
1407 self.match = None
1406 self.match = None
1408 self.match_index = None
1407 self.match_index = None
1409 raise TIMEOUT (str(e) + '\n' + str(self))
1408 raise TIMEOUT (str(e) + '\n' + str(self))
1410 except:
1409 except:
1411 self.before = incoming
1410 self.before = incoming
1412 self.after = None
1411 self.after = None
1413 self.match = None
1412 self.match = None
1414 self.match_index = None
1413 self.match_index = None
1415 raise
1414 raise
1416
1415
1417 def getwinsize(self):
1416 def getwinsize(self):
1418
1417
1419 """This returns the terminal window size of the child tty. The return
1418 """This returns the terminal window size of the child tty. The return
1420 value is a tuple of (rows, cols). """
1419 value is a tuple of (rows, cols). """
1421
1420
1422 TIOCGWINSZ = getattr(termios, 'TIOCGWINSZ', 1074295912L)
1421 TIOCGWINSZ = getattr(termios, 'TIOCGWINSZ', 1074295912L)
1423 s = struct.pack('HHHH', 0, 0, 0, 0)
1422 s = struct.pack('HHHH', 0, 0, 0, 0)
1424 x = fcntl.ioctl(self.fileno(), TIOCGWINSZ, s)
1423 x = fcntl.ioctl(self.fileno(), TIOCGWINSZ, s)
1425 return struct.unpack('HHHH', x)[0:2]
1424 return struct.unpack('HHHH', x)[0:2]
1426
1425
1427 def setwinsize(self, r, c):
1426 def setwinsize(self, r, c):
1428
1427
1429 """This sets the terminal window size of the child tty. This will cause
1428 """This sets the terminal window size of the child tty. This will cause
1430 a SIGWINCH signal to be sent to the child. This does not change the
1429 a SIGWINCH signal to be sent to the child. This does not change the
1431 physical window size. It changes the size reported to TTY-aware
1430 physical window size. It changes the size reported to TTY-aware
1432 applications like vi or curses -- applications that respond to the
1431 applications like vi or curses -- applications that respond to the
1433 SIGWINCH signal. """
1432 SIGWINCH signal. """
1434
1433
1435 # Check for buggy platforms. Some Python versions on some platforms
1434 # Check for buggy platforms. Some Python versions on some platforms
1436 # (notably OSF1 Alpha and RedHat 7.1) truncate the value for
1435 # (notably OSF1 Alpha and RedHat 7.1) truncate the value for
1437 # termios.TIOCSWINSZ. It is not clear why this happens.
1436 # termios.TIOCSWINSZ. It is not clear why this happens.
1438 # These platforms don't seem to handle the signed int very well;
1437 # These platforms don't seem to handle the signed int very well;
1439 # yet other platforms like OpenBSD have a large negative value for
1438 # yet other platforms like OpenBSD have a large negative value for
1440 # TIOCSWINSZ and they don't have a truncate problem.
1439 # TIOCSWINSZ and they don't have a truncate problem.
1441 # Newer versions of Linux have totally different values for TIOCSWINSZ.
1440 # Newer versions of Linux have totally different values for TIOCSWINSZ.
1442 # Note that this fix is a hack.
1441 # Note that this fix is a hack.
1443 TIOCSWINSZ = getattr(termios, 'TIOCSWINSZ', -2146929561)
1442 TIOCSWINSZ = getattr(termios, 'TIOCSWINSZ', -2146929561)
1444 if TIOCSWINSZ == 2148037735L: # L is not required in Python >= 2.2.
1443 if TIOCSWINSZ == 2148037735L: # L is not required in Python >= 2.2.
1445 TIOCSWINSZ = -2146929561 # Same bits, but with sign.
1444 TIOCSWINSZ = -2146929561 # Same bits, but with sign.
1446 # Note, assume ws_xpixel and ws_ypixel are zero.
1445 # Note, assume ws_xpixel and ws_ypixel are zero.
1447 s = struct.pack('HHHH', r, c, 0, 0)
1446 s = struct.pack('HHHH', r, c, 0, 0)
1448 fcntl.ioctl(self.fileno(), TIOCSWINSZ, s)
1447 fcntl.ioctl(self.fileno(), TIOCSWINSZ, s)
1449
1448
1450 def interact(self, escape_character = chr(29), input_filter = None, output_filter = None):
1449 def interact(self, escape_character = chr(29), input_filter = None, output_filter = None):
1451
1450
1452 """This gives control of the child process to the interactive user (the
1451 """This gives control of the child process to the interactive user (the
1453 human at the keyboard). Keystrokes are sent to the child process, and
1452 human at the keyboard). Keystrokes are sent to the child process, and
1454 the stdout and stderr output of the child process is printed. This
1453 the stdout and stderr output of the child process is printed. This
1455 simply echos the child stdout and child stderr to the real stdout and
1454 simply echos the child stdout and child stderr to the real stdout and
1456 it echos the real stdin to the child stdin. When the user types the
1455 it echos the real stdin to the child stdin. When the user types the
1457 escape_character this method will stop. The default for
1456 escape_character this method will stop. The default for
1458 escape_character is ^]. This should not be confused with ASCII 27 --
1457 escape_character is ^]. This should not be confused with ASCII 27 --
1459 the ESC character. ASCII 29 was chosen for historical merit because
1458 the ESC character. ASCII 29 was chosen for historical merit because
1460 this is the character used by 'telnet' as the escape character. The
1459 this is the character used by 'telnet' as the escape character. The
1461 escape_character will not be sent to the child process.
1460 escape_character will not be sent to the child process.
1462
1461
1463 You may pass in optional input and output filter functions. These
1462 You may pass in optional input and output filter functions. These
1464 functions should take a string and return a string. The output_filter
1463 functions should take a string and return a string. The output_filter
1465 will be passed all the output from the child process. The input_filter
1464 will be passed all the output from the child process. The input_filter
1466 will be passed all the keyboard input from the user. The input_filter
1465 will be passed all the keyboard input from the user. The input_filter
1467 is run BEFORE the check for the escape_character.
1466 is run BEFORE the check for the escape_character.
1468
1467
1469 Note that if you change the window size of the parent the SIGWINCH
1468 Note that if you change the window size of the parent the SIGWINCH
1470 signal will not be passed through to the child. If you want the child
1469 signal will not be passed through to the child. If you want the child
1471 window size to change when the parent's window size changes then do
1470 window size to change when the parent's window size changes then do
1472 something like the following example::
1471 something like the following example::
1473
1472
1474 import pexpect, struct, fcntl, termios, signal, sys
1473 import pexpect, struct, fcntl, termios, signal, sys
1475 def sigwinch_passthrough (sig, data):
1474 def sigwinch_passthrough (sig, data):
1476 s = struct.pack("HHHH", 0, 0, 0, 0)
1475 s = struct.pack("HHHH", 0, 0, 0, 0)
1477 a = struct.unpack('hhhh', fcntl.ioctl(sys.stdout.fileno(), termios.TIOCGWINSZ , s))
1476 a = struct.unpack('hhhh', fcntl.ioctl(sys.stdout.fileno(), termios.TIOCGWINSZ , s))
1478 global p
1477 global p
1479 p.setwinsize(a[0],a[1])
1478 p.setwinsize(a[0],a[1])
1480 p = pexpect.spawn('/bin/bash') # Note this is global and used in sigwinch_passthrough.
1479 p = pexpect.spawn('/bin/bash') # Note this is global and used in sigwinch_passthrough.
1481 signal.signal(signal.SIGWINCH, sigwinch_passthrough)
1480 signal.signal(signal.SIGWINCH, sigwinch_passthrough)
1482 p.interact()
1481 p.interact()
1483 """
1482 """
1484
1483
1485 # Flush the buffer.
1484 # Flush the buffer.
1486 self.stdout.write (self.buffer)
1485 self.stdout.write (self.buffer)
1487 self.stdout.flush()
1486 self.stdout.flush()
1488 self.buffer = ''
1487 self.buffer = ''
1489 mode = tty.tcgetattr(self.STDIN_FILENO)
1488 mode = tty.tcgetattr(self.STDIN_FILENO)
1490 tty.setraw(self.STDIN_FILENO)
1489 tty.setraw(self.STDIN_FILENO)
1491 try:
1490 try:
1492 self.__interact_copy(escape_character, input_filter, output_filter)
1491 self.__interact_copy(escape_character, input_filter, output_filter)
1493 finally:
1492 finally:
1494 tty.tcsetattr(self.STDIN_FILENO, tty.TCSAFLUSH, mode)
1493 tty.tcsetattr(self.STDIN_FILENO, tty.TCSAFLUSH, mode)
1495
1494
1496 def __interact_writen(self, fd, data):
1495 def __interact_writen(self, fd, data):
1497
1496
1498 """This is used by the interact() method.
1497 """This is used by the interact() method.
1499 """
1498 """
1500
1499
1501 while data != '' and self.isalive():
1500 while data != '' and self.isalive():
1502 n = os.write(fd, data)
1501 n = os.write(fd, data)
1503 data = data[n:]
1502 data = data[n:]
1504
1503
1505 def __interact_read(self, fd):
1504 def __interact_read(self, fd):
1506
1505
1507 """This is used by the interact() method.
1506 """This is used by the interact() method.
1508 """
1507 """
1509
1508
1510 return os.read(fd, 1000)
1509 return os.read(fd, 1000)
1511
1510
1512 def __interact_copy(self, escape_character = None, input_filter = None, output_filter = None):
1511 def __interact_copy(self, escape_character = None, input_filter = None, output_filter = None):
1513
1512
1514 """This is used by the interact() method.
1513 """This is used by the interact() method.
1515 """
1514 """
1516
1515
1517 while self.isalive():
1516 while self.isalive():
1518 r,w,e = self.__select([self.child_fd, self.STDIN_FILENO], [], [])
1517 r,w,e = self.__select([self.child_fd, self.STDIN_FILENO], [], [])
1519 if self.child_fd in r:
1518 if self.child_fd in r:
1520 data = self.__interact_read(self.child_fd)
1519 data = self.__interact_read(self.child_fd)
1521 if output_filter: data = output_filter(data)
1520 if output_filter: data = output_filter(data)
1522 if self.logfile is not None:
1521 if self.logfile is not None:
1523 self.logfile.write (data)
1522 self.logfile.write (data)
1524 self.logfile.flush()
1523 self.logfile.flush()
1525 os.write(self.STDOUT_FILENO, data)
1524 os.write(self.STDOUT_FILENO, data)
1526 if self.STDIN_FILENO in r:
1525 if self.STDIN_FILENO in r:
1527 data = self.__interact_read(self.STDIN_FILENO)
1526 data = self.__interact_read(self.STDIN_FILENO)
1528 if input_filter: data = input_filter(data)
1527 if input_filter: data = input_filter(data)
1529 i = data.rfind(escape_character)
1528 i = data.rfind(escape_character)
1530 if i != -1:
1529 if i != -1:
1531 data = data[:i]
1530 data = data[:i]
1532 self.__interact_writen(self.child_fd, data)
1531 self.__interact_writen(self.child_fd, data)
1533 break
1532 break
1534 self.__interact_writen(self.child_fd, data)
1533 self.__interact_writen(self.child_fd, data)
1535
1534
1536 def __select (self, iwtd, owtd, ewtd, timeout=None):
1535 def __select (self, iwtd, owtd, ewtd, timeout=None):
1537
1536
1538 """This is a wrapper around select.select() that ignores signals. If
1537 """This is a wrapper around select.select() that ignores signals. If
1539 select.select raises a select.error exception and errno is an EINTR
1538 select.select raises a select.error exception and errno is an EINTR
1540 error then it is ignored. Mainly this is used to ignore sigwinch
1539 error then it is ignored. Mainly this is used to ignore sigwinch
1541 (terminal resize). """
1540 (terminal resize). """
1542
1541
1543 # if select() is interrupted by a signal (errno==EINTR) then
1542 # if select() is interrupted by a signal (errno==EINTR) then
1544 # we loop back and enter the select() again.
1543 # we loop back and enter the select() again.
1545 if timeout is not None:
1544 if timeout is not None:
1546 end_time = time.time() + timeout
1545 end_time = time.time() + timeout
1547 while True:
1546 while True:
1548 try:
1547 try:
1549 return select.select (iwtd, owtd, ewtd, timeout)
1548 return select.select (iwtd, owtd, ewtd, timeout)
1550 except select.error, e:
1549 except select.error, e:
1551 if e[0] == errno.EINTR:
1550 if e[0] == errno.EINTR:
1552 # if we loop back we have to subtract the amount of time we already waited.
1551 # if we loop back we have to subtract the amount of time we already waited.
1553 if timeout is not None:
1552 if timeout is not None:
1554 timeout = end_time - time.time()
1553 timeout = end_time - time.time()
1555 if timeout < 0:
1554 if timeout < 0:
1556 return ([],[],[])
1555 return ([],[],[])
1557 else: # something else caused the select.error, so this really is an exception
1556 else: # something else caused the select.error, so this really is an exception
1558 raise
1557 raise
1559
1558
1560 ##############################################################################
1559 ##############################################################################
1561 # The following methods are no longer supported or allowed.
1560 # The following methods are no longer supported or allowed.
1562
1561
1563 def setmaxread (self, maxread):
1562 def setmaxread (self, maxread):
1564
1563
1565 """This method is no longer supported or allowed. I don't like getters
1564 """This method is no longer supported or allowed. I don't like getters
1566 and setters without a good reason. """
1565 and setters without a good reason. """
1567
1566
1568 raise ExceptionPexpect ('This method is no longer supported or allowed. Just assign a value to the maxread member variable.')
1567 raise ExceptionPexpect ('This method is no longer supported or allowed. Just assign a value to the maxread member variable.')
1569
1568
1570 def setlog (self, fileobject):
1569 def setlog (self, fileobject):
1571
1570
1572 """This method is no longer supported or allowed.
1571 """This method is no longer supported or allowed.
1573 """
1572 """
1574
1573
1575 raise ExceptionPexpect ('This method is no longer supported or allowed. Just assign a value to the logfile member variable.')
1574 raise ExceptionPexpect ('This method is no longer supported or allowed. Just assign a value to the logfile member variable.')
1576
1575
1577 ##############################################################################
1576 ##############################################################################
1578 # End of spawn class
1577 # End of spawn class
1579 ##############################################################################
1578 ##############################################################################
1580
1579
1581 class searcher_string (object):
1580 class searcher_string (object):
1582
1581
1583 """This is a plain string search helper for the spawn.expect_any() method.
1582 """This is a plain string search helper for the spawn.expect_any() method.
1584
1583
1585 Attributes:
1584 Attributes:
1586
1585
1587 eof_index - index of EOF, or -1
1586 eof_index - index of EOF, or -1
1588 timeout_index - index of TIMEOUT, or -1
1587 timeout_index - index of TIMEOUT, or -1
1589
1588
1590 After a successful match by the search() method the following attributes
1589 After a successful match by the search() method the following attributes
1591 are available:
1590 are available:
1592
1591
1593 start - index into the buffer, first byte of match
1592 start - index into the buffer, first byte of match
1594 end - index into the buffer, first byte after match
1593 end - index into the buffer, first byte after match
1595 match - the matching string itself
1594 match - the matching string itself
1596 """
1595 """
1597
1596
1598 def __init__(self, strings):
1597 def __init__(self, strings):
1599
1598
1600 """This creates an instance of searcher_string. This argument 'strings'
1599 """This creates an instance of searcher_string. This argument 'strings'
1601 may be a list; a sequence of strings; or the EOF or TIMEOUT types. """
1600 may be a list; a sequence of strings; or the EOF or TIMEOUT types. """
1602
1601
1603 self.eof_index = -1
1602 self.eof_index = -1
1604 self.timeout_index = -1
1603 self.timeout_index = -1
1605 self._strings = []
1604 self._strings = []
1606 for n, s in zip(range(len(strings)), strings):
1605 for n, s in zip(range(len(strings)), strings):
1607 if s is EOF:
1606 if s is EOF:
1608 self.eof_index = n
1607 self.eof_index = n
1609 continue
1608 continue
1610 if s is TIMEOUT:
1609 if s is TIMEOUT:
1611 self.timeout_index = n
1610 self.timeout_index = n
1612 continue
1611 continue
1613 self._strings.append((n, s))
1612 self._strings.append((n, s))
1614
1613
1615 def __str__(self):
1614 def __str__(self):
1616
1615
1617 """This returns a human-readable string that represents the state of
1616 """This returns a human-readable string that represents the state of
1618 the object."""
1617 the object."""
1619
1618
1620 ss = [ (ns[0],' %d: "%s"' % ns) for ns in self._strings ]
1619 ss = [ (ns[0],' %d: "%s"' % ns) for ns in self._strings ]
1621 ss.append((-1,'searcher_string:'))
1620 ss.append((-1,'searcher_string:'))
1622 if self.eof_index >= 0:
1621 if self.eof_index >= 0:
1623 ss.append ((self.eof_index,' %d: EOF' % self.eof_index))
1622 ss.append ((self.eof_index,' %d: EOF' % self.eof_index))
1624 if self.timeout_index >= 0:
1623 if self.timeout_index >= 0:
1625 ss.append ((self.timeout_index,' %d: TIMEOUT' % self.timeout_index))
1624 ss.append ((self.timeout_index,' %d: TIMEOUT' % self.timeout_index))
1626 ss.sort()
1625 ss.sort()
1627 ss = zip(*ss)[1]
1626 ss = zip(*ss)[1]
1628 return '\n'.join(ss)
1627 return '\n'.join(ss)
1629
1628
1630 def search(self, buffer, freshlen, searchwindowsize=None):
1629 def search(self, buffer, freshlen, searchwindowsize=None):
1631
1630
1632 """This searches 'buffer' for the first occurence of one of the search
1631 """This searches 'buffer' for the first occurence of one of the search
1633 strings. 'freshlen' must indicate the number of bytes at the end of
1632 strings. 'freshlen' must indicate the number of bytes at the end of
1634 'buffer' which have not been searched before. It helps to avoid
1633 'buffer' which have not been searched before. It helps to avoid
1635 searching the same, possibly big, buffer over and over again.
1634 searching the same, possibly big, buffer over and over again.
1636
1635
1637 See class spawn for the 'searchwindowsize' argument.
1636 See class spawn for the 'searchwindowsize' argument.
1638
1637
1639 If there is a match this returns the index of that string, and sets
1638 If there is a match this returns the index of that string, and sets
1640 'start', 'end' and 'match'. Otherwise, this returns -1. """
1639 'start', 'end' and 'match'. Otherwise, this returns -1. """
1641
1640
1642 absurd_match = len(buffer)
1641 absurd_match = len(buffer)
1643 first_match = absurd_match
1642 first_match = absurd_match
1644
1643
1645 # 'freshlen' helps a lot here. Further optimizations could
1644 # 'freshlen' helps a lot here. Further optimizations could
1646 # possibly include:
1645 # possibly include:
1647 #
1646 #
1648 # using something like the Boyer-Moore Fast String Searching
1647 # using something like the Boyer-Moore Fast String Searching
1649 # Algorithm; pre-compiling the search through a list of
1648 # Algorithm; pre-compiling the search through a list of
1650 # strings into something that can scan the input once to
1649 # strings into something that can scan the input once to
1651 # search for all N strings; realize that if we search for
1650 # search for all N strings; realize that if we search for
1652 # ['bar', 'baz'] and the input is '...foo' we need not bother
1651 # ['bar', 'baz'] and the input is '...foo' we need not bother
1653 # rescanning until we've read three more bytes.
1652 # rescanning until we've read three more bytes.
1654 #
1653 #
1655 # Sadly, I don't know enough about this interesting topic. /grahn
1654 # Sadly, I don't know enough about this interesting topic. /grahn
1656
1655
1657 for index, s in self._strings:
1656 for index, s in self._strings:
1658 if searchwindowsize is None:
1657 if searchwindowsize is None:
1659 # the match, if any, can only be in the fresh data,
1658 # the match, if any, can only be in the fresh data,
1660 # or at the very end of the old data
1659 # or at the very end of the old data
1661 offset = -(freshlen+len(s))
1660 offset = -(freshlen+len(s))
1662 else:
1661 else:
1663 # better obey searchwindowsize
1662 # better obey searchwindowsize
1664 offset = -searchwindowsize
1663 offset = -searchwindowsize
1665 n = buffer.find(s, offset)
1664 n = buffer.find(s, offset)
1666 if n >= 0 and n < first_match:
1665 if n >= 0 and n < first_match:
1667 first_match = n
1666 first_match = n
1668 best_index, best_match = index, s
1667 best_index, best_match = index, s
1669 if first_match == absurd_match:
1668 if first_match == absurd_match:
1670 return -1
1669 return -1
1671 self.match = best_match
1670 self.match = best_match
1672 self.start = first_match
1671 self.start = first_match
1673 self.end = self.start + len(self.match)
1672 self.end = self.start + len(self.match)
1674 return best_index
1673 return best_index
1675
1674
1676 class searcher_re (object):
1675 class searcher_re (object):
1677
1676
1678 """This is regular expression string search helper for the
1677 """This is regular expression string search helper for the
1679 spawn.expect_any() method.
1678 spawn.expect_any() method.
1680
1679
1681 Attributes:
1680 Attributes:
1682
1681
1683 eof_index - index of EOF, or -1
1682 eof_index - index of EOF, or -1
1684 timeout_index - index of TIMEOUT, or -1
1683 timeout_index - index of TIMEOUT, or -1
1685
1684
1686 After a successful match by the search() method the following attributes
1685 After a successful match by the search() method the following attributes
1687 are available:
1686 are available:
1688
1687
1689 start - index into the buffer, first byte of match
1688 start - index into the buffer, first byte of match
1690 end - index into the buffer, first byte after match
1689 end - index into the buffer, first byte after match
1691 match - the re.match object returned by a succesful re.search
1690 match - the re.match object returned by a succesful re.search
1692
1691
1693 """
1692 """
1694
1693
1695 def __init__(self, patterns):
1694 def __init__(self, patterns):
1696
1695
1697 """This creates an instance that searches for 'patterns' Where
1696 """This creates an instance that searches for 'patterns' Where
1698 'patterns' may be a list or other sequence of compiled regular
1697 'patterns' may be a list or other sequence of compiled regular
1699 expressions, or the EOF or TIMEOUT types."""
1698 expressions, or the EOF or TIMEOUT types."""
1700
1699
1701 self.eof_index = -1
1700 self.eof_index = -1
1702 self.timeout_index = -1
1701 self.timeout_index = -1
1703 self._searches = []
1702 self._searches = []
1704 for n, s in zip(range(len(patterns)), patterns):
1703 for n, s in zip(range(len(patterns)), patterns):
1705 if s is EOF:
1704 if s is EOF:
1706 self.eof_index = n
1705 self.eof_index = n
1707 continue
1706 continue
1708 if s is TIMEOUT:
1707 if s is TIMEOUT:
1709 self.timeout_index = n
1708 self.timeout_index = n
1710 continue
1709 continue
1711 self._searches.append((n, s))
1710 self._searches.append((n, s))
1712
1711
1713 def __str__(self):
1712 def __str__(self):
1714
1713
1715 """This returns a human-readable string that represents the state of
1714 """This returns a human-readable string that represents the state of
1716 the object."""
1715 the object."""
1717
1716
1718 ss = [ (n,' %d: re.compile("%s")' % (n,str(s.pattern))) for n,s in self._searches]
1717 ss = [ (n,' %d: re.compile("%s")' % (n,str(s.pattern))) for n,s in self._searches]
1719 ss.append((-1,'searcher_re:'))
1718 ss.append((-1,'searcher_re:'))
1720 if self.eof_index >= 0:
1719 if self.eof_index >= 0:
1721 ss.append ((self.eof_index,' %d: EOF' % self.eof_index))
1720 ss.append ((self.eof_index,' %d: EOF' % self.eof_index))
1722 if self.timeout_index >= 0:
1721 if self.timeout_index >= 0:
1723 ss.append ((self.timeout_index,' %d: TIMEOUT' % self.timeout_index))
1722 ss.append ((self.timeout_index,' %d: TIMEOUT' % self.timeout_index))
1724 ss.sort()
1723 ss.sort()
1725 ss = zip(*ss)[1]
1724 ss = zip(*ss)[1]
1726 return '\n'.join(ss)
1725 return '\n'.join(ss)
1727
1726
1728 def search(self, buffer, freshlen, searchwindowsize=None):
1727 def search(self, buffer, freshlen, searchwindowsize=None):
1729
1728
1730 """This searches 'buffer' for the first occurence of one of the regular
1729 """This searches 'buffer' for the first occurence of one of the regular
1731 expressions. 'freshlen' must indicate the number of bytes at the end of
1730 expressions. 'freshlen' must indicate the number of bytes at the end of
1732 'buffer' which have not been searched before.
1731 'buffer' which have not been searched before.
1733
1732
1734 See class spawn for the 'searchwindowsize' argument.
1733 See class spawn for the 'searchwindowsize' argument.
1735
1734
1736 If there is a match this returns the index of that string, and sets
1735 If there is a match this returns the index of that string, and sets
1737 'start', 'end' and 'match'. Otherwise, returns -1."""
1736 'start', 'end' and 'match'. Otherwise, returns -1."""
1738
1737
1739 absurd_match = len(buffer)
1738 absurd_match = len(buffer)
1740 first_match = absurd_match
1739 first_match = absurd_match
1741 # 'freshlen' doesn't help here -- we cannot predict the
1740 # 'freshlen' doesn't help here -- we cannot predict the
1742 # length of a match, and the re module provides no help.
1741 # length of a match, and the re module provides no help.
1743 if searchwindowsize is None:
1742 if searchwindowsize is None:
1744 searchstart = 0
1743 searchstart = 0
1745 else:
1744 else:
1746 searchstart = max(0, len(buffer)-searchwindowsize)
1745 searchstart = max(0, len(buffer)-searchwindowsize)
1747 for index, s in self._searches:
1746 for index, s in self._searches:
1748 match = s.search(buffer, searchstart)
1747 match = s.search(buffer, searchstart)
1749 if match is None:
1748 if match is None:
1750 continue
1749 continue
1751 n = match.start()
1750 n = match.start()
1752 if n < first_match:
1751 if n < first_match:
1753 first_match = n
1752 first_match = n
1754 the_match = match
1753 the_match = match
1755 best_index = index
1754 best_index = index
1756 if first_match == absurd_match:
1755 if first_match == absurd_match:
1757 return -1
1756 return -1
1758 self.start = first_match
1757 self.start = first_match
1759 self.match = the_match
1758 self.match = the_match
1760 self.end = self.match.end()
1759 self.end = self.match.end()
1761 return best_index
1760 return best_index
1762
1761
1763 def which (filename):
1762 def which (filename):
1764
1763
1765 """This takes a given filename; tries to find it in the environment path;
1764 """This takes a given filename; tries to find it in the environment path;
1766 then checks if it is executable. This returns the full path to the filename
1765 then checks if it is executable. This returns the full path to the filename
1767 if found and executable. Otherwise this returns None."""
1766 if found and executable. Otherwise this returns None."""
1768
1767
1769 # Special case where filename already contains a path.
1768 # Special case where filename already contains a path.
1770 if os.path.dirname(filename) != '':
1769 if os.path.dirname(filename) != '':
1771 if os.access (filename, os.X_OK):
1770 if os.access (filename, os.X_OK):
1772 return filename
1771 return filename
1773
1772
1774 if not os.environ.has_key('PATH') or os.environ['PATH'] == '':
1773 if not os.environ.has_key('PATH') or os.environ['PATH'] == '':
1775 p = os.defpath
1774 p = os.defpath
1776 else:
1775 else:
1777 p = os.environ['PATH']
1776 p = os.environ['PATH']
1778
1777
1779 # Oddly enough this was the one line that made Pexpect
1778 # Oddly enough this was the one line that made Pexpect
1780 # incompatible with Python 1.5.2.
1779 # incompatible with Python 1.5.2.
1781 #pathlist = p.split (os.pathsep)
1780 pathlist = p.split(os.pathsep)
1782 pathlist = string.split (p, os.pathsep)
1783
1781
1784 for path in pathlist:
1782 for path in pathlist:
1785 f = os.path.join(path, filename)
1783 f = os.path.join(path, filename)
1786 if os.access(f, os.X_OK):
1784 if os.access(f, os.X_OK):
1787 return f
1785 return f
1788 return None
1786 return None
1789
1787
1790 def split_command_line(command_line):
1788 def split_command_line(command_line):
1791
1789
1792 """This splits a command line into a list of arguments. It splits arguments
1790 """This splits a command line into a list of arguments. It splits arguments
1793 on spaces, but handles embedded quotes, doublequotes, and escaped
1791 on spaces, but handles embedded quotes, doublequotes, and escaped
1794 characters. It's impossible to do this with a regular expression, so I
1792 characters. It's impossible to do this with a regular expression, so I
1795 wrote a little state machine to parse the command line. """
1793 wrote a little state machine to parse the command line. """
1796
1794
1797 arg_list = []
1795 arg_list = []
1798 arg = ''
1796 arg = ''
1799
1797
1800 # Constants to name the states we can be in.
1798 # Constants to name the states we can be in.
1801 state_basic = 0
1799 state_basic = 0
1802 state_esc = 1
1800 state_esc = 1
1803 state_singlequote = 2
1801 state_singlequote = 2
1804 state_doublequote = 3
1802 state_doublequote = 3
1805 state_whitespace = 4 # The state of consuming whitespace between commands.
1803 state_whitespace = 4 # The state of consuming whitespace between commands.
1806 state = state_basic
1804 state = state_basic
1807
1805
1808 for c in command_line:
1806 for c in command_line:
1809 if state == state_basic or state == state_whitespace:
1807 if state == state_basic or state == state_whitespace:
1810 if c == '\\': # Escape the next character
1808 if c == '\\': # Escape the next character
1811 state = state_esc
1809 state = state_esc
1812 elif c == r"'": # Handle single quote
1810 elif c == r"'": # Handle single quote
1813 state = state_singlequote
1811 state = state_singlequote
1814 elif c == r'"': # Handle double quote
1812 elif c == r'"': # Handle double quote
1815 state = state_doublequote
1813 state = state_doublequote
1816 elif c.isspace():
1814 elif c.isspace():
1817 # Add arg to arg_list if we aren't in the middle of whitespace.
1815 # Add arg to arg_list if we aren't in the middle of whitespace.
1818 if state == state_whitespace:
1816 if state == state_whitespace:
1819 None # Do nothing.
1817 None # Do nothing.
1820 else:
1818 else:
1821 arg_list.append(arg)
1819 arg_list.append(arg)
1822 arg = ''
1820 arg = ''
1823 state = state_whitespace
1821 state = state_whitespace
1824 else:
1822 else:
1825 arg = arg + c
1823 arg = arg + c
1826 state = state_basic
1824 state = state_basic
1827 elif state == state_esc:
1825 elif state == state_esc:
1828 arg = arg + c
1826 arg = arg + c
1829 state = state_basic
1827 state = state_basic
1830 elif state == state_singlequote:
1828 elif state == state_singlequote:
1831 if c == r"'":
1829 if c == r"'":
1832 state = state_basic
1830 state = state_basic
1833 else:
1831 else:
1834 arg = arg + c
1832 arg = arg + c
1835 elif state == state_doublequote:
1833 elif state == state_doublequote:
1836 if c == r'"':
1834 if c == r'"':
1837 state = state_basic
1835 state = state_basic
1838 else:
1836 else:
1839 arg = arg + c
1837 arg = arg + c
1840
1838
1841 if arg != '':
1839 if arg != '':
1842 arg_list.append(arg)
1840 arg_list.append(arg)
1843 return arg_list
1841 return arg_list
1844
1842
1845 # vi:ts=4:sw=4:expandtab:ft=python:
1843 # vi:ts=4:sw=4:expandtab:ft=python:
General Comments 0
You need to be logged in to leave comments. Login now