##// 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 1 # -*- coding: utf-8 -*-
2 2 """Main IPython class."""
3 3
4 4 #-----------------------------------------------------------------------------
5 5 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
6 6 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
7 7 # Copyright (C) 2008-2010 The IPython Development Team
8 8 #
9 9 # Distributed under the terms of the BSD License. The full license is in
10 10 # the file COPYING, distributed as part of this software.
11 11 #-----------------------------------------------------------------------------
12 12
13 13 #-----------------------------------------------------------------------------
14 14 # Imports
15 15 #-----------------------------------------------------------------------------
16 16
17 17 from __future__ import with_statement
18 18 from __future__ import absolute_import
19 19
20 20 import __builtin__
21 21 import __future__
22 22 import abc
23 23 import atexit
24 24 import codeop
25 import exceptions
26 import new
27 25 import os
28 26 import re
29 import string
30 27 import sys
31 28 import tempfile
29 import types
32 30 from contextlib import nested
33 31
34 32 from IPython.config.configurable import Configurable
35 33 from IPython.core import debugger, oinspect
36 34 from IPython.core import history as ipcorehist
37 35 from IPython.core import page
38 36 from IPython.core import prefilter
39 37 from IPython.core import shadowns
40 38 from IPython.core import ultratb
41 39 from IPython.core.alias import AliasManager
42 40 from IPython.core.builtin_trap import BuiltinTrap
43 41 from IPython.core.compilerop import CachingCompiler
44 42 from IPython.core.display_trap import DisplayTrap
45 43 from IPython.core.displayhook import DisplayHook
46 44 from IPython.core.error import TryNext, UsageError
47 45 from IPython.core.extensions import ExtensionManager
48 46 from IPython.core.fakemodule import FakeModule, init_fakemod_dict
49 47 from IPython.core.history import HistoryManager
50 48 from IPython.core.inputlist import InputList
51 49 from IPython.core.inputsplitter import IPythonInputSplitter
52 50 from IPython.core.logger import Logger
53 51 from IPython.core.magic import Magic
54 52 from IPython.core.payload import PayloadManager
55 53 from IPython.core.plugin import PluginManager
56 54 from IPython.core.prefilter import PrefilterManager, ESC_MAGIC
57 55 from IPython.external.Itpl import ItplNS
58 56 from IPython.utils import PyColorize
59 57 from IPython.utils import io
60 58 from IPython.utils import pickleshare
61 59 from IPython.utils.doctestreload import doctest_reload
62 60 from IPython.utils.io import ask_yes_no, rprint
63 61 from IPython.utils.ipstruct import Struct
64 62 from IPython.utils.path import get_home_dir, get_ipython_dir, HomeDirError
65 63 from IPython.utils.process import system, getoutput
66 64 from IPython.utils.strdispatch import StrDispatch
67 65 from IPython.utils.syspathcontext import prepended_to_syspath
68 66 from IPython.utils.text import num_ini_spaces, format_screen, LSString, SList
69 67 from IPython.utils.traitlets import (Int, Str, CBool, CaselessStrEnum, Enum,
70 68 List, Unicode, Instance, Type)
71 69 from IPython.utils.warn import warn, error, fatal
72 70 import IPython.core.hooks
73 71
74 72 #-----------------------------------------------------------------------------
75 73 # Globals
76 74 #-----------------------------------------------------------------------------
77 75
78 76 # compiled regexps for autoindent management
79 77 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
80 78
81 79 #-----------------------------------------------------------------------------
82 80 # Utilities
83 81 #-----------------------------------------------------------------------------
84 82
85 83 # store the builtin raw_input globally, and use this always, in case user code
86 84 # overwrites it (like wx.py.PyShell does)
87 85 raw_input_original = raw_input
88 86
89 87 def softspace(file, newvalue):
90 88 """Copied from code.py, to remove the dependency"""
91 89
92 90 oldvalue = 0
93 91 try:
94 92 oldvalue = file.softspace
95 93 except AttributeError:
96 94 pass
97 95 try:
98 96 file.softspace = newvalue
99 97 except (AttributeError, TypeError):
100 98 # "attribute-less object" or "read-only attributes"
101 99 pass
102 100 return oldvalue
103 101
104 102
105 103 def no_op(*a, **kw): pass
106 104
107 class SpaceInInput(exceptions.Exception): pass
105 class SpaceInInput(Exception): pass
108 106
109 107 class Bunch: pass
110 108
111 109
112 110 def get_default_colors():
113 111 if sys.platform=='darwin':
114 112 return "LightBG"
115 113 elif os.name=='nt':
116 114 return 'Linux'
117 115 else:
118 116 return 'Linux'
119 117
120 118
121 119 class SeparateStr(Str):
122 120 """A Str subclass to validate separate_in, separate_out, etc.
123 121
124 122 This is a Str based trait that converts '0'->'' and '\\n'->'\n'.
125 123 """
126 124
127 125 def validate(self, obj, value):
128 126 if value == '0': value = ''
129 127 value = value.replace('\\n','\n')
130 128 return super(SeparateStr, self).validate(obj, value)
131 129
132 130 class MultipleInstanceError(Exception):
133 131 pass
134 132
135 133
136 134 #-----------------------------------------------------------------------------
137 135 # Main IPython class
138 136 #-----------------------------------------------------------------------------
139 137
140 138 class InteractiveShell(Configurable, Magic):
141 139 """An enhanced, interactive shell for Python."""
142 140
143 141 _instance = None
144 142 autocall = Enum((0,1,2), default_value=1, config=True)
145 143 # TODO: remove all autoindent logic and put into frontends.
146 144 # We can't do this yet because even runlines uses the autoindent.
147 145 autoindent = CBool(True, config=True)
148 146 automagic = CBool(True, config=True)
149 147 cache_size = Int(1000, config=True)
150 148 color_info = CBool(True, config=True)
151 149 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
152 150 default_value=get_default_colors(), config=True)
153 151 debug = CBool(False, config=True)
154 152 deep_reload = CBool(False, config=True)
155 153 displayhook_class = Type(DisplayHook)
156 154 exit_now = CBool(False)
157 155 # Monotonically increasing execution counter
158 156 execution_count = Int(1)
159 157 filename = Str("<ipython console>")
160 158 ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__
161 159
162 160 # Input splitter, to split entire cells of input into either individual
163 161 # interactive statements or whole blocks.
164 162 input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
165 163 (), {})
166 164 logstart = CBool(False, config=True)
167 165 logfile = Str('', config=True)
168 166 logappend = Str('', config=True)
169 167 object_info_string_level = Enum((0,1,2), default_value=0,
170 168 config=True)
171 169 pdb = CBool(False, config=True)
172 170
173 171 pprint = CBool(True, config=True)
174 172 profile = Str('', config=True)
175 173 prompt_in1 = Str('In [\\#]: ', config=True)
176 174 prompt_in2 = Str(' .\\D.: ', config=True)
177 175 prompt_out = Str('Out[\\#]: ', config=True)
178 176 prompts_pad_left = CBool(True, config=True)
179 177 quiet = CBool(False, config=True)
180 178
181 179 # The readline stuff will eventually be moved to the terminal subclass
182 180 # but for now, we can't do that as readline is welded in everywhere.
183 181 readline_use = CBool(True, config=True)
184 182 readline_merge_completions = CBool(True, config=True)
185 183 readline_omit__names = Enum((0,1,2), default_value=0, config=True)
186 184 readline_remove_delims = Str('-/~', config=True)
187 185 readline_parse_and_bind = List([
188 186 'tab: complete',
189 187 '"\C-l": clear-screen',
190 188 'set show-all-if-ambiguous on',
191 189 '"\C-o": tab-insert',
192 190 '"\M-i": " "',
193 191 '"\M-o": "\d\d\d\d"',
194 192 '"\M-I": "\d\d\d\d"',
195 193 '"\C-r": reverse-search-history',
196 194 '"\C-s": forward-search-history',
197 195 '"\C-p": history-search-backward',
198 196 '"\C-n": history-search-forward',
199 197 '"\e[A": history-search-backward',
200 198 '"\e[B": history-search-forward',
201 199 '"\C-k": kill-line',
202 200 '"\C-u": unix-line-discard',
203 201 ], allow_none=False, config=True)
204 202
205 203 # TODO: this part of prompt management should be moved to the frontends.
206 204 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
207 205 separate_in = SeparateStr('\n', config=True)
208 206 separate_out = SeparateStr('', config=True)
209 207 separate_out2 = SeparateStr('', config=True)
210 208 wildcards_case_sensitive = CBool(True, config=True)
211 209 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
212 210 default_value='Context', config=True)
213 211
214 212 # Subcomponents of InteractiveShell
215 213 alias_manager = Instance('IPython.core.alias.AliasManager')
216 214 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
217 215 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap')
218 216 display_trap = Instance('IPython.core.display_trap.DisplayTrap')
219 217 extension_manager = Instance('IPython.core.extensions.ExtensionManager')
220 218 plugin_manager = Instance('IPython.core.plugin.PluginManager')
221 219 payload_manager = Instance('IPython.core.payload.PayloadManager')
222 220 history_manager = Instance('IPython.core.history.HistoryManager')
223 221
224 222 # Private interface
225 223 _post_execute = set()
226 224
227 225 def __init__(self, config=None, ipython_dir=None,
228 226 user_ns=None, user_global_ns=None,
229 227 custom_exceptions=((), None)):
230 228
231 229 # This is where traits with a config_key argument are updated
232 230 # from the values on config.
233 231 super(InteractiveShell, self).__init__(config=config)
234 232
235 233 # These are relatively independent and stateless
236 234 self.init_ipython_dir(ipython_dir)
237 235 self.init_instance_attrs()
238 236 self.init_environment()
239 237
240 238 # Create namespaces (user_ns, user_global_ns, etc.)
241 239 self.init_create_namespaces(user_ns, user_global_ns)
242 240 # This has to be done after init_create_namespaces because it uses
243 241 # something in self.user_ns, but before init_sys_modules, which
244 242 # is the first thing to modify sys.
245 243 # TODO: When we override sys.stdout and sys.stderr before this class
246 244 # is created, we are saving the overridden ones here. Not sure if this
247 245 # is what we want to do.
248 246 self.save_sys_module_state()
249 247 self.init_sys_modules()
250 248
251 249 self.init_history()
252 250 self.init_encoding()
253 251 self.init_prefilter()
254 252
255 253 Magic.__init__(self, self)
256 254
257 255 self.init_syntax_highlighting()
258 256 self.init_hooks()
259 257 self.init_pushd_popd_magic()
260 258 # self.init_traceback_handlers use to be here, but we moved it below
261 259 # because it and init_io have to come after init_readline.
262 260 self.init_user_ns()
263 261 self.init_logger()
264 262 self.init_alias()
265 263 self.init_builtins()
266 264
267 265 # pre_config_initialization
268 266
269 267 # The next section should contain everything that was in ipmaker.
270 268 self.init_logstart()
271 269
272 270 # The following was in post_config_initialization
273 271 self.init_inspector()
274 272 # init_readline() must come before init_io(), because init_io uses
275 273 # readline related things.
276 274 self.init_readline()
277 275 # init_completer must come after init_readline, because it needs to
278 276 # know whether readline is present or not system-wide to configure the
279 277 # completers, since the completion machinery can now operate
280 278 # independently of readline (e.g. over the network)
281 279 self.init_completer()
282 280 # TODO: init_io() needs to happen before init_traceback handlers
283 281 # because the traceback handlers hardcode the stdout/stderr streams.
284 282 # This logic in in debugger.Pdb and should eventually be changed.
285 283 self.init_io()
286 284 self.init_traceback_handlers(custom_exceptions)
287 285 self.init_prompts()
288 286 self.init_displayhook()
289 287 self.init_reload_doctest()
290 288 self.init_magics()
291 289 self.init_pdb()
292 290 self.init_extension_manager()
293 291 self.init_plugin_manager()
294 292 self.init_payload()
295 293 self.hooks.late_startup_hook()
296 294 atexit.register(self.atexit_operations)
297 295
298 296 @classmethod
299 297 def instance(cls, *args, **kwargs):
300 298 """Returns a global InteractiveShell instance."""
301 299 if cls._instance is None:
302 300 inst = cls(*args, **kwargs)
303 301 # Now make sure that the instance will also be returned by
304 302 # the subclasses instance attribute.
305 303 for subclass in cls.mro():
306 304 if issubclass(cls, subclass) and \
307 305 issubclass(subclass, InteractiveShell):
308 306 subclass._instance = inst
309 307 else:
310 308 break
311 309 if isinstance(cls._instance, cls):
312 310 return cls._instance
313 311 else:
314 312 raise MultipleInstanceError(
315 313 'Multiple incompatible subclass instances of '
316 314 'InteractiveShell are being created.'
317 315 )
318 316
319 317 @classmethod
320 318 def initialized(cls):
321 319 return hasattr(cls, "_instance")
322 320
323 321 def get_ipython(self):
324 322 """Return the currently running IPython instance."""
325 323 return self
326 324
327 325 #-------------------------------------------------------------------------
328 326 # Trait changed handlers
329 327 #-------------------------------------------------------------------------
330 328
331 329 def _ipython_dir_changed(self, name, new):
332 330 if not os.path.isdir(new):
333 331 os.makedirs(new, mode = 0777)
334 332
335 333 def set_autoindent(self,value=None):
336 334 """Set the autoindent flag, checking for readline support.
337 335
338 336 If called with no arguments, it acts as a toggle."""
339 337
340 338 if not self.has_readline:
341 339 if os.name == 'posix':
342 340 warn("The auto-indent feature requires the readline library")
343 341 self.autoindent = 0
344 342 return
345 343 if value is None:
346 344 self.autoindent = not self.autoindent
347 345 else:
348 346 self.autoindent = value
349 347
350 348 #-------------------------------------------------------------------------
351 349 # init_* methods called by __init__
352 350 #-------------------------------------------------------------------------
353 351
354 352 def init_ipython_dir(self, ipython_dir):
355 353 if ipython_dir is not None:
356 354 self.ipython_dir = ipython_dir
357 355 self.config.Global.ipython_dir = self.ipython_dir
358 356 return
359 357
360 358 if hasattr(self.config.Global, 'ipython_dir'):
361 359 self.ipython_dir = self.config.Global.ipython_dir
362 360 else:
363 361 self.ipython_dir = get_ipython_dir()
364 362
365 363 # All children can just read this
366 364 self.config.Global.ipython_dir = self.ipython_dir
367 365
368 366 def init_instance_attrs(self):
369 367 self.more = False
370 368
371 369 # command compiler
372 370 self.compile = CachingCompiler()
373 371
374 372 # User input buffers
375 373 # NOTE: these variables are slated for full removal, once we are 100%
376 374 # sure that the new execution logic is solid. We will delte runlines,
377 375 # push_line and these buffers, as all input will be managed by the
378 376 # frontends via an inputsplitter instance.
379 377 self.buffer = []
380 378 self.buffer_raw = []
381 379
382 380 # Make an empty namespace, which extension writers can rely on both
383 381 # existing and NEVER being used by ipython itself. This gives them a
384 382 # convenient location for storing additional information and state
385 383 # their extensions may require, without fear of collisions with other
386 384 # ipython names that may develop later.
387 385 self.meta = Struct()
388 386
389 387 # Object variable to store code object waiting execution. This is
390 388 # used mainly by the multithreaded shells, but it can come in handy in
391 389 # other situations. No need to use a Queue here, since it's a single
392 390 # item which gets cleared once run.
393 391 self.code_to_run = None
394 392
395 393 # Temporary files used for various purposes. Deleted at exit.
396 394 self.tempfiles = []
397 395
398 396 # Keep track of readline usage (later set by init_readline)
399 397 self.has_readline = False
400 398
401 399 # keep track of where we started running (mainly for crash post-mortem)
402 400 # This is not being used anywhere currently.
403 401 self.starting_dir = os.getcwd()
404 402
405 403 # Indentation management
406 404 self.indent_current_nsp = 0
407 405
408 406 def init_environment(self):
409 407 """Any changes we need to make to the user's environment."""
410 408 pass
411 409
412 410 def init_encoding(self):
413 411 # Get system encoding at startup time. Certain terminals (like Emacs
414 412 # under Win32 have it set to None, and we need to have a known valid
415 413 # encoding to use in the raw_input() method
416 414 try:
417 415 self.stdin_encoding = sys.stdin.encoding or 'ascii'
418 416 except AttributeError:
419 417 self.stdin_encoding = 'ascii'
420 418
421 419 def init_syntax_highlighting(self):
422 420 # Python source parser/formatter for syntax highlighting
423 421 pyformat = PyColorize.Parser().format
424 422 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
425 423
426 424 def init_pushd_popd_magic(self):
427 425 # for pushd/popd management
428 426 try:
429 427 self.home_dir = get_home_dir()
430 428 except HomeDirError, msg:
431 429 fatal(msg)
432 430
433 431 self.dir_stack = []
434 432
435 433 def init_logger(self):
436 434 self.logger = Logger(self.home_dir, logfname='ipython_log.py',
437 435 logmode='rotate')
438 436
439 437 def init_logstart(self):
440 438 """Initialize logging in case it was requested at the command line.
441 439 """
442 440 if self.logappend:
443 441 self.magic_logstart(self.logappend + ' append')
444 442 elif self.logfile:
445 443 self.magic_logstart(self.logfile)
446 444 elif self.logstart:
447 445 self.magic_logstart()
448 446
449 447 def init_builtins(self):
450 448 self.builtin_trap = BuiltinTrap(shell=self)
451 449
452 450 def init_inspector(self):
453 451 # Object inspector
454 452 self.inspector = oinspect.Inspector(oinspect.InspectColors,
455 453 PyColorize.ANSICodeColors,
456 454 'NoColor',
457 455 self.object_info_string_level)
458 456
459 457 def init_io(self):
460 458 # This will just use sys.stdout and sys.stderr. If you want to
461 459 # override sys.stdout and sys.stderr themselves, you need to do that
462 460 # *before* instantiating this class, because Term holds onto
463 461 # references to the underlying streams.
464 462 if sys.platform == 'win32' and self.has_readline:
465 463 Term = io.IOTerm(cout=self.readline._outputfile,
466 464 cerr=self.readline._outputfile)
467 465 else:
468 466 Term = io.IOTerm()
469 467 io.Term = Term
470 468
471 469 def init_prompts(self):
472 470 # TODO: This is a pass for now because the prompts are managed inside
473 471 # the DisplayHook. Once there is a separate prompt manager, this
474 472 # will initialize that object and all prompt related information.
475 473 pass
476 474
477 475 def init_displayhook(self):
478 476 # Initialize displayhook, set in/out prompts and printing system
479 477 self.displayhook = self.displayhook_class(
480 478 shell=self,
481 479 cache_size=self.cache_size,
482 480 input_sep = self.separate_in,
483 481 output_sep = self.separate_out,
484 482 output_sep2 = self.separate_out2,
485 483 ps1 = self.prompt_in1,
486 484 ps2 = self.prompt_in2,
487 485 ps_out = self.prompt_out,
488 486 pad_left = self.prompts_pad_left
489 487 )
490 488 # This is a context manager that installs/revmoes the displayhook at
491 489 # the appropriate time.
492 490 self.display_trap = DisplayTrap(hook=self.displayhook)
493 491
494 492 def init_reload_doctest(self):
495 493 # Do a proper resetting of doctest, including the necessary displayhook
496 494 # monkeypatching
497 495 try:
498 496 doctest_reload()
499 497 except ImportError:
500 498 warn("doctest module does not exist.")
501 499
502 500 #-------------------------------------------------------------------------
503 501 # Things related to injections into the sys module
504 502 #-------------------------------------------------------------------------
505 503
506 504 def save_sys_module_state(self):
507 505 """Save the state of hooks in the sys module.
508 506
509 507 This has to be called after self.user_ns is created.
510 508 """
511 509 self._orig_sys_module_state = {}
512 510 self._orig_sys_module_state['stdin'] = sys.stdin
513 511 self._orig_sys_module_state['stdout'] = sys.stdout
514 512 self._orig_sys_module_state['stderr'] = sys.stderr
515 513 self._orig_sys_module_state['excepthook'] = sys.excepthook
516 514 try:
517 515 self._orig_sys_modules_main_name = self.user_ns['__name__']
518 516 except KeyError:
519 517 pass
520 518
521 519 def restore_sys_module_state(self):
522 520 """Restore the state of the sys module."""
523 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 523 setattr(sys, k, v)
526 524 except AttributeError:
527 525 pass
528 526 # Reset what what done in self.init_sys_modules
529 527 try:
530 528 sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name
531 529 except (AttributeError, KeyError):
532 530 pass
533 531
534 532 #-------------------------------------------------------------------------
535 533 # Things related to hooks
536 534 #-------------------------------------------------------------------------
537 535
538 536 def init_hooks(self):
539 537 # hooks holds pointers used for user-side customizations
540 538 self.hooks = Struct()
541 539
542 540 self.strdispatchers = {}
543 541
544 542 # Set all default hooks, defined in the IPython.hooks module.
545 543 hooks = IPython.core.hooks
546 544 for hook_name in hooks.__all__:
547 545 # default hooks have priority 100, i.e. low; user hooks should have
548 546 # 0-100 priority
549 547 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
550 548
551 549 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
552 550 """set_hook(name,hook) -> sets an internal IPython hook.
553 551
554 552 IPython exposes some of its internal API as user-modifiable hooks. By
555 553 adding your function to one of these hooks, you can modify IPython's
556 554 behavior to call at runtime your own routines."""
557 555
558 556 # At some point in the future, this should validate the hook before it
559 557 # accepts it. Probably at least check that the hook takes the number
560 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 562 # check if the hook is for strdispatcher first
565 563 if str_key is not None:
566 564 sdp = self.strdispatchers.get(name, StrDispatch())
567 565 sdp.add_s(str_key, f, priority )
568 566 self.strdispatchers[name] = sdp
569 567 return
570 568 if re_key is not None:
571 569 sdp = self.strdispatchers.get(name, StrDispatch())
572 570 sdp.add_re(re.compile(re_key), f, priority )
573 571 self.strdispatchers[name] = sdp
574 572 return
575 573
576 574 dp = getattr(self.hooks, name, None)
577 575 if name not in IPython.core.hooks.__all__:
578 576 print "Warning! Hook '%s' is not one of %s" % \
579 577 (name, IPython.core.hooks.__all__ )
580 578 if not dp:
581 579 dp = IPython.core.hooks.CommandChainDispatcher()
582 580
583 581 try:
584 582 dp.add(f,priority)
585 583 except AttributeError:
586 584 # it was not commandchain, plain old func - replace
587 585 dp = f
588 586
589 587 setattr(self.hooks,name, dp)
590 588
591 589 def register_post_execute(self, func):
592 590 """Register a function for calling after code execution.
593 591 """
594 592 if not callable(func):
595 593 raise ValueError('argument %s must be callable' % func)
596 594 self._post_execute.add(func)
597 595
598 596 #-------------------------------------------------------------------------
599 597 # Things related to the "main" module
600 598 #-------------------------------------------------------------------------
601 599
602 600 def new_main_mod(self,ns=None):
603 601 """Return a new 'main' module object for user code execution.
604 602 """
605 603 main_mod = self._user_main_module
606 604 init_fakemod_dict(main_mod,ns)
607 605 return main_mod
608 606
609 607 def cache_main_mod(self,ns,fname):
610 608 """Cache a main module's namespace.
611 609
612 610 When scripts are executed via %run, we must keep a reference to the
613 611 namespace of their __main__ module (a FakeModule instance) around so
614 612 that Python doesn't clear it, rendering objects defined therein
615 613 useless.
616 614
617 615 This method keeps said reference in a private dict, keyed by the
618 616 absolute path of the module object (which corresponds to the script
619 617 path). This way, for multiple executions of the same script we only
620 618 keep one copy of the namespace (the last one), thus preventing memory
621 619 leaks from old references while allowing the objects from the last
622 620 execution to be accessible.
623 621
624 622 Note: we can not allow the actual FakeModule instances to be deleted,
625 623 because of how Python tears down modules (it hard-sets all their
626 624 references to None without regard for reference counts). This method
627 625 must therefore make a *copy* of the given namespace, to allow the
628 626 original module's __dict__ to be cleared and reused.
629 627
630 628
631 629 Parameters
632 630 ----------
633 631 ns : a namespace (a dict, typically)
634 632
635 633 fname : str
636 634 Filename associated with the namespace.
637 635
638 636 Examples
639 637 --------
640 638
641 639 In [10]: import IPython
642 640
643 641 In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
644 642
645 643 In [12]: IPython.__file__ in _ip._main_ns_cache
646 644 Out[12]: True
647 645 """
648 646 self._main_ns_cache[os.path.abspath(fname)] = ns.copy()
649 647
650 648 def clear_main_mod_cache(self):
651 649 """Clear the cache of main modules.
652 650
653 651 Mainly for use by utilities like %reset.
654 652
655 653 Examples
656 654 --------
657 655
658 656 In [15]: import IPython
659 657
660 658 In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
661 659
662 660 In [17]: len(_ip._main_ns_cache) > 0
663 661 Out[17]: True
664 662
665 663 In [18]: _ip.clear_main_mod_cache()
666 664
667 665 In [19]: len(_ip._main_ns_cache) == 0
668 666 Out[19]: True
669 667 """
670 668 self._main_ns_cache.clear()
671 669
672 670 #-------------------------------------------------------------------------
673 671 # Things related to debugging
674 672 #-------------------------------------------------------------------------
675 673
676 674 def init_pdb(self):
677 675 # Set calling of pdb on exceptions
678 676 # self.call_pdb is a property
679 677 self.call_pdb = self.pdb
680 678
681 679 def _get_call_pdb(self):
682 680 return self._call_pdb
683 681
684 682 def _set_call_pdb(self,val):
685 683
686 684 if val not in (0,1,False,True):
687 685 raise ValueError,'new call_pdb value must be boolean'
688 686
689 687 # store value in instance
690 688 self._call_pdb = val
691 689
692 690 # notify the actual exception handlers
693 691 self.InteractiveTB.call_pdb = val
694 692
695 693 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
696 694 'Control auto-activation of pdb at exceptions')
697 695
698 696 def debugger(self,force=False):
699 697 """Call the pydb/pdb debugger.
700 698
701 699 Keywords:
702 700
703 701 - force(False): by default, this routine checks the instance call_pdb
704 702 flag and does not actually invoke the debugger if the flag is false.
705 703 The 'force' option forces the debugger to activate even if the flag
706 704 is false.
707 705 """
708 706
709 707 if not (force or self.call_pdb):
710 708 return
711 709
712 710 if not hasattr(sys,'last_traceback'):
713 711 error('No traceback has been produced, nothing to debug.')
714 712 return
715 713
716 714 # use pydb if available
717 715 if debugger.has_pydb:
718 716 from pydb import pm
719 717 else:
720 718 # fallback to our internal debugger
721 719 pm = lambda : self.InteractiveTB.debugger(force=True)
722 720 self.history_saving_wrapper(pm)()
723 721
724 722 #-------------------------------------------------------------------------
725 723 # Things related to IPython's various namespaces
726 724 #-------------------------------------------------------------------------
727 725
728 726 def init_create_namespaces(self, user_ns=None, user_global_ns=None):
729 727 # Create the namespace where the user will operate. user_ns is
730 728 # normally the only one used, and it is passed to the exec calls as
731 729 # the locals argument. But we do carry a user_global_ns namespace
732 730 # given as the exec 'globals' argument, This is useful in embedding
733 731 # situations where the ipython shell opens in a context where the
734 732 # distinction between locals and globals is meaningful. For
735 733 # non-embedded contexts, it is just the same object as the user_ns dict.
736 734
737 735 # FIXME. For some strange reason, __builtins__ is showing up at user
738 736 # level as a dict instead of a module. This is a manual fix, but I
739 737 # should really track down where the problem is coming from. Alex
740 738 # Schmolck reported this problem first.
741 739
742 740 # A useful post by Alex Martelli on this topic:
743 741 # Re: inconsistent value from __builtins__
744 742 # Von: Alex Martelli <aleaxit@yahoo.com>
745 743 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
746 744 # Gruppen: comp.lang.python
747 745
748 746 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
749 747 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
750 748 # > <type 'dict'>
751 749 # > >>> print type(__builtins__)
752 750 # > <type 'module'>
753 751 # > Is this difference in return value intentional?
754 752
755 753 # Well, it's documented that '__builtins__' can be either a dictionary
756 754 # or a module, and it's been that way for a long time. Whether it's
757 755 # intentional (or sensible), I don't know. In any case, the idea is
758 756 # that if you need to access the built-in namespace directly, you
759 757 # should start with "import __builtin__" (note, no 's') which will
760 758 # definitely give you a module. Yeah, it's somewhat confusing:-(.
761 759
762 760 # These routines return properly built dicts as needed by the rest of
763 761 # the code, and can also be used by extension writers to generate
764 762 # properly initialized namespaces.
765 763 user_ns, user_global_ns = self.make_user_namespaces(user_ns,
766 764 user_global_ns)
767 765
768 766 # Assign namespaces
769 767 # This is the namespace where all normal user variables live
770 768 self.user_ns = user_ns
771 769 self.user_global_ns = user_global_ns
772 770
773 771 # An auxiliary namespace that checks what parts of the user_ns were
774 772 # loaded at startup, so we can list later only variables defined in
775 773 # actual interactive use. Since it is always a subset of user_ns, it
776 774 # doesn't need to be separately tracked in the ns_table.
777 775 self.user_ns_hidden = {}
778 776
779 777 # A namespace to keep track of internal data structures to prevent
780 778 # them from cluttering user-visible stuff. Will be updated later
781 779 self.internal_ns = {}
782 780
783 781 # Now that FakeModule produces a real module, we've run into a nasty
784 782 # problem: after script execution (via %run), the module where the user
785 783 # code ran is deleted. Now that this object is a true module (needed
786 784 # so docetst and other tools work correctly), the Python module
787 785 # teardown mechanism runs over it, and sets to None every variable
788 786 # present in that module. Top-level references to objects from the
789 787 # script survive, because the user_ns is updated with them. However,
790 788 # calling functions defined in the script that use other things from
791 789 # the script will fail, because the function's closure had references
792 790 # to the original objects, which are now all None. So we must protect
793 791 # these modules from deletion by keeping a cache.
794 792 #
795 793 # To avoid keeping stale modules around (we only need the one from the
796 794 # last run), we use a dict keyed with the full path to the script, so
797 795 # only the last version of the module is held in the cache. Note,
798 796 # however, that we must cache the module *namespace contents* (their
799 797 # __dict__). Because if we try to cache the actual modules, old ones
800 798 # (uncached) could be destroyed while still holding references (such as
801 799 # those held by GUI objects that tend to be long-lived)>
802 800 #
803 801 # The %reset command will flush this cache. See the cache_main_mod()
804 802 # and clear_main_mod_cache() methods for details on use.
805 803
806 804 # This is the cache used for 'main' namespaces
807 805 self._main_ns_cache = {}
808 806 # And this is the single instance of FakeModule whose __dict__ we keep
809 807 # copying and clearing for reuse on each %run
810 808 self._user_main_module = FakeModule()
811 809
812 810 # A table holding all the namespaces IPython deals with, so that
813 811 # introspection facilities can search easily.
814 812 self.ns_table = {'user':user_ns,
815 813 'user_global':user_global_ns,
816 814 'internal':self.internal_ns,
817 815 'builtin':__builtin__.__dict__
818 816 }
819 817
820 818 # Similarly, track all namespaces where references can be held and that
821 819 # we can safely clear (so it can NOT include builtin). This one can be
822 820 # a simple list. Note that the main execution namespaces, user_ns and
823 821 # user_global_ns, can NOT be listed here, as clearing them blindly
824 822 # causes errors in object __del__ methods. Instead, the reset() method
825 823 # clears them manually and carefully.
826 824 self.ns_refs_table = [ self.user_ns_hidden,
827 825 self.internal_ns, self._main_ns_cache ]
828 826
829 827 def make_user_namespaces(self, user_ns=None, user_global_ns=None):
830 828 """Return a valid local and global user interactive namespaces.
831 829
832 830 This builds a dict with the minimal information needed to operate as a
833 831 valid IPython user namespace, which you can pass to the various
834 832 embedding classes in ipython. The default implementation returns the
835 833 same dict for both the locals and the globals to allow functions to
836 834 refer to variables in the namespace. Customized implementations can
837 835 return different dicts. The locals dictionary can actually be anything
838 836 following the basic mapping protocol of a dict, but the globals dict
839 837 must be a true dict, not even a subclass. It is recommended that any
840 838 custom object for the locals namespace synchronize with the globals
841 839 dict somehow.
842 840
843 841 Raises TypeError if the provided globals namespace is not a true dict.
844 842
845 843 Parameters
846 844 ----------
847 845 user_ns : dict-like, optional
848 846 The current user namespace. The items in this namespace should
849 847 be included in the output. If None, an appropriate blank
850 848 namespace should be created.
851 849 user_global_ns : dict, optional
852 850 The current user global namespace. The items in this namespace
853 851 should be included in the output. If None, an appropriate
854 852 blank namespace should be created.
855 853
856 854 Returns
857 855 -------
858 856 A pair of dictionary-like object to be used as the local namespace
859 857 of the interpreter and a dict to be used as the global namespace.
860 858 """
861 859
862 860
863 861 # We must ensure that __builtin__ (without the final 's') is always
864 862 # available and pointing to the __builtin__ *module*. For more details:
865 863 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
866 864
867 865 if user_ns is None:
868 866 # Set __name__ to __main__ to better match the behavior of the
869 867 # normal interpreter.
870 868 user_ns = {'__name__' :'__main__',
871 869 '__builtin__' : __builtin__,
872 870 '__builtins__' : __builtin__,
873 871 }
874 872 else:
875 873 user_ns.setdefault('__name__','__main__')
876 874 user_ns.setdefault('__builtin__',__builtin__)
877 875 user_ns.setdefault('__builtins__',__builtin__)
878 876
879 877 if user_global_ns is None:
880 878 user_global_ns = user_ns
881 879 if type(user_global_ns) is not dict:
882 880 raise TypeError("user_global_ns must be a true dict; got %r"
883 881 % type(user_global_ns))
884 882
885 883 return user_ns, user_global_ns
886 884
887 885 def init_sys_modules(self):
888 886 # We need to insert into sys.modules something that looks like a
889 887 # module but which accesses the IPython namespace, for shelve and
890 888 # pickle to work interactively. Normally they rely on getting
891 889 # everything out of __main__, but for embedding purposes each IPython
892 890 # instance has its own private namespace, so we can't go shoving
893 891 # everything into __main__.
894 892
895 893 # note, however, that we should only do this for non-embedded
896 894 # ipythons, which really mimic the __main__.__dict__ with their own
897 895 # namespace. Embedded instances, on the other hand, should not do
898 896 # this because they need to manage the user local/global namespaces
899 897 # only, but they live within a 'normal' __main__ (meaning, they
900 898 # shouldn't overtake the execution environment of the script they're
901 899 # embedded in).
902 900
903 901 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
904 902
905 903 try:
906 904 main_name = self.user_ns['__name__']
907 905 except KeyError:
908 906 raise KeyError('user_ns dictionary MUST have a "__name__" key')
909 907 else:
910 908 sys.modules[main_name] = FakeModule(self.user_ns)
911 909
912 910 def init_user_ns(self):
913 911 """Initialize all user-visible namespaces to their minimum defaults.
914 912
915 913 Certain history lists are also initialized here, as they effectively
916 914 act as user namespaces.
917 915
918 916 Notes
919 917 -----
920 918 All data structures here are only filled in, they are NOT reset by this
921 919 method. If they were not empty before, data will simply be added to
922 920 therm.
923 921 """
924 922 # This function works in two parts: first we put a few things in
925 923 # user_ns, and we sync that contents into user_ns_hidden so that these
926 924 # initial variables aren't shown by %who. After the sync, we add the
927 925 # rest of what we *do* want the user to see with %who even on a new
928 926 # session (probably nothing, so theye really only see their own stuff)
929 927
930 928 # The user dict must *always* have a __builtin__ reference to the
931 929 # Python standard __builtin__ namespace, which must be imported.
932 930 # This is so that certain operations in prompt evaluation can be
933 931 # reliably executed with builtins. Note that we can NOT use
934 932 # __builtins__ (note the 's'), because that can either be a dict or a
935 933 # module, and can even mutate at runtime, depending on the context
936 934 # (Python makes no guarantees on it). In contrast, __builtin__ is
937 935 # always a module object, though it must be explicitly imported.
938 936
939 937 # For more details:
940 938 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
941 939 ns = dict(__builtin__ = __builtin__)
942 940
943 941 # Put 'help' in the user namespace
944 942 try:
945 943 from site import _Helper
946 944 ns['help'] = _Helper()
947 945 except ImportError:
948 946 warn('help() not available - check site.py')
949 947
950 948 # make global variables for user access to the histories
951 949 ns['_ih'] = self.input_hist
952 950 ns['_oh'] = self.output_hist
953 951 ns['_dh'] = self.dir_hist
954 952
955 953 ns['_sh'] = shadowns
956 954
957 955 # user aliases to input and output histories. These shouldn't show up
958 956 # in %who, as they can have very large reprs.
959 957 ns['In'] = self.input_hist
960 958 ns['Out'] = self.output_hist
961 959
962 960 # Store myself as the public api!!!
963 961 ns['get_ipython'] = self.get_ipython
964 962
965 963 # Sync what we've added so far to user_ns_hidden so these aren't seen
966 964 # by %who
967 965 self.user_ns_hidden.update(ns)
968 966
969 967 # Anything put into ns now would show up in %who. Think twice before
970 968 # putting anything here, as we really want %who to show the user their
971 969 # stuff, not our variables.
972 970
973 971 # Finally, update the real user's namespace
974 972 self.user_ns.update(ns)
975 973
976 974 def reset(self):
977 975 """Clear all internal namespaces.
978 976
979 977 Note that this is much more aggressive than %reset, since it clears
980 978 fully all namespaces, as well as all input/output lists.
981 979 """
982 980 # Clear histories
983 981 self.history_manager.reset()
984 982
985 983 # Reset counter used to index all histories
986 984 self.execution_count = 0
987 985
988 986 # Restore the user namespaces to minimal usability
989 987 for ns in self.ns_refs_table:
990 988 ns.clear()
991 989
992 990 # The main execution namespaces must be cleared very carefully,
993 991 # skipping the deletion of the builtin-related keys, because doing so
994 992 # would cause errors in many object's __del__ methods.
995 993 for ns in [self.user_ns, self.user_global_ns]:
996 994 drop_keys = set(ns.keys())
997 995 drop_keys.discard('__builtin__')
998 996 drop_keys.discard('__builtins__')
999 997 for k in drop_keys:
1000 998 del ns[k]
1001 999
1002 1000 # Restore the user namespaces to minimal usability
1003 1001 self.init_user_ns()
1004 1002
1005 1003 # Restore the default and user aliases
1006 1004 self.alias_manager.clear_aliases()
1007 1005 self.alias_manager.init_aliases()
1008 1006
1009 1007 def reset_selective(self, regex=None):
1010 1008 """Clear selective variables from internal namespaces based on a
1011 1009 specified regular expression.
1012 1010
1013 1011 Parameters
1014 1012 ----------
1015 1013 regex : string or compiled pattern, optional
1016 1014 A regular expression pattern that will be used in searching
1017 1015 variable names in the users namespaces.
1018 1016 """
1019 1017 if regex is not None:
1020 1018 try:
1021 1019 m = re.compile(regex)
1022 1020 except TypeError:
1023 1021 raise TypeError('regex must be a string or compiled pattern')
1024 1022 # Search for keys in each namespace that match the given regex
1025 1023 # If a match is found, delete the key/value pair.
1026 1024 for ns in self.ns_refs_table:
1027 1025 for var in ns:
1028 1026 if m.search(var):
1029 1027 del ns[var]
1030 1028
1031 1029 def push(self, variables, interactive=True):
1032 1030 """Inject a group of variables into the IPython user namespace.
1033 1031
1034 1032 Parameters
1035 1033 ----------
1036 1034 variables : dict, str or list/tuple of str
1037 1035 The variables to inject into the user's namespace. If a dict, a
1038 1036 simple update is done. If a str, the string is assumed to have
1039 1037 variable names separated by spaces. A list/tuple of str can also
1040 1038 be used to give the variable names. If just the variable names are
1041 1039 give (list/tuple/str) then the variable values looked up in the
1042 1040 callers frame.
1043 1041 interactive : bool
1044 1042 If True (default), the variables will be listed with the ``who``
1045 1043 magic.
1046 1044 """
1047 1045 vdict = None
1048 1046
1049 1047 # We need a dict of name/value pairs to do namespace updates.
1050 1048 if isinstance(variables, dict):
1051 1049 vdict = variables
1052 1050 elif isinstance(variables, (basestring, list, tuple)):
1053 1051 if isinstance(variables, basestring):
1054 1052 vlist = variables.split()
1055 1053 else:
1056 1054 vlist = variables
1057 1055 vdict = {}
1058 1056 cf = sys._getframe(1)
1059 1057 for name in vlist:
1060 1058 try:
1061 1059 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1062 1060 except:
1063 1061 print ('Could not get variable %s from %s' %
1064 1062 (name,cf.f_code.co_name))
1065 1063 else:
1066 1064 raise ValueError('variables must be a dict/str/list/tuple')
1067 1065
1068 1066 # Propagate variables to user namespace
1069 1067 self.user_ns.update(vdict)
1070 1068
1071 1069 # And configure interactive visibility
1072 1070 config_ns = self.user_ns_hidden
1073 1071 if interactive:
1074 1072 for name, val in vdict.iteritems():
1075 1073 config_ns.pop(name, None)
1076 1074 else:
1077 1075 for name,val in vdict.iteritems():
1078 1076 config_ns[name] = val
1079 1077
1080 1078 #-------------------------------------------------------------------------
1081 1079 # Things related to object introspection
1082 1080 #-------------------------------------------------------------------------
1083 1081
1084 1082 def _ofind(self, oname, namespaces=None):
1085 1083 """Find an object in the available namespaces.
1086 1084
1087 1085 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
1088 1086
1089 1087 Has special code to detect magic functions.
1090 1088 """
1091 1089 #oname = oname.strip()
1092 1090 #print '1- oname: <%r>' % oname # dbg
1093 1091 try:
1094 1092 oname = oname.strip().encode('ascii')
1095 1093 #print '2- oname: <%r>' % oname # dbg
1096 1094 except UnicodeEncodeError:
1097 1095 print 'Python identifiers can only contain ascii characters.'
1098 1096 return dict(found=False)
1099 1097
1100 1098 alias_ns = None
1101 1099 if namespaces is None:
1102 1100 # Namespaces to search in:
1103 1101 # Put them in a list. The order is important so that we
1104 1102 # find things in the same order that Python finds them.
1105 1103 namespaces = [ ('Interactive', self.user_ns),
1106 1104 ('IPython internal', self.internal_ns),
1107 1105 ('Python builtin', __builtin__.__dict__),
1108 1106 ('Alias', self.alias_manager.alias_table),
1109 1107 ]
1110 1108 alias_ns = self.alias_manager.alias_table
1111 1109
1112 1110 # initialize results to 'null'
1113 1111 found = False; obj = None; ospace = None; ds = None;
1114 1112 ismagic = False; isalias = False; parent = None
1115 1113
1116 1114 # We need to special-case 'print', which as of python2.6 registers as a
1117 1115 # function but should only be treated as one if print_function was
1118 1116 # loaded with a future import. In this case, just bail.
1119 1117 if (oname == 'print' and not (self.compile.compiler_flags &
1120 1118 __future__.CO_FUTURE_PRINT_FUNCTION)):
1121 1119 return {'found':found, 'obj':obj, 'namespace':ospace,
1122 1120 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1123 1121
1124 1122 # Look for the given name by splitting it in parts. If the head is
1125 1123 # found, then we look for all the remaining parts as members, and only
1126 1124 # declare success if we can find them all.
1127 1125 oname_parts = oname.split('.')
1128 1126 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
1129 1127 for nsname,ns in namespaces:
1130 1128 try:
1131 1129 obj = ns[oname_head]
1132 1130 except KeyError:
1133 1131 continue
1134 1132 else:
1135 1133 #print 'oname_rest:', oname_rest # dbg
1136 1134 for part in oname_rest:
1137 1135 try:
1138 1136 parent = obj
1139 1137 obj = getattr(obj,part)
1140 1138 except:
1141 1139 # Blanket except b/c some badly implemented objects
1142 1140 # allow __getattr__ to raise exceptions other than
1143 1141 # AttributeError, which then crashes IPython.
1144 1142 break
1145 1143 else:
1146 1144 # If we finish the for loop (no break), we got all members
1147 1145 found = True
1148 1146 ospace = nsname
1149 1147 if ns == alias_ns:
1150 1148 isalias = True
1151 1149 break # namespace loop
1152 1150
1153 1151 # Try to see if it's magic
1154 1152 if not found:
1155 1153 if oname.startswith(ESC_MAGIC):
1156 1154 oname = oname[1:]
1157 1155 obj = getattr(self,'magic_'+oname,None)
1158 1156 if obj is not None:
1159 1157 found = True
1160 1158 ospace = 'IPython internal'
1161 1159 ismagic = True
1162 1160
1163 1161 # Last try: special-case some literals like '', [], {}, etc:
1164 1162 if not found and oname_head in ["''",'""','[]','{}','()']:
1165 1163 obj = eval(oname_head)
1166 1164 found = True
1167 1165 ospace = 'Interactive'
1168 1166
1169 1167 return {'found':found, 'obj':obj, 'namespace':ospace,
1170 1168 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1171 1169
1172 1170 def _ofind_property(self, oname, info):
1173 1171 """Second part of object finding, to look for property details."""
1174 1172 if info.found:
1175 1173 # Get the docstring of the class property if it exists.
1176 1174 path = oname.split('.')
1177 1175 root = '.'.join(path[:-1])
1178 1176 if info.parent is not None:
1179 1177 try:
1180 1178 target = getattr(info.parent, '__class__')
1181 1179 # The object belongs to a class instance.
1182 1180 try:
1183 1181 target = getattr(target, path[-1])
1184 1182 # The class defines the object.
1185 1183 if isinstance(target, property):
1186 1184 oname = root + '.__class__.' + path[-1]
1187 1185 info = Struct(self._ofind(oname))
1188 1186 except AttributeError: pass
1189 1187 except AttributeError: pass
1190 1188
1191 1189 # We return either the new info or the unmodified input if the object
1192 1190 # hadn't been found
1193 1191 return info
1194 1192
1195 1193 def _object_find(self, oname, namespaces=None):
1196 1194 """Find an object and return a struct with info about it."""
1197 1195 inf = Struct(self._ofind(oname, namespaces))
1198 1196 return Struct(self._ofind_property(oname, inf))
1199 1197
1200 1198 def _inspect(self, meth, oname, namespaces=None, **kw):
1201 1199 """Generic interface to the inspector system.
1202 1200
1203 1201 This function is meant to be called by pdef, pdoc & friends."""
1204 1202 info = self._object_find(oname)
1205 1203 if info.found:
1206 1204 pmethod = getattr(self.inspector, meth)
1207 1205 formatter = format_screen if info.ismagic else None
1208 1206 if meth == 'pdoc':
1209 1207 pmethod(info.obj, oname, formatter)
1210 1208 elif meth == 'pinfo':
1211 1209 pmethod(info.obj, oname, formatter, info, **kw)
1212 1210 else:
1213 1211 pmethod(info.obj, oname)
1214 1212 else:
1215 1213 print 'Object `%s` not found.' % oname
1216 1214 return 'not found' # so callers can take other action
1217 1215
1218 1216 def object_inspect(self, oname):
1219 1217 info = self._object_find(oname)
1220 1218 if info.found:
1221 1219 return self.inspector.info(info.obj, oname, info=info)
1222 1220 else:
1223 1221 return oinspect.object_info(name=oname, found=False)
1224 1222
1225 1223 #-------------------------------------------------------------------------
1226 1224 # Things related to history management
1227 1225 #-------------------------------------------------------------------------
1228 1226
1229 1227 def init_history(self):
1230 1228 self.history_manager = HistoryManager(shell=self)
1231 1229
1232 1230 def save_hist(self):
1233 1231 """Save input history to a file (via readline library)."""
1234 1232 self.history_manager.save_hist()
1235 1233
1236 1234 # For backwards compatibility
1237 1235 savehist = save_hist
1238 1236
1239 1237 def reload_hist(self):
1240 1238 """Reload the input history from disk file."""
1241 1239 self.history_manager.reload_hist()
1242 1240
1243 1241 # For backwards compatibility
1244 1242 reloadhist = reload_hist
1245 1243
1246 1244 def history_saving_wrapper(self, func):
1247 1245 """ Wrap func for readline history saving
1248 1246
1249 1247 Convert func into callable that saves & restores
1250 1248 history around the call """
1251 1249
1252 1250 if self.has_readline:
1253 1251 from IPython.utils import rlineimpl as readline
1254 1252 else:
1255 1253 return func
1256 1254
1257 1255 def wrapper():
1258 1256 self.save_hist()
1259 1257 try:
1260 1258 func()
1261 1259 finally:
1262 1260 readline.read_history_file(self.histfile)
1263 1261 return wrapper
1264 1262
1265 1263 #-------------------------------------------------------------------------
1266 1264 # Things related to exception handling and tracebacks (not debugging)
1267 1265 #-------------------------------------------------------------------------
1268 1266
1269 1267 def init_traceback_handlers(self, custom_exceptions):
1270 1268 # Syntax error handler.
1271 1269 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor')
1272 1270
1273 1271 # The interactive one is initialized with an offset, meaning we always
1274 1272 # want to remove the topmost item in the traceback, which is our own
1275 1273 # internal code. Valid modes: ['Plain','Context','Verbose']
1276 1274 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1277 1275 color_scheme='NoColor',
1278 1276 tb_offset = 1,
1279 1277 check_cache=self.compile.check_cache)
1280 1278
1281 1279 # The instance will store a pointer to the system-wide exception hook,
1282 1280 # so that runtime code (such as magics) can access it. This is because
1283 1281 # during the read-eval loop, it may get temporarily overwritten.
1284 1282 self.sys_excepthook = sys.excepthook
1285 1283
1286 1284 # and add any custom exception handlers the user may have specified
1287 1285 self.set_custom_exc(*custom_exceptions)
1288 1286
1289 1287 # Set the exception mode
1290 1288 self.InteractiveTB.set_mode(mode=self.xmode)
1291 1289
1292 1290 def set_custom_exc(self, exc_tuple, handler):
1293 1291 """set_custom_exc(exc_tuple,handler)
1294 1292
1295 1293 Set a custom exception handler, which will be called if any of the
1296 1294 exceptions in exc_tuple occur in the mainloop (specifically, in the
1297 1295 run_code() method.
1298 1296
1299 1297 Inputs:
1300 1298
1301 1299 - exc_tuple: a *tuple* of valid exceptions to call the defined
1302 1300 handler for. It is very important that you use a tuple, and NOT A
1303 1301 LIST here, because of the way Python's except statement works. If
1304 1302 you only want to trap a single exception, use a singleton tuple:
1305 1303
1306 1304 exc_tuple == (MyCustomException,)
1307 1305
1308 1306 - handler: this must be defined as a function with the following
1309 1307 basic interface::
1310 1308
1311 1309 def my_handler(self, etype, value, tb, tb_offset=None)
1312 1310 ...
1313 1311 # The return value must be
1314 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 1315 of IPython itself, and it will be called if any of the exceptions
1318 1316 listed in the exc_tuple are caught. If the handler is None, an
1319 1317 internal basic one is used, which just prints basic info.
1320 1318
1321 1319 WARNING: by putting in your own exception handler into IPython's main
1322 1320 execution loop, you run a very good chance of nasty crashes. This
1323 1321 facility should only be used if you really know what you are doing."""
1324 1322
1325 1323 assert type(exc_tuple)==type(()) , \
1326 1324 "The custom exceptions must be given AS A TUPLE."
1327 1325
1328 1326 def dummy_handler(self,etype,value,tb):
1329 1327 print '*** Simple custom exception handler ***'
1330 1328 print 'Exception type :',etype
1331 1329 print 'Exception value:',value
1332 1330 print 'Traceback :',tb
1333 1331 print 'Source code :','\n'.join(self.buffer)
1334 1332
1335 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 1336 self.custom_exceptions = exc_tuple
1339 1337
1340 1338 def excepthook(self, etype, value, tb):
1341 1339 """One more defense for GUI apps that call sys.excepthook.
1342 1340
1343 1341 GUI frameworks like wxPython trap exceptions and call
1344 1342 sys.excepthook themselves. I guess this is a feature that
1345 1343 enables them to keep running after exceptions that would
1346 1344 otherwise kill their mainloop. This is a bother for IPython
1347 1345 which excepts to catch all of the program exceptions with a try:
1348 1346 except: statement.
1349 1347
1350 1348 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1351 1349 any app directly invokes sys.excepthook, it will look to the user like
1352 1350 IPython crashed. In order to work around this, we can disable the
1353 1351 CrashHandler and replace it with this excepthook instead, which prints a
1354 1352 regular traceback using our InteractiveTB. In this fashion, apps which
1355 1353 call sys.excepthook will generate a regular-looking exception from
1356 1354 IPython, and the CrashHandler will only be triggered by real IPython
1357 1355 crashes.
1358 1356
1359 1357 This hook should be used sparingly, only in places which are not likely
1360 1358 to be true IPython errors.
1361 1359 """
1362 1360 self.showtraceback((etype,value,tb),tb_offset=0)
1363 1361
1364 1362 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None,
1365 1363 exception_only=False):
1366 1364 """Display the exception that just occurred.
1367 1365
1368 1366 If nothing is known about the exception, this is the method which
1369 1367 should be used throughout the code for presenting user tracebacks,
1370 1368 rather than directly invoking the InteractiveTB object.
1371 1369
1372 1370 A specific showsyntaxerror() also exists, but this method can take
1373 1371 care of calling it if needed, so unless you are explicitly catching a
1374 1372 SyntaxError exception, don't try to analyze the stack manually and
1375 1373 simply call this method."""
1376 1374
1377 1375 try:
1378 1376 if exc_tuple is None:
1379 1377 etype, value, tb = sys.exc_info()
1380 1378 else:
1381 1379 etype, value, tb = exc_tuple
1382 1380
1383 1381 if etype is None:
1384 1382 if hasattr(sys, 'last_type'):
1385 1383 etype, value, tb = sys.last_type, sys.last_value, \
1386 1384 sys.last_traceback
1387 1385 else:
1388 1386 self.write_err('No traceback available to show.\n')
1389 1387 return
1390 1388
1391 1389 if etype is SyntaxError:
1392 1390 # Though this won't be called by syntax errors in the input
1393 1391 # line, there may be SyntaxError cases whith imported code.
1394 1392 self.showsyntaxerror(filename)
1395 1393 elif etype is UsageError:
1396 1394 print "UsageError:", value
1397 1395 else:
1398 1396 # WARNING: these variables are somewhat deprecated and not
1399 1397 # necessarily safe to use in a threaded environment, but tools
1400 1398 # like pdb depend on their existence, so let's set them. If we
1401 1399 # find problems in the field, we'll need to revisit their use.
1402 1400 sys.last_type = etype
1403 1401 sys.last_value = value
1404 1402 sys.last_traceback = tb
1405 1403
1406 1404 if etype in self.custom_exceptions:
1407 1405 # FIXME: Old custom traceback objects may just return a
1408 1406 # string, in that case we just put it into a list
1409 1407 stb = self.CustomTB(etype, value, tb, tb_offset)
1410 1408 if isinstance(ctb, basestring):
1411 1409 stb = [stb]
1412 1410 else:
1413 1411 if exception_only:
1414 1412 stb = ['An exception has occurred, use %tb to see '
1415 1413 'the full traceback.\n']
1416 1414 stb.extend(self.InteractiveTB.get_exception_only(etype,
1417 1415 value))
1418 1416 else:
1419 1417 stb = self.InteractiveTB.structured_traceback(etype,
1420 1418 value, tb, tb_offset=tb_offset)
1421 1419 # FIXME: the pdb calling should be done by us, not by
1422 1420 # the code computing the traceback.
1423 1421 if self.InteractiveTB.call_pdb:
1424 1422 # pdb mucks up readline, fix it back
1425 1423 self.set_readline_completer()
1426 1424
1427 1425 # Actually show the traceback
1428 1426 self._showtraceback(etype, value, stb)
1429 1427
1430 1428 except KeyboardInterrupt:
1431 1429 self.write_err("\nKeyboardInterrupt\n")
1432 1430
1433 1431 def _showtraceback(self, etype, evalue, stb):
1434 1432 """Actually show a traceback.
1435 1433
1436 1434 Subclasses may override this method to put the traceback on a different
1437 1435 place, like a side channel.
1438 1436 """
1439 1437 print >> io.Term.cout, self.InteractiveTB.stb2text(stb)
1440 1438
1441 1439 def showsyntaxerror(self, filename=None):
1442 1440 """Display the syntax error that just occurred.
1443 1441
1444 1442 This doesn't display a stack trace because there isn't one.
1445 1443
1446 1444 If a filename is given, it is stuffed in the exception instead
1447 1445 of what was there before (because Python's parser always uses
1448 1446 "<string>" when reading from a string).
1449 1447 """
1450 1448 etype, value, last_traceback = sys.exc_info()
1451 1449
1452 1450 # See note about these variables in showtraceback() above
1453 1451 sys.last_type = etype
1454 1452 sys.last_value = value
1455 1453 sys.last_traceback = last_traceback
1456 1454
1457 1455 if filename and etype is SyntaxError:
1458 1456 # Work hard to stuff the correct filename in the exception
1459 1457 try:
1460 1458 msg, (dummy_filename, lineno, offset, line) = value
1461 1459 except:
1462 1460 # Not the format we expect; leave it alone
1463 1461 pass
1464 1462 else:
1465 1463 # Stuff in the right filename
1466 1464 try:
1467 1465 # Assume SyntaxError is a class exception
1468 1466 value = SyntaxError(msg, (filename, lineno, offset, line))
1469 1467 except:
1470 1468 # If that failed, assume SyntaxError is a string
1471 1469 value = msg, (filename, lineno, offset, line)
1472 1470 stb = self.SyntaxTB.structured_traceback(etype, value, [])
1473 1471 self._showtraceback(etype, value, stb)
1474 1472
1475 1473 #-------------------------------------------------------------------------
1476 1474 # Things related to readline
1477 1475 #-------------------------------------------------------------------------
1478 1476
1479 1477 def init_readline(self):
1480 1478 """Command history completion/saving/reloading."""
1481 1479
1482 1480 if self.readline_use:
1483 1481 import IPython.utils.rlineimpl as readline
1484 1482
1485 1483 self.rl_next_input = None
1486 1484 self.rl_do_indent = False
1487 1485
1488 1486 if not self.readline_use or not readline.have_readline:
1489 1487 self.has_readline = False
1490 1488 self.readline = None
1491 1489 # Set a number of methods that depend on readline to be no-op
1492 1490 self.save_hist = no_op
1493 1491 self.reload_hist = no_op
1494 1492 self.set_readline_completer = no_op
1495 1493 self.set_custom_completer = no_op
1496 1494 self.set_completer_frame = no_op
1497 1495 warn('Readline services not available or not loaded.')
1498 1496 else:
1499 1497 self.has_readline = True
1500 1498 self.readline = readline
1501 1499 sys.modules['readline'] = readline
1502 1500
1503 1501 # Platform-specific configuration
1504 1502 if os.name == 'nt':
1505 1503 # FIXME - check with Frederick to see if we can harmonize
1506 1504 # naming conventions with pyreadline to avoid this
1507 1505 # platform-dependent check
1508 1506 self.readline_startup_hook = readline.set_pre_input_hook
1509 1507 else:
1510 1508 self.readline_startup_hook = readline.set_startup_hook
1511 1509
1512 1510 # Load user's initrc file (readline config)
1513 1511 # Or if libedit is used, load editrc.
1514 1512 inputrc_name = os.environ.get('INPUTRC')
1515 1513 if inputrc_name is None:
1516 1514 home_dir = get_home_dir()
1517 1515 if home_dir is not None:
1518 1516 inputrc_name = '.inputrc'
1519 1517 if readline.uses_libedit:
1520 1518 inputrc_name = '.editrc'
1521 1519 inputrc_name = os.path.join(home_dir, inputrc_name)
1522 1520 if os.path.isfile(inputrc_name):
1523 1521 try:
1524 1522 readline.read_init_file(inputrc_name)
1525 1523 except:
1526 1524 warn('Problems reading readline initialization file <%s>'
1527 1525 % inputrc_name)
1528 1526
1529 1527 # Configure readline according to user's prefs
1530 1528 # This is only done if GNU readline is being used. If libedit
1531 1529 # is being used (as on Leopard) the readline config is
1532 1530 # not run as the syntax for libedit is different.
1533 1531 if not readline.uses_libedit:
1534 1532 for rlcommand in self.readline_parse_and_bind:
1535 1533 #print "loading rl:",rlcommand # dbg
1536 1534 readline.parse_and_bind(rlcommand)
1537 1535
1538 1536 # Remove some chars from the delimiters list. If we encounter
1539 1537 # unicode chars, discard them.
1540 1538 delims = readline.get_completer_delims().encode("ascii", "ignore")
1541 delims = delims.translate(string._idmap,
1542 self.readline_remove_delims)
1539 delims = delims.translate(None, self.readline_remove_delims)
1543 1540 delims = delims.replace(ESC_MAGIC, '')
1544 1541 readline.set_completer_delims(delims)
1545 1542 # otherwise we end up with a monster history after a while:
1546 1543 readline.set_history_length(1000)
1547 1544 try:
1548 1545 #print '*** Reading readline history' # dbg
1549 1546 readline.read_history_file(self.histfile)
1550 1547 except IOError:
1551 1548 pass # It doesn't exist yet.
1552 1549
1553 1550 # If we have readline, we want our history saved upon ipython
1554 1551 # exiting.
1555 1552 atexit.register(self.save_hist)
1556 1553
1557 1554 # Configure auto-indent for all platforms
1558 1555 self.set_autoindent(self.autoindent)
1559 1556
1560 1557 def set_next_input(self, s):
1561 1558 """ Sets the 'default' input string for the next command line.
1562 1559
1563 1560 Requires readline.
1564 1561
1565 1562 Example:
1566 1563
1567 1564 [D:\ipython]|1> _ip.set_next_input("Hello Word")
1568 1565 [D:\ipython]|2> Hello Word_ # cursor is here
1569 1566 """
1570 1567
1571 1568 self.rl_next_input = s
1572 1569
1573 1570 # Maybe move this to the terminal subclass?
1574 1571 def pre_readline(self):
1575 1572 """readline hook to be used at the start of each line.
1576 1573
1577 1574 Currently it handles auto-indent only."""
1578 1575
1579 1576 if self.rl_do_indent:
1580 1577 self.readline.insert_text(self._indent_current_str())
1581 1578 if self.rl_next_input is not None:
1582 1579 self.readline.insert_text(self.rl_next_input)
1583 1580 self.rl_next_input = None
1584 1581
1585 1582 def _indent_current_str(self):
1586 1583 """return the current level of indentation as a string"""
1587 1584 return self.input_splitter.indent_spaces * ' '
1588 1585
1589 1586 #-------------------------------------------------------------------------
1590 1587 # Things related to text completion
1591 1588 #-------------------------------------------------------------------------
1592 1589
1593 1590 def init_completer(self):
1594 1591 """Initialize the completion machinery.
1595 1592
1596 1593 This creates completion machinery that can be used by client code,
1597 1594 either interactively in-process (typically triggered by the readline
1598 1595 library), programatically (such as in test suites) or out-of-prcess
1599 1596 (typically over the network by remote frontends).
1600 1597 """
1601 1598 from IPython.core.completer import IPCompleter
1602 1599 from IPython.core.completerlib import (module_completer,
1603 1600 magic_run_completer, cd_completer)
1604 1601
1605 1602 self.Completer = IPCompleter(self,
1606 1603 self.user_ns,
1607 1604 self.user_global_ns,
1608 1605 self.readline_omit__names,
1609 1606 self.alias_manager.alias_table,
1610 1607 self.has_readline)
1611 1608
1612 1609 # Add custom completers to the basic ones built into IPCompleter
1613 1610 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1614 1611 self.strdispatchers['complete_command'] = sdisp
1615 1612 self.Completer.custom_completers = sdisp
1616 1613
1617 1614 self.set_hook('complete_command', module_completer, str_key = 'import')
1618 1615 self.set_hook('complete_command', module_completer, str_key = 'from')
1619 1616 self.set_hook('complete_command', magic_run_completer, str_key = '%run')
1620 1617 self.set_hook('complete_command', cd_completer, str_key = '%cd')
1621 1618
1622 1619 # Only configure readline if we truly are using readline. IPython can
1623 1620 # do tab-completion over the network, in GUIs, etc, where readline
1624 1621 # itself may be absent
1625 1622 if self.has_readline:
1626 1623 self.set_readline_completer()
1627 1624
1628 1625 def complete(self, text, line=None, cursor_pos=None):
1629 1626 """Return the completed text and a list of completions.
1630 1627
1631 1628 Parameters
1632 1629 ----------
1633 1630
1634 1631 text : string
1635 1632 A string of text to be completed on. It can be given as empty and
1636 1633 instead a line/position pair are given. In this case, the
1637 1634 completer itself will split the line like readline does.
1638 1635
1639 1636 line : string, optional
1640 1637 The complete line that text is part of.
1641 1638
1642 1639 cursor_pos : int, optional
1643 1640 The position of the cursor on the input line.
1644 1641
1645 1642 Returns
1646 1643 -------
1647 1644 text : string
1648 1645 The actual text that was completed.
1649 1646
1650 1647 matches : list
1651 1648 A sorted list with all possible completions.
1652 1649
1653 1650 The optional arguments allow the completion to take more context into
1654 1651 account, and are part of the low-level completion API.
1655 1652
1656 1653 This is a wrapper around the completion mechanism, similar to what
1657 1654 readline does at the command line when the TAB key is hit. By
1658 1655 exposing it as a method, it can be used by other non-readline
1659 1656 environments (such as GUIs) for text completion.
1660 1657
1661 1658 Simple usage example:
1662 1659
1663 1660 In [1]: x = 'hello'
1664 1661
1665 1662 In [2]: _ip.complete('x.l')
1666 1663 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
1667 1664 """
1668 1665
1669 1666 # Inject names into __builtin__ so we can complete on the added names.
1670 1667 with self.builtin_trap:
1671 1668 return self.Completer.complete(text, line, cursor_pos)
1672 1669
1673 1670 def set_custom_completer(self, completer, pos=0):
1674 1671 """Adds a new custom completer function.
1675 1672
1676 1673 The position argument (defaults to 0) is the index in the completers
1677 1674 list where you want the completer to be inserted."""
1678 1675
1679 newcomp = new.instancemethod(completer,self.Completer,
1680 self.Completer.__class__)
1676 newcomp = types.MethodType(completer,self.Completer)
1681 1677 self.Completer.matchers.insert(pos,newcomp)
1682 1678
1683 1679 def set_readline_completer(self):
1684 1680 """Reset readline's completer to be our own."""
1685 1681 self.readline.set_completer(self.Completer.rlcomplete)
1686 1682
1687 1683 def set_completer_frame(self, frame=None):
1688 1684 """Set the frame of the completer."""
1689 1685 if frame:
1690 1686 self.Completer.namespace = frame.f_locals
1691 1687 self.Completer.global_namespace = frame.f_globals
1692 1688 else:
1693 1689 self.Completer.namespace = self.user_ns
1694 1690 self.Completer.global_namespace = self.user_global_ns
1695 1691
1696 1692 #-------------------------------------------------------------------------
1697 1693 # Things related to magics
1698 1694 #-------------------------------------------------------------------------
1699 1695
1700 1696 def init_magics(self):
1701 1697 # FIXME: Move the color initialization to the DisplayHook, which
1702 1698 # should be split into a prompt manager and displayhook. We probably
1703 1699 # even need a centralize colors management object.
1704 1700 self.magic_colors(self.colors)
1705 1701 # History was moved to a separate module
1706 1702 from . import history
1707 1703 history.init_ipython(self)
1708 1704
1709 1705 def magic(self,arg_s):
1710 1706 """Call a magic function by name.
1711 1707
1712 1708 Input: a string containing the name of the magic function to call and
1713 1709 any additional arguments to be passed to the magic.
1714 1710
1715 1711 magic('name -opt foo bar') is equivalent to typing at the ipython
1716 1712 prompt:
1717 1713
1718 1714 In[1]: %name -opt foo bar
1719 1715
1720 1716 To call a magic without arguments, simply use magic('name').
1721 1717
1722 1718 This provides a proper Python function to call IPython's magics in any
1723 1719 valid Python code you can type at the interpreter, including loops and
1724 1720 compound statements.
1725 1721 """
1726 1722 args = arg_s.split(' ',1)
1727 1723 magic_name = args[0]
1728 1724 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
1729 1725
1730 1726 try:
1731 1727 magic_args = args[1]
1732 1728 except IndexError:
1733 1729 magic_args = ''
1734 1730 fn = getattr(self,'magic_'+magic_name,None)
1735 1731 if fn is None:
1736 1732 error("Magic function `%s` not found." % magic_name)
1737 1733 else:
1738 1734 magic_args = self.var_expand(magic_args,1)
1739 1735 with nested(self.builtin_trap,):
1740 1736 result = fn(magic_args)
1741 1737 return result
1742 1738
1743 1739 def define_magic(self, magicname, func):
1744 1740 """Expose own function as magic function for ipython
1745 1741
1746 1742 def foo_impl(self,parameter_s=''):
1747 1743 'My very own magic!. (Use docstrings, IPython reads them).'
1748 1744 print 'Magic function. Passed parameter is between < >:'
1749 1745 print '<%s>' % parameter_s
1750 1746 print 'The self object is:',self
1751 1747
1752 1748 self.define_magic('foo',foo_impl)
1753 1749 """
1754 1750
1755 1751 import new
1756 im = new.instancemethod(func,self, self.__class__)
1752 im = types.MethodType(func,self)
1757 1753 old = getattr(self, "magic_" + magicname, None)
1758 1754 setattr(self, "magic_" + magicname, im)
1759 1755 return old
1760 1756
1761 1757 #-------------------------------------------------------------------------
1762 1758 # Things related to macros
1763 1759 #-------------------------------------------------------------------------
1764 1760
1765 1761 def define_macro(self, name, themacro):
1766 1762 """Define a new macro
1767 1763
1768 1764 Parameters
1769 1765 ----------
1770 1766 name : str
1771 1767 The name of the macro.
1772 1768 themacro : str or Macro
1773 1769 The action to do upon invoking the macro. If a string, a new
1774 1770 Macro object is created by passing the string to it.
1775 1771 """
1776 1772
1777 1773 from IPython.core import macro
1778 1774
1779 1775 if isinstance(themacro, basestring):
1780 1776 themacro = macro.Macro(themacro)
1781 1777 if not isinstance(themacro, macro.Macro):
1782 1778 raise ValueError('A macro must be a string or a Macro instance.')
1783 1779 self.user_ns[name] = themacro
1784 1780
1785 1781 #-------------------------------------------------------------------------
1786 1782 # Things related to the running of system commands
1787 1783 #-------------------------------------------------------------------------
1788 1784
1789 1785 def system(self, cmd):
1790 1786 """Call the given cmd in a subprocess.
1791 1787
1792 1788 Parameters
1793 1789 ----------
1794 1790 cmd : str
1795 1791 Command to execute (can not end in '&', as bacground processes are
1796 1792 not supported.
1797 1793 """
1798 1794 # We do not support backgrounding processes because we either use
1799 1795 # pexpect or pipes to read from. Users can always just call
1800 1796 # os.system() if they really want a background process.
1801 1797 if cmd.endswith('&'):
1802 1798 raise OSError("Background processes not supported.")
1803 1799
1804 1800 return system(self.var_expand(cmd, depth=2))
1805 1801
1806 1802 def getoutput(self, cmd, split=True):
1807 1803 """Get output (possibly including stderr) from a subprocess.
1808 1804
1809 1805 Parameters
1810 1806 ----------
1811 1807 cmd : str
1812 1808 Command to execute (can not end in '&', as background processes are
1813 1809 not supported.
1814 1810 split : bool, optional
1815 1811
1816 1812 If True, split the output into an IPython SList. Otherwise, an
1817 1813 IPython LSString is returned. These are objects similar to normal
1818 1814 lists and strings, with a few convenience attributes for easier
1819 1815 manipulation of line-based output. You can use '?' on them for
1820 1816 details.
1821 1817 """
1822 1818 if cmd.endswith('&'):
1823 1819 raise OSError("Background processes not supported.")
1824 1820 out = getoutput(self.var_expand(cmd, depth=2))
1825 1821 if split:
1826 1822 out = SList(out.splitlines())
1827 1823 else:
1828 1824 out = LSString(out)
1829 1825 return out
1830 1826
1831 1827 #-------------------------------------------------------------------------
1832 1828 # Things related to aliases
1833 1829 #-------------------------------------------------------------------------
1834 1830
1835 1831 def init_alias(self):
1836 1832 self.alias_manager = AliasManager(shell=self, config=self.config)
1837 1833 self.ns_table['alias'] = self.alias_manager.alias_table,
1838 1834
1839 1835 #-------------------------------------------------------------------------
1840 1836 # Things related to extensions and plugins
1841 1837 #-------------------------------------------------------------------------
1842 1838
1843 1839 def init_extension_manager(self):
1844 1840 self.extension_manager = ExtensionManager(shell=self, config=self.config)
1845 1841
1846 1842 def init_plugin_manager(self):
1847 1843 self.plugin_manager = PluginManager(config=self.config)
1848 1844
1849 1845 #-------------------------------------------------------------------------
1850 1846 # Things related to payloads
1851 1847 #-------------------------------------------------------------------------
1852 1848
1853 1849 def init_payload(self):
1854 1850 self.payload_manager = PayloadManager(config=self.config)
1855 1851
1856 1852 #-------------------------------------------------------------------------
1857 1853 # Things related to the prefilter
1858 1854 #-------------------------------------------------------------------------
1859 1855
1860 1856 def init_prefilter(self):
1861 1857 self.prefilter_manager = PrefilterManager(shell=self, config=self.config)
1862 1858 # Ultimately this will be refactored in the new interpreter code, but
1863 1859 # for now, we should expose the main prefilter method (there's legacy
1864 1860 # code out there that may rely on this).
1865 1861 self.prefilter = self.prefilter_manager.prefilter_lines
1866 1862
1867 1863 def auto_rewrite_input(self, cmd):
1868 1864 """Print to the screen the rewritten form of the user's command.
1869 1865
1870 1866 This shows visual feedback by rewriting input lines that cause
1871 1867 automatic calling to kick in, like::
1872 1868
1873 1869 /f x
1874 1870
1875 1871 into::
1876 1872
1877 1873 ------> f(x)
1878 1874
1879 1875 after the user's input prompt. This helps the user understand that the
1880 1876 input line was transformed automatically by IPython.
1881 1877 """
1882 1878 rw = self.displayhook.prompt1.auto_rewrite() + cmd
1883 1879
1884 1880 try:
1885 1881 # plain ascii works better w/ pyreadline, on some machines, so
1886 1882 # we use it and only print uncolored rewrite if we have unicode
1887 1883 rw = str(rw)
1888 1884 print >> IPython.utils.io.Term.cout, rw
1889 1885 except UnicodeEncodeError:
1890 1886 print "------> " + cmd
1891 1887
1892 1888 #-------------------------------------------------------------------------
1893 1889 # Things related to extracting values/expressions from kernel and user_ns
1894 1890 #-------------------------------------------------------------------------
1895 1891
1896 1892 def _simple_error(self):
1897 1893 etype, value = sys.exc_info()[:2]
1898 1894 return u'[ERROR] {e.__name__}: {v}'.format(e=etype, v=value)
1899 1895
1900 1896 def user_variables(self, names):
1901 1897 """Get a list of variable names from the user's namespace.
1902 1898
1903 1899 Parameters
1904 1900 ----------
1905 1901 names : list of strings
1906 1902 A list of names of variables to be read from the user namespace.
1907 1903
1908 1904 Returns
1909 1905 -------
1910 1906 A dict, keyed by the input names and with the repr() of each value.
1911 1907 """
1912 1908 out = {}
1913 1909 user_ns = self.user_ns
1914 1910 for varname in names:
1915 1911 try:
1916 1912 value = repr(user_ns[varname])
1917 1913 except:
1918 1914 value = self._simple_error()
1919 1915 out[varname] = value
1920 1916 return out
1921 1917
1922 1918 def user_expressions(self, expressions):
1923 1919 """Evaluate a dict of expressions in the user's namespace.
1924 1920
1925 1921 Parameters
1926 1922 ----------
1927 1923 expressions : dict
1928 1924 A dict with string keys and string values. The expression values
1929 1925 should be valid Python expressions, each of which will be evaluated
1930 1926 in the user namespace.
1931 1927
1932 1928 Returns
1933 1929 -------
1934 1930 A dict, keyed like the input expressions dict, with the repr() of each
1935 1931 value.
1936 1932 """
1937 1933 out = {}
1938 1934 user_ns = self.user_ns
1939 1935 global_ns = self.user_global_ns
1940 1936 for key, expr in expressions.iteritems():
1941 1937 try:
1942 1938 value = repr(eval(expr, global_ns, user_ns))
1943 1939 except:
1944 1940 value = self._simple_error()
1945 1941 out[key] = value
1946 1942 return out
1947 1943
1948 1944 #-------------------------------------------------------------------------
1949 1945 # Things related to the running of code
1950 1946 #-------------------------------------------------------------------------
1951 1947
1952 1948 def ex(self, cmd):
1953 1949 """Execute a normal python statement in user namespace."""
1954 1950 with nested(self.builtin_trap,):
1955 1951 exec cmd in self.user_global_ns, self.user_ns
1956 1952
1957 1953 def ev(self, expr):
1958 1954 """Evaluate python expression expr in user namespace.
1959 1955
1960 1956 Returns the result of evaluation
1961 1957 """
1962 1958 with nested(self.builtin_trap,):
1963 1959 return eval(expr, self.user_global_ns, self.user_ns)
1964 1960
1965 1961 def safe_execfile(self, fname, *where, **kw):
1966 1962 """A safe version of the builtin execfile().
1967 1963
1968 1964 This version will never throw an exception, but instead print
1969 1965 helpful error messages to the screen. This only works on pure
1970 1966 Python files with the .py extension.
1971 1967
1972 1968 Parameters
1973 1969 ----------
1974 1970 fname : string
1975 1971 The name of the file to be executed.
1976 1972 where : tuple
1977 1973 One or two namespaces, passed to execfile() as (globals,locals).
1978 1974 If only one is given, it is passed as both.
1979 1975 exit_ignore : bool (False)
1980 1976 If True, then silence SystemExit for non-zero status (it is always
1981 1977 silenced for zero status, as it is so common).
1982 1978 """
1983 1979 kw.setdefault('exit_ignore', False)
1984 1980
1985 1981 fname = os.path.abspath(os.path.expanduser(fname))
1986 1982
1987 1983 # Make sure we have a .py file
1988 1984 if not fname.endswith('.py'):
1989 1985 warn('File must end with .py to be run using execfile: <%s>' % fname)
1990 1986
1991 1987 # Make sure we can open the file
1992 1988 try:
1993 1989 with open(fname) as thefile:
1994 1990 pass
1995 1991 except:
1996 1992 warn('Could not open file <%s> for safe execution.' % fname)
1997 1993 return
1998 1994
1999 1995 # Find things also in current directory. This is needed to mimic the
2000 1996 # behavior of running a script from the system command line, where
2001 1997 # Python inserts the script's directory into sys.path
2002 1998 dname = os.path.dirname(fname)
2003 1999
2004 2000 with prepended_to_syspath(dname):
2005 2001 try:
2006 2002 execfile(fname,*where)
2007 2003 except SystemExit, status:
2008 2004 # If the call was made with 0 or None exit status (sys.exit(0)
2009 2005 # or sys.exit() ), don't bother showing a traceback, as both of
2010 2006 # these are considered normal by the OS:
2011 2007 # > python -c'import sys;sys.exit(0)'; echo $?
2012 2008 # 0
2013 2009 # > python -c'import sys;sys.exit()'; echo $?
2014 2010 # 0
2015 2011 # For other exit status, we show the exception unless
2016 2012 # explicitly silenced, but only in short form.
2017 2013 if status.code not in (0, None) and not kw['exit_ignore']:
2018 2014 self.showtraceback(exception_only=True)
2019 2015 except:
2020 2016 self.showtraceback()
2021 2017
2022 2018 def safe_execfile_ipy(self, fname):
2023 2019 """Like safe_execfile, but for .ipy files with IPython syntax.
2024 2020
2025 2021 Parameters
2026 2022 ----------
2027 2023 fname : str
2028 2024 The name of the file to execute. The filename must have a
2029 2025 .ipy extension.
2030 2026 """
2031 2027 fname = os.path.abspath(os.path.expanduser(fname))
2032 2028
2033 2029 # Make sure we have a .py file
2034 2030 if not fname.endswith('.ipy'):
2035 2031 warn('File must end with .py to be run using execfile: <%s>' % fname)
2036 2032
2037 2033 # Make sure we can open the file
2038 2034 try:
2039 2035 with open(fname) as thefile:
2040 2036 pass
2041 2037 except:
2042 2038 warn('Could not open file <%s> for safe execution.' % fname)
2043 2039 return
2044 2040
2045 2041 # Find things also in current directory. This is needed to mimic the
2046 2042 # behavior of running a script from the system command line, where
2047 2043 # Python inserts the script's directory into sys.path
2048 2044 dname = os.path.dirname(fname)
2049 2045
2050 2046 with prepended_to_syspath(dname):
2051 2047 try:
2052 2048 with open(fname) as thefile:
2053 2049 # self.run_cell currently captures all exceptions
2054 2050 # raised in user code. It would be nice if there were
2055 2051 # versions of runlines, execfile that did raise, so
2056 2052 # we could catch the errors.
2057 2053 self.run_cell(thefile.read())
2058 2054 except:
2059 2055 self.showtraceback()
2060 2056 warn('Unknown failure executing file: <%s>' % fname)
2061 2057
2062 2058 def run_cell(self, cell):
2063 2059 """Run the contents of an entire multiline 'cell' of code.
2064 2060
2065 2061 The cell is split into separate blocks which can be executed
2066 2062 individually. Then, based on how many blocks there are, they are
2067 2063 executed as follows:
2068 2064
2069 2065 - A single block: 'single' mode.
2070 2066
2071 2067 If there's more than one block, it depends:
2072 2068
2073 2069 - if the last one is no more than two lines long, run all but the last
2074 2070 in 'exec' mode and the very last one in 'single' mode. This makes it
2075 2071 easy to type simple expressions at the end to see computed values. -
2076 2072 otherwise (last one is also multiline), run all in 'exec' mode
2077 2073
2078 2074 When code is executed in 'single' mode, :func:`sys.displayhook` fires,
2079 2075 results are displayed and output prompts are computed. In 'exec' mode,
2080 2076 no results are displayed unless :func:`print` is called explicitly;
2081 2077 this mode is more akin to running a script.
2082 2078
2083 2079 Parameters
2084 2080 ----------
2085 2081 cell : str
2086 2082 A single or multiline string.
2087 2083 """
2088 2084
2089 2085 # We need to break up the input into executable blocks that can be run
2090 2086 # in 'single' mode, to provide comfortable user behavior.
2091 2087 blocks = self.input_splitter.split_blocks(cell)
2092 2088
2093 2089 if not blocks:
2094 2090 return
2095 2091
2096 2092 # Store the 'ipython' version of the cell as well, since that's what
2097 2093 # needs to go into the translated history and get executed (the
2098 2094 # original cell may contain non-python syntax).
2099 2095 ipy_cell = ''.join(blocks)
2100 2096
2101 2097 # Store raw and processed history
2102 2098 self.history_manager.store_inputs(ipy_cell, cell)
2103 2099
2104 2100 self.logger.log(ipy_cell, cell)
2105 2101 # dbg code!!!
2106 2102 if 0:
2107 2103 def myapp(self, val): # dbg
2108 2104 import traceback as tb
2109 2105 stack = ''.join(tb.format_stack())
2110 2106 print 'Value:', val
2111 2107 print 'Stack:\n', stack
2112 2108 list.append(self, val)
2113 2109
2114 2110 import new
2115 self.input_hist.append = new.instancemethod(myapp, self.input_hist,
2116 list)
2111 self.input_hist.append = types.MethodType(myapp, self.input_hist)
2117 2112 # End dbg
2118 2113
2119 2114 # All user code execution must happen with our context managers active
2120 2115 with nested(self.builtin_trap, self.display_trap):
2121 2116
2122 2117 # Single-block input should behave like an interactive prompt
2123 2118 if len(blocks) == 1:
2124 2119 # since we return here, we need to update the execution count
2125 2120 out = self.run_one_block(blocks[0])
2126 2121 self.execution_count += 1
2127 2122 return out
2128 2123
2129 2124 # In multi-block input, if the last block is a simple (one-two
2130 2125 # lines) expression, run it in single mode so it produces output.
2131 2126 # Otherwise just feed the whole thing to run_code. This seems like
2132 2127 # a reasonable usability design.
2133 2128 last = blocks[-1]
2134 2129 last_nlines = len(last.splitlines())
2135 2130
2136 2131 # Note: below, whenever we call run_code, we must sync history
2137 2132 # ourselves, because run_code is NOT meant to manage history at all.
2138 2133 if last_nlines < 2:
2139 2134 # Here we consider the cell split between 'body' and 'last',
2140 2135 # store all history and execute 'body', and if successful, then
2141 2136 # proceed to execute 'last'.
2142 2137
2143 2138 # Get the main body to run as a cell
2144 2139 ipy_body = ''.join(blocks[:-1])
2145 2140 retcode = self.run_source(ipy_body, symbol='exec',
2146 2141 post_execute=False)
2147 2142 if retcode==0:
2148 2143 # And the last expression via runlines so it produces output
2149 2144 self.run_one_block(last)
2150 2145 else:
2151 2146 # Run the whole cell as one entity, storing both raw and
2152 2147 # processed input in history
2153 2148 self.run_source(ipy_cell, symbol='exec')
2154 2149
2155 2150 # Each cell is a *single* input, regardless of how many lines it has
2156 2151 self.execution_count += 1
2157 2152
2158 2153 def run_one_block(self, block):
2159 2154 """Run a single interactive block.
2160 2155
2161 2156 If the block is single-line, dynamic transformations are applied to it
2162 2157 (like automagics, autocall and alias recognition).
2163 2158 """
2164 2159 if len(block.splitlines()) <= 1:
2165 2160 out = self.run_single_line(block)
2166 2161 else:
2167 2162 out = self.run_code(block)
2168 2163 return out
2169 2164
2170 2165 def run_single_line(self, line):
2171 2166 """Run a single-line interactive statement.
2172 2167
2173 2168 This assumes the input has been transformed to IPython syntax by
2174 2169 applying all static transformations (those with an explicit prefix like
2175 2170 % or !), but it will further try to apply the dynamic ones.
2176 2171
2177 2172 It does not update history.
2178 2173 """
2179 2174 tline = self.prefilter_manager.prefilter_line(line)
2180 2175 return self.run_source(tline)
2181 2176
2182 2177 # PENDING REMOVAL: this method is slated for deletion, once our new
2183 2178 # input logic has been 100% moved to frontends and is stable.
2184 2179 def runlines(self, lines, clean=False):
2185 2180 """Run a string of one or more lines of source.
2186 2181
2187 2182 This method is capable of running a string containing multiple source
2188 2183 lines, as if they had been entered at the IPython prompt. Since it
2189 2184 exposes IPython's processing machinery, the given strings can contain
2190 2185 magic calls (%magic), special shell access (!cmd), etc.
2191 2186 """
2192 2187
2193 2188 if isinstance(lines, (list, tuple)):
2194 2189 lines = '\n'.join(lines)
2195 2190
2196 2191 if clean:
2197 2192 lines = self._cleanup_ipy_script(lines)
2198 2193
2199 2194 # We must start with a clean buffer, in case this is run from an
2200 2195 # interactive IPython session (via a magic, for example).
2201 2196 self.reset_buffer()
2202 2197 lines = lines.splitlines()
2203 2198
2204 2199 # Since we will prefilter all lines, store the user's raw input too
2205 2200 # before we apply any transformations
2206 2201 self.buffer_raw[:] = [ l+'\n' for l in lines]
2207 2202
2208 2203 more = False
2209 2204 prefilter_lines = self.prefilter_manager.prefilter_lines
2210 2205 with nested(self.builtin_trap, self.display_trap):
2211 2206 for line in lines:
2212 2207 # skip blank lines so we don't mess up the prompt counter, but
2213 2208 # do NOT skip even a blank line if we are in a code block (more
2214 2209 # is true)
2215 2210
2216 2211 if line or more:
2217 2212 more = self.push_line(prefilter_lines(line, more))
2218 2213 # IPython's run_source returns None if there was an error
2219 2214 # compiling the code. This allows us to stop processing
2220 2215 # right away, so the user gets the error message at the
2221 2216 # right place.
2222 2217 if more is None:
2223 2218 break
2224 2219 # final newline in case the input didn't have it, so that the code
2225 2220 # actually does get executed
2226 2221 if more:
2227 2222 self.push_line('\n')
2228 2223
2229 2224 def run_source(self, source, filename=None,
2230 2225 symbol='single', post_execute=True):
2231 2226 """Compile and run some source in the interpreter.
2232 2227
2233 2228 Arguments are as for compile_command().
2234 2229
2235 2230 One several things can happen:
2236 2231
2237 2232 1) The input is incorrect; compile_command() raised an
2238 2233 exception (SyntaxError or OverflowError). A syntax traceback
2239 2234 will be printed by calling the showsyntaxerror() method.
2240 2235
2241 2236 2) The input is incomplete, and more input is required;
2242 2237 compile_command() returned None. Nothing happens.
2243 2238
2244 2239 3) The input is complete; compile_command() returned a code
2245 2240 object. The code is executed by calling self.run_code() (which
2246 2241 also handles run-time exceptions, except for SystemExit).
2247 2242
2248 2243 The return value is:
2249 2244
2250 2245 - True in case 2
2251 2246
2252 2247 - False in the other cases, unless an exception is raised, where
2253 2248 None is returned instead. This can be used by external callers to
2254 2249 know whether to continue feeding input or not.
2255 2250
2256 2251 The return value can be used to decide whether to use sys.ps1 or
2257 2252 sys.ps2 to prompt the next line."""
2258 2253
2259 2254 # We need to ensure that the source is unicode from here on.
2260 2255 if type(source)==str:
2261 2256 usource = source.decode(self.stdin_encoding)
2262 2257 else:
2263 2258 usource = source
2264 2259
2265 2260 if 0: # dbg
2266 2261 print 'Source:', repr(source) # dbg
2267 2262 print 'USource:', repr(usource) # dbg
2268 2263 print 'type:', type(source) # dbg
2269 2264 print 'encoding', self.stdin_encoding # dbg
2270 2265
2271 2266 try:
2272 2267 code = self.compile(usource, symbol, self.execution_count)
2273 2268 except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError):
2274 2269 # Case 1
2275 2270 self.showsyntaxerror(filename)
2276 2271 return None
2277 2272
2278 2273 if code is None:
2279 2274 # Case 2
2280 2275 return True
2281 2276
2282 2277 # Case 3
2283 2278 # We store the code object so that threaded shells and
2284 2279 # custom exception handlers can access all this info if needed.
2285 2280 # The source corresponding to this can be obtained from the
2286 2281 # buffer attribute as '\n'.join(self.buffer).
2287 2282 self.code_to_run = code
2288 2283 # now actually execute the code object
2289 2284 if self.run_code(code, post_execute) == 0:
2290 2285 return False
2291 2286 else:
2292 2287 return None
2293 2288
2294 2289 # For backwards compatibility
2295 2290 runsource = run_source
2296 2291
2297 2292 def run_code(self, code_obj, post_execute=True):
2298 2293 """Execute a code object.
2299 2294
2300 2295 When an exception occurs, self.showtraceback() is called to display a
2301 2296 traceback.
2302 2297
2303 2298 Return value: a flag indicating whether the code to be run completed
2304 2299 successfully:
2305 2300
2306 2301 - 0: successful execution.
2307 2302 - 1: an error occurred.
2308 2303 """
2309 2304
2310 2305 # Set our own excepthook in case the user code tries to call it
2311 2306 # directly, so that the IPython crash handler doesn't get triggered
2312 2307 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
2313 2308
2314 2309 # we save the original sys.excepthook in the instance, in case config
2315 2310 # code (such as magics) needs access to it.
2316 2311 self.sys_excepthook = old_excepthook
2317 2312 outflag = 1 # happens in more places, so it's easier as default
2318 2313 try:
2319 2314 try:
2320 2315 self.hooks.pre_run_code_hook()
2321 2316 #rprint('Running code') # dbg
2322 2317 exec code_obj in self.user_global_ns, self.user_ns
2323 2318 finally:
2324 2319 # Reset our crash handler in place
2325 2320 sys.excepthook = old_excepthook
2326 2321 except SystemExit:
2327 2322 self.reset_buffer()
2328 2323 self.showtraceback(exception_only=True)
2329 2324 warn("To exit: use any of 'exit', 'quit', %Exit or Ctrl-D.", level=1)
2330 2325 except self.custom_exceptions:
2331 2326 etype,value,tb = sys.exc_info()
2332 2327 self.CustomTB(etype,value,tb)
2333 2328 except:
2334 2329 self.showtraceback()
2335 2330 else:
2336 2331 outflag = 0
2337 2332 if softspace(sys.stdout, 0):
2338 2333 print
2339 2334
2340 2335 # Execute any registered post-execution functions. Here, any errors
2341 2336 # are reported only minimally and just on the terminal, because the
2342 2337 # main exception channel may be occupied with a user traceback.
2343 2338 # FIXME: we need to think this mechanism a little more carefully.
2344 2339 if post_execute:
2345 2340 for func in self._post_execute:
2346 2341 try:
2347 2342 func()
2348 2343 except:
2349 2344 head = '[ ERROR ] Evaluating post_execute function: %s' % \
2350 2345 func
2351 2346 print >> io.Term.cout, head
2352 2347 print >> io.Term.cout, self._simple_error()
2353 2348 print >> io.Term.cout, 'Removing from post_execute'
2354 2349 self._post_execute.remove(func)
2355 2350
2356 2351 # Flush out code object which has been run (and source)
2357 2352 self.code_to_run = None
2358 2353 return outflag
2359 2354
2360 2355 # For backwards compatibility
2361 2356 runcode = run_code
2362 2357
2363 2358 # PENDING REMOVAL: this method is slated for deletion, once our new
2364 2359 # input logic has been 100% moved to frontends and is stable.
2365 2360 def push_line(self, line):
2366 2361 """Push a line to the interpreter.
2367 2362
2368 2363 The line should not have a trailing newline; it may have
2369 2364 internal newlines. The line is appended to a buffer and the
2370 2365 interpreter's run_source() method is called with the
2371 2366 concatenated contents of the buffer as source. If this
2372 2367 indicates that the command was executed or invalid, the buffer
2373 2368 is reset; otherwise, the command is incomplete, and the buffer
2374 2369 is left as it was after the line was appended. The return
2375 2370 value is 1 if more input is required, 0 if the line was dealt
2376 2371 with in some way (this is the same as run_source()).
2377 2372 """
2378 2373
2379 2374 # autoindent management should be done here, and not in the
2380 2375 # interactive loop, since that one is only seen by keyboard input. We
2381 2376 # need this done correctly even for code run via runlines (which uses
2382 2377 # push).
2383 2378
2384 2379 #print 'push line: <%s>' % line # dbg
2385 2380 self.buffer.append(line)
2386 2381 full_source = '\n'.join(self.buffer)
2387 2382 more = self.run_source(full_source, self.filename)
2388 2383 if not more:
2389 2384 self.history_manager.store_inputs('\n'.join(self.buffer_raw),
2390 2385 full_source)
2391 2386 self.reset_buffer()
2392 2387 self.execution_count += 1
2393 2388 return more
2394 2389
2395 2390 def reset_buffer(self):
2396 2391 """Reset the input buffer."""
2397 2392 self.buffer[:] = []
2398 2393 self.buffer_raw[:] = []
2399 2394 self.input_splitter.reset()
2400 2395
2401 2396 # For backwards compatibility
2402 2397 resetbuffer = reset_buffer
2403 2398
2404 2399 def _is_secondary_block_start(self, s):
2405 2400 if not s.endswith(':'):
2406 2401 return False
2407 2402 if (s.startswith('elif') or
2408 2403 s.startswith('else') or
2409 2404 s.startswith('except') or
2410 2405 s.startswith('finally')):
2411 2406 return True
2412 2407
2413 2408 def _cleanup_ipy_script(self, script):
2414 2409 """Make a script safe for self.runlines()
2415 2410
2416 2411 Currently, IPython is lines based, with blocks being detected by
2417 2412 empty lines. This is a problem for block based scripts that may
2418 2413 not have empty lines after blocks. This script adds those empty
2419 2414 lines to make scripts safe for running in the current line based
2420 2415 IPython.
2421 2416 """
2422 2417 res = []
2423 2418 lines = script.splitlines()
2424 2419 level = 0
2425 2420
2426 2421 for l in lines:
2427 2422 lstripped = l.lstrip()
2428 2423 stripped = l.strip()
2429 2424 if not stripped:
2430 2425 continue
2431 2426 newlevel = len(l) - len(lstripped)
2432 2427 if level > 0 and newlevel == 0 and \
2433 2428 not self._is_secondary_block_start(stripped):
2434 2429 # add empty line
2435 2430 res.append('')
2436 2431 res.append(l)
2437 2432 level = newlevel
2438 2433
2439 2434 return '\n'.join(res) + '\n'
2440 2435
2441 2436 #-------------------------------------------------------------------------
2442 2437 # Things related to GUI support and pylab
2443 2438 #-------------------------------------------------------------------------
2444 2439
2445 2440 def enable_pylab(self, gui=None):
2446 2441 raise NotImplementedError('Implement enable_pylab in a subclass')
2447 2442
2448 2443 #-------------------------------------------------------------------------
2449 2444 # Utilities
2450 2445 #-------------------------------------------------------------------------
2451 2446
2452 2447 def var_expand(self,cmd,depth=0):
2453 2448 """Expand python variables in a string.
2454 2449
2455 2450 The depth argument indicates how many frames above the caller should
2456 2451 be walked to look for the local namespace where to expand variables.
2457 2452
2458 2453 The global namespace for expansion is always the user's interactive
2459 2454 namespace.
2460 2455 """
2461 2456
2462 2457 return str(ItplNS(cmd,
2463 2458 self.user_ns, # globals
2464 2459 # Skip our own frame in searching for locals:
2465 2460 sys._getframe(depth+1).f_locals # locals
2466 2461 ))
2467 2462
2468 2463 def mktempfile(self, data=None, prefix='ipython_edit_'):
2469 2464 """Make a new tempfile and return its filename.
2470 2465
2471 2466 This makes a call to tempfile.mktemp, but it registers the created
2472 2467 filename internally so ipython cleans it up at exit time.
2473 2468
2474 2469 Optional inputs:
2475 2470
2476 2471 - data(None): if data is given, it gets written out to the temp file
2477 2472 immediately, and the file is closed again."""
2478 2473
2479 2474 filename = tempfile.mktemp('.py', prefix)
2480 2475 self.tempfiles.append(filename)
2481 2476
2482 2477 if data:
2483 2478 tmp_file = open(filename,'w')
2484 2479 tmp_file.write(data)
2485 2480 tmp_file.close()
2486 2481 return filename
2487 2482
2488 2483 # TODO: This should be removed when Term is refactored.
2489 2484 def write(self,data):
2490 2485 """Write a string to the default output"""
2491 2486 io.Term.cout.write(data)
2492 2487
2493 2488 # TODO: This should be removed when Term is refactored.
2494 2489 def write_err(self,data):
2495 2490 """Write a string to the default error output"""
2496 2491 io.Term.cerr.write(data)
2497 2492
2498 2493 def ask_yes_no(self,prompt,default=True):
2499 2494 if self.quiet:
2500 2495 return True
2501 2496 return ask_yes_no(prompt,default)
2502 2497
2503 2498 def show_usage(self):
2504 2499 """Show a usage message"""
2505 2500 page.page(IPython.core.usage.interactive_usage)
2506 2501
2507 2502 #-------------------------------------------------------------------------
2508 2503 # Things related to IPython exiting
2509 2504 #-------------------------------------------------------------------------
2510 2505 def atexit_operations(self):
2511 2506 """This will be executed at the time of exit.
2512 2507
2513 2508 Cleanup operations and saving of persistent data that is done
2514 2509 unconditionally by IPython should be performed here.
2515 2510
2516 2511 For things that may depend on startup flags or platform specifics (such
2517 2512 as having readline or not), register a separate atexit function in the
2518 2513 code that has the appropriate information, rather than trying to
2519 2514 clutter
2520 2515 """
2521 2516 # Cleanup all tempfiles left around
2522 2517 for tfile in self.tempfiles:
2523 2518 try:
2524 2519 os.unlink(tfile)
2525 2520 except OSError:
2526 2521 pass
2527 2522
2528 2523 # Clear all user namespaces to release all references cleanly.
2529 2524 self.reset()
2530 2525
2531 2526 # Run user hooks
2532 2527 self.hooks.shutdown_hook()
2533 2528
2534 2529 def cleanup(self):
2535 2530 self.restore_sys_module_state()
2536 2531
2537 2532
2538 2533 class InteractiveShellABC(object):
2539 2534 """An abstract base class for InteractiveShell."""
2540 2535 __metaclass__ = abc.ABCMeta
2541 2536
2542 2537 InteractiveShellABC.register(InteractiveShell)
@@ -1,892 +1,891 b''
1 1 # -*- coding: utf-8 -*-
2 2 """Tools for inspecting Python objects.
3 3
4 4 Uses syntax highlighting for presenting the various information elements.
5 5
6 6 Similar in spirit to the inspect module, but all calls take a name argument to
7 7 reference the name under which an object is being read.
8 8 """
9 9
10 10 #*****************************************************************************
11 11 # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
12 12 #
13 13 # Distributed under the terms of the BSD License. The full license is in
14 14 # the file COPYING, distributed as part of this software.
15 15 #*****************************************************************************
16 16
17 17 __all__ = ['Inspector','InspectColors']
18 18
19 19 # stdlib modules
20 20 import __builtin__
21 21 import StringIO
22 22 import inspect
23 23 import linecache
24 24 import os
25 import string
26 25 import sys
27 26 import types
28 27 from collections import namedtuple
29 28 from itertools import izip_longest
30 29
31 30 # IPython's own
32 31 from IPython.core import page
33 32 from IPython.external.Itpl import itpl
34 33 from IPython.utils import PyColorize
35 34 import IPython.utils.io
36 35 from IPython.utils.text import indent
37 36 from IPython.utils.wildcard import list_namespace
38 37 from IPython.utils.coloransi import *
39 38
40 39 #****************************************************************************
41 40 # Builtin color schemes
42 41
43 42 Colors = TermColors # just a shorthand
44 43
45 44 # Build a few color schemes
46 45 NoColor = ColorScheme(
47 46 'NoColor',{
48 47 'header' : Colors.NoColor,
49 48 'normal' : Colors.NoColor # color off (usu. Colors.Normal)
50 49 } )
51 50
52 51 LinuxColors = ColorScheme(
53 52 'Linux',{
54 53 'header' : Colors.LightRed,
55 54 'normal' : Colors.Normal # color off (usu. Colors.Normal)
56 55 } )
57 56
58 57 LightBGColors = ColorScheme(
59 58 'LightBG',{
60 59 'header' : Colors.Red,
61 60 'normal' : Colors.Normal # color off (usu. Colors.Normal)
62 61 } )
63 62
64 63 # Build table of color schemes (needed by the parser)
65 64 InspectColors = ColorSchemeTable([NoColor,LinuxColors,LightBGColors],
66 65 'Linux')
67 66
68 67 #****************************************************************************
69 68 # Auxiliary functions and objects
70 69
71 70 # See the messaging spec for the definition of all these fields. This list
72 71 # effectively defines the order of display
73 72 info_fields = ['type_name', 'base_class', 'string_form', 'namespace',
74 73 'length', 'file', 'definition', 'docstring', 'source',
75 74 'init_definition', 'class_docstring', 'init_docstring',
76 75 'call_def', 'call_docstring',
77 76 # These won't be printed but will be used to determine how to
78 77 # format the object
79 78 'ismagic', 'isalias', 'argspec', 'found', 'name',
80 79 ]
81 80
82 81
83 82 def object_info(**kw):
84 83 """Make an object info dict with all fields present."""
85 84 infodict = dict(izip_longest(info_fields, [None]))
86 85 infodict.update(kw)
87 86 return infodict
88 87
89 88
90 89 def getdoc(obj):
91 90 """Stable wrapper around inspect.getdoc.
92 91
93 92 This can't crash because of attribute problems.
94 93
95 94 It also attempts to call a getdoc() method on the given object. This
96 95 allows objects which provide their docstrings via non-standard mechanisms
97 96 (like Pyro proxies) to still be inspected by ipython's ? system."""
98 97
99 98 ds = None # default return value
100 99 try:
101 100 ds = inspect.getdoc(obj)
102 101 except:
103 102 # Harden against an inspect failure, which can occur with
104 103 # SWIG-wrapped extensions.
105 104 pass
106 105 # Allow objects to offer customized documentation via a getdoc method:
107 106 try:
108 107 ds2 = obj.getdoc()
109 108 except:
110 109 pass
111 110 else:
112 111 # if we get extra info, we add it to the normal docstring.
113 112 if ds is None:
114 113 ds = ds2
115 114 else:
116 115 ds = '%s\n%s' % (ds,ds2)
117 116 return ds
118 117
119 118
120 119 def getsource(obj,is_binary=False):
121 120 """Wrapper around inspect.getsource.
122 121
123 122 This can be modified by other projects to provide customized source
124 123 extraction.
125 124
126 125 Inputs:
127 126
128 127 - obj: an object whose source code we will attempt to extract.
129 128
130 129 Optional inputs:
131 130
132 131 - is_binary: whether the object is known to come from a binary source.
133 132 This implementation will skip returning any output for binary objects, but
134 133 custom extractors may know how to meaningfully process them."""
135 134
136 135 if is_binary:
137 136 return None
138 137 else:
139 138 try:
140 139 src = inspect.getsource(obj)
141 140 except TypeError:
142 141 if hasattr(obj,'__class__'):
143 142 src = inspect.getsource(obj.__class__)
144 143 return src
145 144
146 145 def getargspec(obj):
147 146 """Get the names and default values of a function's arguments.
148 147
149 148 A tuple of four things is returned: (args, varargs, varkw, defaults).
150 149 'args' is a list of the argument names (it may contain nested lists).
151 150 'varargs' and 'varkw' are the names of the * and ** arguments or None.
152 151 'defaults' is an n-tuple of the default values of the last n arguments.
153 152
154 153 Modified version of inspect.getargspec from the Python Standard
155 154 Library."""
156 155
157 156 if inspect.isfunction(obj):
158 157 func_obj = obj
159 158 elif inspect.ismethod(obj):
160 159 func_obj = obj.im_func
161 160 elif hasattr(obj, '__call__'):
162 161 func_obj = obj.__call__
163 162 else:
164 163 raise TypeError('arg is not a Python function')
165 164 args, varargs, varkw = inspect.getargs(func_obj.func_code)
166 165 return args, varargs, varkw, func_obj.func_defaults
167 166
168 167
169 168 def format_argspec(argspec):
170 169 """Format argspect, convenience wrapper around inspect's.
171 170
172 171 This takes a dict instead of ordered arguments and calls
173 172 inspect.format_argspec with the arguments in the necessary order.
174 173 """
175 174 return inspect.formatargspec(argspec['args'], argspec['varargs'],
176 175 argspec['varkw'], argspec['defaults'])
177 176
178 177
179 178 def call_tip(oinfo, format_call=True):
180 179 """Extract call tip data from an oinfo dict.
181 180
182 181 Parameters
183 182 ----------
184 183 oinfo : dict
185 184
186 185 format_call : bool, optional
187 186 If True, the call line is formatted and returned as a string. If not, a
188 187 tuple of (name, argspec) is returned.
189 188
190 189 Returns
191 190 -------
192 191 call_info : None, str or (str, dict) tuple.
193 192 When format_call is True, the whole call information is formattted as a
194 193 single string. Otherwise, the object's name and its argspec dict are
195 194 returned. If no call information is available, None is returned.
196 195
197 196 docstring : str or None
198 197 The most relevant docstring for calling purposes is returned, if
199 198 available. The priority is: call docstring for callable instances, then
200 199 constructor docstring for classes, then main object's docstring otherwise
201 200 (regular functions).
202 201 """
203 202 # Get call definition
204 203 argspec = oinfo['argspec']
205 204 if argspec is None:
206 205 call_line = None
207 206 else:
208 207 # Callable objects will have 'self' as their first argument, prune
209 208 # it out if it's there for clarity (since users do *not* pass an
210 209 # extra first argument explicitly).
211 210 try:
212 211 has_self = argspec['args'][0] == 'self'
213 212 except (KeyError, IndexError):
214 213 pass
215 214 else:
216 215 if has_self:
217 216 argspec['args'] = argspec['args'][1:]
218 217
219 218 call_line = oinfo['name']+format_argspec(argspec)
220 219
221 220 # Now get docstring.
222 221 # The priority is: call docstring, constructor docstring, main one.
223 222 doc = oinfo['call_docstring']
224 223 if doc is None:
225 224 doc = oinfo['init_docstring']
226 225 if doc is None:
227 226 doc = oinfo['docstring']
228 227
229 228 return call_line, doc
230 229
231 230 #****************************************************************************
232 231 # Class definitions
233 232
234 233 class myStringIO(StringIO.StringIO):
235 234 """Adds a writeln method to normal StringIO."""
236 235 def writeln(self,*arg,**kw):
237 236 """Does a write() and then a write('\n')"""
238 237 self.write(*arg,**kw)
239 238 self.write('\n')
240 239
241 240
242 241 class Inspector:
243 242 def __init__(self, color_table=InspectColors,
244 243 code_color_table=PyColorize.ANSICodeColors,
245 244 scheme='NoColor',
246 245 str_detail_level=0):
247 246 self.color_table = color_table
248 247 self.parser = PyColorize.Parser(code_color_table,out='str')
249 248 self.format = self.parser.format
250 249 self.str_detail_level = str_detail_level
251 250 self.set_active_scheme(scheme)
252 251
253 252 def _getdef(self,obj,oname=''):
254 253 """Return the definition header for any callable object.
255 254
256 255 If any exception is generated, None is returned instead and the
257 256 exception is suppressed."""
258 257
259 258 try:
260 259 # We need a plain string here, NOT unicode!
261 260 hdef = oname + inspect.formatargspec(*getargspec(obj))
262 261 return hdef.encode('ascii')
263 262 except:
264 263 return None
265 264
266 265 def __head(self,h):
267 266 """Return a header string with proper colors."""
268 267 return '%s%s%s' % (self.color_table.active_colors.header,h,
269 268 self.color_table.active_colors.normal)
270 269
271 270 def set_active_scheme(self,scheme):
272 271 self.color_table.set_active_scheme(scheme)
273 272 self.parser.color_table.set_active_scheme(scheme)
274 273
275 274 def noinfo(self,msg,oname):
276 275 """Generic message when no information is found."""
277 276 print 'No %s found' % msg,
278 277 if oname:
279 278 print 'for %s' % oname
280 279 else:
281 280 print
282 281
283 282 def pdef(self,obj,oname=''):
284 283 """Print the definition header for any callable object.
285 284
286 285 If the object is a class, print the constructor information."""
287 286
288 287 if not callable(obj):
289 288 print 'Object is not callable.'
290 289 return
291 290
292 291 header = ''
293 292
294 293 if inspect.isclass(obj):
295 294 header = self.__head('Class constructor information:\n')
296 295 obj = obj.__init__
297 296 elif type(obj) is types.InstanceType:
298 297 obj = obj.__call__
299 298
300 299 output = self._getdef(obj,oname)
301 300 if output is None:
302 301 self.noinfo('definition header',oname)
303 302 else:
304 303 print >>IPython.utils.io.Term.cout, header,self.format(output),
305 304
306 305 def pdoc(self,obj,oname='',formatter = None):
307 306 """Print the docstring for any object.
308 307
309 308 Optional:
310 309 -formatter: a function to run the docstring through for specially
311 310 formatted docstrings."""
312 311
313 312 head = self.__head # so that itpl can find it even if private
314 313 ds = getdoc(obj)
315 314 if formatter:
316 315 ds = formatter(ds)
317 316 if inspect.isclass(obj):
318 317 init_ds = getdoc(obj.__init__)
319 318 output = itpl('$head("Class Docstring:")\n'
320 319 '$indent(ds)\n'
321 320 '$head("Constructor Docstring"):\n'
322 321 '$indent(init_ds)')
323 322 elif (type(obj) is types.InstanceType or isinstance(obj,object)) \
324 323 and hasattr(obj,'__call__'):
325 324 call_ds = getdoc(obj.__call__)
326 325 if call_ds:
327 326 output = itpl('$head("Class Docstring:")\n$indent(ds)\n'
328 327 '$head("Calling Docstring:")\n$indent(call_ds)')
329 328 else:
330 329 output = ds
331 330 else:
332 331 output = ds
333 332 if output is None:
334 333 self.noinfo('documentation',oname)
335 334 return
336 335 page.page(output)
337 336
338 337 def psource(self,obj,oname=''):
339 338 """Print the source code for an object."""
340 339
341 340 # Flush the source cache because inspect can return out-of-date source
342 341 linecache.checkcache()
343 342 try:
344 343 src = getsource(obj)
345 344 except:
346 345 self.noinfo('source',oname)
347 346 else:
348 347 page.page(self.format(src))
349 348
350 349 def pfile(self,obj,oname=''):
351 350 """Show the whole file where an object was defined."""
352 351
353 352 try:
354 353 try:
355 354 lineno = inspect.getsourcelines(obj)[1]
356 355 except TypeError:
357 356 # For instances, try the class object like getsource() does
358 357 if hasattr(obj,'__class__'):
359 358 lineno = inspect.getsourcelines(obj.__class__)[1]
360 359 # Adjust the inspected object so getabsfile() below works
361 360 obj = obj.__class__
362 361 except:
363 362 self.noinfo('file',oname)
364 363 return
365 364
366 365 # We only reach this point if object was successfully queried
367 366
368 367 # run contents of file through pager starting at line
369 368 # where the object is defined
370 369 ofile = inspect.getabsfile(obj)
371 370
372 371 if (ofile.endswith('.so') or ofile.endswith('.dll')):
373 372 print 'File %r is binary, not printing.' % ofile
374 373 elif not os.path.isfile(ofile):
375 374 print 'File %r does not exist, not printing.' % ofile
376 375 else:
377 376 # Print only text files, not extension binaries. Note that
378 377 # getsourcelines returns lineno with 1-offset and page() uses
379 378 # 0-offset, so we must adjust.
380 379 page.page(self.format(open(ofile).read()),lineno-1)
381 380
382 381 def pinfo(self,obj,oname='',formatter=None,info=None,detail_level=0):
383 382 """Show detailed information about an object.
384 383
385 384 Optional arguments:
386 385
387 386 - oname: name of the variable pointing to the object.
388 387
389 388 - formatter: special formatter for docstrings (see pdoc)
390 389
391 390 - info: a structure with some information fields which may have been
392 391 precomputed already.
393 392
394 393 - detail_level: if set to 1, more information is given.
395 394 """
396 395
397 396 obj_type = type(obj)
398 397
399 398 header = self.__head
400 399 if info is None:
401 400 ismagic = 0
402 401 isalias = 0
403 402 ospace = ''
404 403 else:
405 404 ismagic = info.ismagic
406 405 isalias = info.isalias
407 406 ospace = info.namespace
408 407 # Get docstring, special-casing aliases:
409 408 if isalias:
410 409 if not callable(obj):
411 410 try:
412 411 ds = "Alias to the system command:\n %s" % obj[1]
413 412 except:
414 413 ds = "Alias: " + str(obj)
415 414 else:
416 415 ds = "Alias to " + str(obj)
417 416 if obj.__doc__:
418 417 ds += "\nDocstring:\n" + obj.__doc__
419 418 else:
420 419 ds = getdoc(obj)
421 420 if ds is None:
422 421 ds = '<no docstring>'
423 422 if formatter is not None:
424 423 ds = formatter(ds)
425 424
426 425 # store output in a list which gets joined with \n at the end.
427 426 out = myStringIO()
428 427
429 428 string_max = 200 # max size of strings to show (snipped if longer)
430 429 shalf = int((string_max -5)/2)
431 430
432 431 if ismagic:
433 432 obj_type_name = 'Magic function'
434 433 elif isalias:
435 434 obj_type_name = 'System alias'
436 435 else:
437 436 obj_type_name = obj_type.__name__
438 437 out.writeln(header('Type:\t\t')+obj_type_name)
439 438
440 439 try:
441 440 bclass = obj.__class__
442 441 out.writeln(header('Base Class:\t')+str(bclass))
443 442 except: pass
444 443
445 444 # String form, but snip if too long in ? form (full in ??)
446 445 if detail_level >= self.str_detail_level:
447 446 try:
448 447 ostr = str(obj)
449 448 str_head = 'String Form:'
450 449 if not detail_level and len(ostr)>string_max:
451 450 ostr = ostr[:shalf] + ' <...> ' + ostr[-shalf:]
452 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 453 if ostr.find('\n') > -1:
455 454 # Print multi-line strings starting at the next line.
456 455 str_sep = '\n'
457 456 else:
458 457 str_sep = '\t'
459 458 out.writeln("%s%s%s" % (header(str_head),str_sep,ostr))
460 459 except:
461 460 pass
462 461
463 462 if ospace:
464 463 out.writeln(header('Namespace:\t')+ospace)
465 464
466 465 # Length (for strings and lists)
467 466 try:
468 467 length = str(len(obj))
469 468 out.writeln(header('Length:\t\t')+length)
470 469 except: pass
471 470
472 471 # Filename where object was defined
473 472 binary_file = False
474 473 try:
475 474 try:
476 475 fname = inspect.getabsfile(obj)
477 476 except TypeError:
478 477 # For an instance, the file that matters is where its class was
479 478 # declared.
480 479 if hasattr(obj,'__class__'):
481 480 fname = inspect.getabsfile(obj.__class__)
482 481 if fname.endswith('<string>'):
483 482 fname = 'Dynamically generated function. No source code available.'
484 483 if (fname.endswith('.so') or fname.endswith('.dll')):
485 484 binary_file = True
486 485 out.writeln(header('File:\t\t')+fname)
487 486 except:
488 487 # if anything goes wrong, we don't want to show source, so it's as
489 488 # if the file was binary
490 489 binary_file = True
491 490
492 491 # reconstruct the function definition and print it:
493 492 defln = self._getdef(obj,oname)
494 493 if defln:
495 494 out.write(header('Definition:\t')+self.format(defln))
496 495
497 496 # Docstrings only in detail 0 mode, since source contains them (we
498 497 # avoid repetitions). If source fails, we add them back, see below.
499 498 if ds and detail_level == 0:
500 499 out.writeln(header('Docstring:\n') + indent(ds))
501 500
502 501 # Original source code for any callable
503 502 if detail_level:
504 503 # Flush the source cache because inspect can return out-of-date
505 504 # source
506 505 linecache.checkcache()
507 506 source_success = False
508 507 try:
509 508 try:
510 509 src = getsource(obj,binary_file)
511 510 except TypeError:
512 511 if hasattr(obj,'__class__'):
513 512 src = getsource(obj.__class__,binary_file)
514 513 if src is not None:
515 514 source = self.format(src)
516 515 out.write(header('Source:\n')+source.rstrip())
517 516 source_success = True
518 517 except Exception, msg:
519 518 pass
520 519
521 520 if ds and not source_success:
522 521 out.writeln(header('Docstring [source file open failed]:\n')
523 522 + indent(ds))
524 523
525 524 # Constructor docstring for classes
526 525 if inspect.isclass(obj):
527 526 # reconstruct the function definition and print it:
528 527 try:
529 528 obj_init = obj.__init__
530 529 except AttributeError:
531 530 init_def = init_ds = None
532 531 else:
533 532 init_def = self._getdef(obj_init,oname)
534 533 init_ds = getdoc(obj_init)
535 534 # Skip Python's auto-generated docstrings
536 535 if init_ds and \
537 536 init_ds.startswith('x.__init__(...) initializes'):
538 537 init_ds = None
539 538
540 539 if init_def or init_ds:
541 540 out.writeln(header('\nConstructor information:'))
542 541 if init_def:
543 542 out.write(header('Definition:\t')+ self.format(init_def))
544 543 if init_ds:
545 544 out.writeln(header('Docstring:\n') + indent(init_ds))
546 545 # and class docstring for instances:
547 546 elif obj_type is types.InstanceType or \
548 547 isinstance(obj,object):
549 548
550 549 # First, check whether the instance docstring is identical to the
551 550 # class one, and print it separately if they don't coincide. In
552 551 # most cases they will, but it's nice to print all the info for
553 552 # objects which use instance-customized docstrings.
554 553 if ds:
555 554 try:
556 555 cls = getattr(obj,'__class__')
557 556 except:
558 557 class_ds = None
559 558 else:
560 559 class_ds = getdoc(cls)
561 560 # Skip Python's auto-generated docstrings
562 561 if class_ds and \
563 562 (class_ds.startswith('function(code, globals[,') or \
564 563 class_ds.startswith('instancemethod(function, instance,') or \
565 564 class_ds.startswith('module(name[,') ):
566 565 class_ds = None
567 566 if class_ds and ds != class_ds:
568 567 out.writeln(header('Class Docstring:\n') +
569 568 indent(class_ds))
570 569
571 570 # Next, try to show constructor docstrings
572 571 try:
573 572 init_ds = getdoc(obj.__init__)
574 573 # Skip Python's auto-generated docstrings
575 574 if init_ds and \
576 575 init_ds.startswith('x.__init__(...) initializes'):
577 576 init_ds = None
578 577 except AttributeError:
579 578 init_ds = None
580 579 if init_ds:
581 580 out.writeln(header('Constructor Docstring:\n') +
582 581 indent(init_ds))
583 582
584 583 # Call form docstring for callable instances
585 584 if hasattr(obj,'__call__'):
586 585 #out.writeln(header('Callable:\t')+'Yes')
587 586 call_def = self._getdef(obj.__call__,oname)
588 587 #if call_def is None:
589 588 # out.writeln(header('Call def:\t')+
590 589 # 'Calling definition not available.')
591 590 if call_def is not None:
592 591 out.writeln(header('Call def:\t')+self.format(call_def))
593 592 call_ds = getdoc(obj.__call__)
594 593 # Skip Python's auto-generated docstrings
595 594 if call_ds and call_ds.startswith('x.__call__(...) <==> x(...)'):
596 595 call_ds = None
597 596 if call_ds:
598 597 out.writeln(header('Call docstring:\n') + indent(call_ds))
599 598
600 599 # Finally send to printer/pager
601 600 output = out.getvalue()
602 601 if output:
603 602 page.page(output)
604 603 # end pinfo
605 604
606 605 def info(self, obj, oname='', formatter=None, info=None, detail_level=0):
607 606 """Compute a dict with detailed information about an object.
608 607
609 608 Optional arguments:
610 609
611 610 - oname: name of the variable pointing to the object.
612 611
613 612 - formatter: special formatter for docstrings (see pdoc)
614 613
615 614 - info: a structure with some information fields which may have been
616 615 precomputed already.
617 616
618 617 - detail_level: if set to 1, more information is given.
619 618 """
620 619
621 620 obj_type = type(obj)
622 621
623 622 header = self.__head
624 623 if info is None:
625 624 ismagic = 0
626 625 isalias = 0
627 626 ospace = ''
628 627 else:
629 628 ismagic = info.ismagic
630 629 isalias = info.isalias
631 630 ospace = info.namespace
632 631
633 632 # Get docstring, special-casing aliases:
634 633 if isalias:
635 634 if not callable(obj):
636 635 try:
637 636 ds = "Alias to the system command:\n %s" % obj[1]
638 637 except:
639 638 ds = "Alias: " + str(obj)
640 639 else:
641 640 ds = "Alias to " + str(obj)
642 641 if obj.__doc__:
643 642 ds += "\nDocstring:\n" + obj.__doc__
644 643 else:
645 644 ds = getdoc(obj)
646 645 if ds is None:
647 646 ds = '<no docstring>'
648 647 if formatter is not None:
649 648 ds = formatter(ds)
650 649
651 650 # store output in a dict, we initialize it here and fill it as we go
652 651 out = dict(name=oname, found=True, isalias=isalias, ismagic=ismagic)
653 652
654 653 string_max = 200 # max size of strings to show (snipped if longer)
655 654 shalf = int((string_max -5)/2)
656 655
657 656 if ismagic:
658 657 obj_type_name = 'Magic function'
659 658 elif isalias:
660 659 obj_type_name = 'System alias'
661 660 else:
662 661 obj_type_name = obj_type.__name__
663 662 out['type_name'] = obj_type_name
664 663
665 664 try:
666 665 bclass = obj.__class__
667 666 out['base_class'] = str(bclass)
668 667 except: pass
669 668
670 669 # String form, but snip if too long in ? form (full in ??)
671 670 if detail_level >= self.str_detail_level:
672 671 try:
673 672 ostr = str(obj)
674 673 str_head = 'string_form'
675 674 if not detail_level and len(ostr)>string_max:
676 675 ostr = ostr[:shalf] + ' <...> ' + ostr[-shalf:]
677 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 678 if ostr.find('\n') > -1:
680 679 # Print multi-line strings starting at the next line.
681 680 str_sep = '\n'
682 681 else:
683 682 str_sep = '\t'
684 683 out[str_head] = ostr
685 684 except:
686 685 pass
687 686
688 687 if ospace:
689 688 out['namespace'] = ospace
690 689
691 690 # Length (for strings and lists)
692 691 try:
693 692 out['length'] = str(len(obj))
694 693 except: pass
695 694
696 695 # Filename where object was defined
697 696 binary_file = False
698 697 try:
699 698 try:
700 699 fname = inspect.getabsfile(obj)
701 700 except TypeError:
702 701 # For an instance, the file that matters is where its class was
703 702 # declared.
704 703 if hasattr(obj,'__class__'):
705 704 fname = inspect.getabsfile(obj.__class__)
706 705 if fname.endswith('<string>'):
707 706 fname = 'Dynamically generated function. No source code available.'
708 707 if (fname.endswith('.so') or fname.endswith('.dll')):
709 708 binary_file = True
710 709 out['file'] = fname
711 710 except:
712 711 # if anything goes wrong, we don't want to show source, so it's as
713 712 # if the file was binary
714 713 binary_file = True
715 714
716 715 # reconstruct the function definition and print it:
717 716 defln = self._getdef(obj, oname)
718 717 if defln:
719 718 out['definition'] = self.format(defln)
720 719
721 720 # Docstrings only in detail 0 mode, since source contains them (we
722 721 # avoid repetitions). If source fails, we add them back, see below.
723 722 if ds and detail_level == 0:
724 723 out['docstring'] = ds
725 724
726 725 # Original source code for any callable
727 726 if detail_level:
728 727 # Flush the source cache because inspect can return out-of-date
729 728 # source
730 729 linecache.checkcache()
731 730 source_success = False
732 731 try:
733 732 try:
734 733 src = getsource(obj,binary_file)
735 734 except TypeError:
736 735 if hasattr(obj,'__class__'):
737 736 src = getsource(obj.__class__,binary_file)
738 737 if src is not None:
739 738 source = self.format(src)
740 739 out['source'] = source.rstrip()
741 740 source_success = True
742 741 except Exception, msg:
743 742 pass
744 743
745 744 # Constructor docstring for classes
746 745 if inspect.isclass(obj):
747 746 # reconstruct the function definition and print it:
748 747 try:
749 748 obj_init = obj.__init__
750 749 except AttributeError:
751 750 init_def = init_ds = None
752 751 else:
753 752 init_def = self._getdef(obj_init,oname)
754 753 init_ds = getdoc(obj_init)
755 754 # Skip Python's auto-generated docstrings
756 755 if init_ds and \
757 756 init_ds.startswith('x.__init__(...) initializes'):
758 757 init_ds = None
759 758
760 759 if init_def or init_ds:
761 760 if init_def:
762 761 out['init_definition'] = self.format(init_def)
763 762 if init_ds:
764 763 out['init_docstring'] = init_ds
765 764
766 765 # and class docstring for instances:
767 766 elif obj_type is types.InstanceType or \
768 767 isinstance(obj, object):
769 768 # First, check whether the instance docstring is identical to the
770 769 # class one, and print it separately if they don't coincide. In
771 770 # most cases they will, but it's nice to print all the info for
772 771 # objects which use instance-customized docstrings.
773 772 if ds:
774 773 try:
775 774 cls = getattr(obj,'__class__')
776 775 except:
777 776 class_ds = None
778 777 else:
779 778 class_ds = getdoc(cls)
780 779 # Skip Python's auto-generated docstrings
781 780 if class_ds and \
782 781 (class_ds.startswith('function(code, globals[,') or \
783 782 class_ds.startswith('instancemethod(function, instance,') or \
784 783 class_ds.startswith('module(name[,') ):
785 784 class_ds = None
786 785 if class_ds and ds != class_ds:
787 786 out['class_docstring'] = class_ds
788 787
789 788 # Next, try to show constructor docstrings
790 789 try:
791 790 init_ds = getdoc(obj.__init__)
792 791 # Skip Python's auto-generated docstrings
793 792 if init_ds and \
794 793 init_ds.startswith('x.__init__(...) initializes'):
795 794 init_ds = None
796 795 except AttributeError:
797 796 init_ds = None
798 797 if init_ds:
799 798 out['init_docstring'] = init_ds
800 799
801 800 # Call form docstring for callable instances
802 801 if hasattr(obj, '__call__'):
803 802 call_def = self._getdef(obj.__call__, oname)
804 803 if call_def is not None:
805 804 out['call_def'] = self.format(call_def)
806 805 call_ds = getdoc(obj.__call__)
807 806 # Skip Python's auto-generated docstrings
808 807 if call_ds and call_ds.startswith('x.__call__(...) <==> x(...)'):
809 808 call_ds = None
810 809 if call_ds:
811 810 out['call_docstring'] = call_ds
812 811
813 812 # Compute the object's argspec as a callable. The key is to decide
814 813 # whether to pull it from the object itself, from its __init__ or
815 814 # from its __call__ method.
816 815
817 816 if inspect.isclass(obj):
818 817 callable_obj = obj.__init__
819 818 elif callable(obj):
820 819 callable_obj = obj
821 820 else:
822 821 callable_obj = None
823 822
824 823 if callable_obj:
825 824 try:
826 825 args, varargs, varkw, defaults = getargspec(callable_obj)
827 826 except (TypeError, AttributeError):
828 827 # For extensions/builtins we can't retrieve the argspec
829 828 pass
830 829 else:
831 830 out['argspec'] = dict(args=args, varargs=varargs,
832 831 varkw=varkw, defaults=defaults)
833 832
834 833 return object_info(**out)
835 834
836 835
837 836 def psearch(self,pattern,ns_table,ns_search=[],
838 837 ignore_case=False,show_all=False):
839 838 """Search namespaces with wildcards for objects.
840 839
841 840 Arguments:
842 841
843 842 - pattern: string containing shell-like wildcards to use in namespace
844 843 searches and optionally a type specification to narrow the search to
845 844 objects of that type.
846 845
847 846 - ns_table: dict of name->namespaces for search.
848 847
849 848 Optional arguments:
850 849
851 850 - ns_search: list of namespace names to include in search.
852 851
853 852 - ignore_case(False): make the search case-insensitive.
854 853
855 854 - show_all(False): show all names, including those starting with
856 855 underscores.
857 856 """
858 857 #print 'ps pattern:<%r>' % pattern # dbg
859 858
860 859 # defaults
861 860 type_pattern = 'all'
862 861 filter = ''
863 862
864 863 cmds = pattern.split()
865 864 len_cmds = len(cmds)
866 865 if len_cmds == 1:
867 866 # Only filter pattern given
868 867 filter = cmds[0]
869 868 elif len_cmds == 2:
870 869 # Both filter and type specified
871 870 filter,type_pattern = cmds
872 871 else:
873 872 raise ValueError('invalid argument string for psearch: <%s>' %
874 873 pattern)
875 874
876 875 # filter search namespaces
877 876 for name in ns_search:
878 877 if name not in ns_table:
879 878 raise ValueError('invalid namespace <%s>. Valid names: %s' %
880 879 (name,ns_table.keys()))
881 880
882 881 #print 'type_pattern:',type_pattern # dbg
883 882 search_result = []
884 883 for ns_name in ns_search:
885 884 ns = ns_table[ns_name]
886 885 tmp_res = list(list_namespace(ns,type_pattern,filter,
887 886 ignore_case=ignore_case,
888 887 show_all=show_all))
889 888 search_result.extend(tmp_res)
890 889 search_result.sort()
891 890
892 891 page.page('\n'.join(search_result))
@@ -1,1244 +1,1243 b''
1 1 # -*- coding: utf-8 -*-
2 2 """
3 3 ultratb.py -- Spice up your tracebacks!
4 4
5 5 * ColorTB
6 6 I've always found it a bit hard to visually parse tracebacks in Python. The
7 7 ColorTB class is a solution to that problem. It colors the different parts of a
8 8 traceback in a manner similar to what you would expect from a syntax-highlighting
9 9 text editor.
10 10
11 11 Installation instructions for ColorTB:
12 12 import sys,ultratb
13 13 sys.excepthook = ultratb.ColorTB()
14 14
15 15 * VerboseTB
16 16 I've also included a port of Ka-Ping Yee's "cgitb.py" that produces all kinds
17 17 of useful info when a traceback occurs. Ping originally had it spit out HTML
18 18 and intended it for CGI programmers, but why should they have all the fun? I
19 19 altered it to spit out colored text to the terminal. It's a bit overwhelming,
20 20 but kind of neat, and maybe useful for long-running programs that you believe
21 21 are bug-free. If a crash *does* occur in that type of program you want details.
22 22 Give it a shot--you'll love it or you'll hate it.
23 23
24 24 Note:
25 25
26 26 The Verbose mode prints the variables currently visible where the exception
27 27 happened (shortening their strings if too long). This can potentially be
28 28 very slow, if you happen to have a huge data structure whose string
29 29 representation is complex to compute. Your computer may appear to freeze for
30 30 a while with cpu usage at 100%. If this occurs, you can cancel the traceback
31 31 with Ctrl-C (maybe hitting it more than once).
32 32
33 33 If you encounter this kind of situation often, you may want to use the
34 34 Verbose_novars mode instead of the regular Verbose, which avoids formatting
35 35 variables (but otherwise includes the information and context given by
36 36 Verbose).
37 37
38 38
39 39 Installation instructions for ColorTB:
40 40 import sys,ultratb
41 41 sys.excepthook = ultratb.VerboseTB()
42 42
43 43 Note: Much of the code in this module was lifted verbatim from the standard
44 44 library module 'traceback.py' and Ka-Ping Yee's 'cgitb.py'.
45 45
46 46 * Color schemes
47 47 The colors are defined in the class TBTools through the use of the
48 48 ColorSchemeTable class. Currently the following exist:
49 49
50 50 - NoColor: allows all of this module to be used in any terminal (the color
51 51 escapes are just dummy blank strings).
52 52
53 53 - Linux: is meant to look good in a terminal like the Linux console (black
54 54 or very dark background).
55 55
56 56 - LightBG: similar to Linux but swaps dark/light colors to be more readable
57 57 in light background terminals.
58 58
59 59 You can implement other color schemes easily, the syntax is fairly
60 60 self-explanatory. Please send back new schemes you develop to the author for
61 61 possible inclusion in future releases.
62 62 """
63 63
64 64 #*****************************************************************************
65 65 # Copyright (C) 2001 Nathaniel Gray <n8gray@caltech.edu>
66 66 # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
67 67 #
68 68 # Distributed under the terms of the BSD License. The full license is in
69 69 # the file COPYING, distributed as part of this software.
70 70 #*****************************************************************************
71 71
72 72 from __future__ import with_statement
73 73
74 74 import inspect
75 75 import keyword
76 76 import linecache
77 77 import os
78 78 import pydoc
79 79 import re
80 import string
81 80 import sys
82 81 import time
83 82 import tokenize
84 83 import traceback
85 84 import types
86 85
87 86 # For purposes of monkeypatching inspect to fix a bug in it.
88 87 from inspect import getsourcefile, getfile, getmodule,\
89 88 ismodule, isclass, ismethod, isfunction, istraceback, isframe, iscode
90 89
91 90 # IPython's own modules
92 91 # Modified pdb which doesn't damage IPython's readline handling
93 92 from IPython.core import debugger, ipapi
94 93 from IPython.core.display_trap import DisplayTrap
95 94 from IPython.core.excolors import exception_colors
96 95 from IPython.utils import PyColorize
97 96 from IPython.utils import io
98 97 from IPython.utils.data import uniq_stable
99 98 from IPython.utils.warn import info, error
100 99
101 100 # Globals
102 101 # amount of space to put line numbers before verbose tracebacks
103 102 INDENT_SIZE = 8
104 103
105 104 # Default color scheme. This is used, for example, by the traceback
106 105 # formatter. When running in an actual IPython instance, the user's rc.colors
107 106 # value is used, but havinga module global makes this functionality available
108 107 # to users of ultratb who are NOT running inside ipython.
109 108 DEFAULT_SCHEME = 'NoColor'
110 109
111 110 #---------------------------------------------------------------------------
112 111 # Code begins
113 112
114 113 # Utility functions
115 114 def inspect_error():
116 115 """Print a message about internal inspect errors.
117 116
118 117 These are unfortunately quite common."""
119 118
120 119 error('Internal Python error in the inspect module.\n'
121 120 'Below is the traceback from this internal error.\n')
122 121
123 122
124 123 def findsource(object):
125 124 """Return the entire source file and starting line number for an object.
126 125
127 126 The argument may be a module, class, method, function, traceback, frame,
128 127 or code object. The source code is returned as a list of all the lines
129 128 in the file and the line number indexes a line in that list. An IOError
130 129 is raised if the source code cannot be retrieved.
131 130
132 131 FIXED version with which we monkeypatch the stdlib to work around a bug."""
133 132
134 133 file = getsourcefile(object) or getfile(object)
135 134 # If the object is a frame, then trying to get the globals dict from its
136 135 # module won't work. Instead, the frame object itself has the globals
137 136 # dictionary.
138 137 globals_dict = None
139 138 if inspect.isframe(object):
140 139 # XXX: can this ever be false?
141 140 globals_dict = object.f_globals
142 141 else:
143 142 module = getmodule(object, file)
144 143 if module:
145 144 globals_dict = module.__dict__
146 145 lines = linecache.getlines(file, globals_dict)
147 146 if not lines:
148 147 raise IOError('could not get source code')
149 148
150 149 if ismodule(object):
151 150 return lines, 0
152 151
153 152 if isclass(object):
154 153 name = object.__name__
155 154 pat = re.compile(r'^(\s*)class\s*' + name + r'\b')
156 155 # make some effort to find the best matching class definition:
157 156 # use the one with the least indentation, which is the one
158 157 # that's most probably not inside a function definition.
159 158 candidates = []
160 159 for i in range(len(lines)):
161 160 match = pat.match(lines[i])
162 161 if match:
163 162 # if it's at toplevel, it's already the best one
164 163 if lines[i][0] == 'c':
165 164 return lines, i
166 165 # else add whitespace to candidate list
167 166 candidates.append((match.group(1), i))
168 167 if candidates:
169 168 # this will sort by whitespace, and by line number,
170 169 # less whitespace first
171 170 candidates.sort()
172 171 return lines, candidates[0][1]
173 172 else:
174 173 raise IOError('could not find class definition')
175 174
176 175 if ismethod(object):
177 176 object = object.im_func
178 177 if isfunction(object):
179 178 object = object.func_code
180 179 if istraceback(object):
181 180 object = object.tb_frame
182 181 if isframe(object):
183 182 object = object.f_code
184 183 if iscode(object):
185 184 if not hasattr(object, 'co_firstlineno'):
186 185 raise IOError('could not find function definition')
187 186 pat = re.compile(r'^(\s*def\s)|(.*(?<!\w)lambda(:|\s))|^(\s*@)')
188 187 pmatch = pat.match
189 188 # fperez - fix: sometimes, co_firstlineno can give a number larger than
190 189 # the length of lines, which causes an error. Safeguard against that.
191 190 lnum = min(object.co_firstlineno,len(lines))-1
192 191 while lnum > 0:
193 192 if pmatch(lines[lnum]): break
194 193 lnum -= 1
195 194
196 195 return lines, lnum
197 196 raise IOError('could not find code object')
198 197
199 198 # Monkeypatch inspect to apply our bugfix. This code only works with py25
200 199 if sys.version_info[:2] >= (2,5):
201 200 inspect.findsource = findsource
202 201
203 202 def fix_frame_records_filenames(records):
204 203 """Try to fix the filenames in each record from inspect.getinnerframes().
205 204
206 205 Particularly, modules loaded from within zip files have useless filenames
207 206 attached to their code object, and inspect.getinnerframes() just uses it.
208 207 """
209 208 fixed_records = []
210 209 for frame, filename, line_no, func_name, lines, index in records:
211 210 # Look inside the frame's globals dictionary for __file__, which should
212 211 # be better.
213 212 better_fn = frame.f_globals.get('__file__', None)
214 213 if isinstance(better_fn, str):
215 214 # Check the type just in case someone did something weird with
216 215 # __file__. It might also be None if the error occurred during
217 216 # import.
218 217 filename = better_fn
219 218 fixed_records.append((frame, filename, line_no, func_name, lines, index))
220 219 return fixed_records
221 220
222 221
223 222 def _fixed_getinnerframes(etb, context=1,tb_offset=0):
224 223 import linecache
225 224 LNUM_POS, LINES_POS, INDEX_POS = 2, 4, 5
226 225
227 226 records = fix_frame_records_filenames(inspect.getinnerframes(etb, context))
228 227
229 228 # If the error is at the console, don't build any context, since it would
230 229 # otherwise produce 5 blank lines printed out (there is no file at the
231 230 # console)
232 231 rec_check = records[tb_offset:]
233 232 try:
234 233 rname = rec_check[0][1]
235 234 if rname == '<ipython console>' or rname.endswith('<string>'):
236 235 return rec_check
237 236 except IndexError:
238 237 pass
239 238
240 239 aux = traceback.extract_tb(etb)
241 240 assert len(records) == len(aux)
242 241 for i, (file, lnum, _, _) in zip(range(len(records)), aux):
243 242 maybeStart = lnum-1 - context//2
244 243 start = max(maybeStart, 0)
245 244 end = start + context
246 245 lines = linecache.getlines(file)[start:end]
247 246 buf = list(records[i])
248 247 buf[LNUM_POS] = lnum
249 248 buf[INDEX_POS] = lnum - 1 - start
250 249 buf[LINES_POS] = lines
251 250 records[i] = tuple(buf)
252 251 return records[tb_offset:]
253 252
254 253 # Helper function -- largely belongs to VerboseTB, but we need the same
255 254 # functionality to produce a pseudo verbose TB for SyntaxErrors, so that they
256 255 # can be recognized properly by ipython.el's py-traceback-line-re
257 256 # (SyntaxErrors have to be treated specially because they have no traceback)
258 257
259 258 _parser = PyColorize.Parser()
260 259
261 260 def _format_traceback_lines(lnum, index, lines, Colors, lvals=None,scheme=None):
262 261 numbers_width = INDENT_SIZE - 1
263 262 res = []
264 263 i = lnum - index
265 264
266 265 # This lets us get fully syntax-highlighted tracebacks.
267 266 if scheme is None:
268 267 ipinst = ipapi.get()
269 268 if ipinst is not None:
270 269 scheme = ipinst.colors
271 270 else:
272 271 scheme = DEFAULT_SCHEME
273 272
274 273 _line_format = _parser.format2
275 274
276 275 for line in lines:
277 276 # FIXME: we need to ensure the source is a pure string at this point,
278 277 # else the coloring code makes a royal mess. This is in need of a
279 278 # serious refactoring, so that all of the ultratb and PyColorize code
280 279 # is unicode-safe. So for now this is rather an ugly hack, but
281 280 # necessary to at least have readable tracebacks. Improvements welcome!
282 281 if type(line)==unicode:
283 282 line = line.encode('utf-8', 'replace')
284 283
285 284 new_line, err = _line_format(line, 'str', scheme)
286 285 if not err: line = new_line
287 286
288 287 if i == lnum:
289 288 # This is the line with the error
290 289 pad = numbers_width - len(str(i))
291 290 if pad >= 3:
292 291 marker = '-'*(pad-3) + '-> '
293 292 elif pad == 2:
294 293 marker = '> '
295 294 elif pad == 1:
296 295 marker = '>'
297 296 else:
298 297 marker = ''
299 298 num = marker + str(i)
300 299 line = '%s%s%s %s%s' %(Colors.linenoEm, num,
301 300 Colors.line, line, Colors.Normal)
302 301 else:
303 302 num = '%*s' % (numbers_width,i)
304 303 line = '%s%s%s %s' %(Colors.lineno, num,
305 304 Colors.Normal, line)
306 305
307 306 res.append(line)
308 307 if lvals and i == lnum:
309 308 res.append(lvals + '\n')
310 309 i = i + 1
311 310 return res
312 311
313 312
314 313 #---------------------------------------------------------------------------
315 314 # Module classes
316 315 class TBTools(object):
317 316 """Basic tools used by all traceback printer classes."""
318 317
319 318 # Number of frames to skip when reporting tracebacks
320 319 tb_offset = 0
321 320
322 321 def __init__(self, color_scheme='NoColor', call_pdb=False, ostream=None):
323 322 # Whether to call the interactive pdb debugger after printing
324 323 # tracebacks or not
325 324 self.call_pdb = call_pdb
326 325
327 326 # Output stream to write to. Note that we store the original value in
328 327 # a private attribute and then make the public ostream a property, so
329 328 # that we can delay accessing io.Term.cout until runtime. The way
330 329 # things are written now, the Term.cout object is dynamically managed
331 330 # so a reference to it should NEVER be stored statically. This
332 331 # property approach confines this detail to a single location, and all
333 332 # subclasses can simply access self.ostream for writing.
334 333 self._ostream = ostream
335 334
336 335 # Create color table
337 336 self.color_scheme_table = exception_colors()
338 337
339 338 self.set_colors(color_scheme)
340 339 self.old_scheme = color_scheme # save initial value for toggles
341 340
342 341 if call_pdb:
343 342 self.pdb = debugger.Pdb(self.color_scheme_table.active_scheme_name)
344 343 else:
345 344 self.pdb = None
346 345
347 346 def _get_ostream(self):
348 347 """Output stream that exceptions are written to.
349 348
350 349 Valid values are:
351 350
352 351 - None: the default, which means that IPython will dynamically resolve
353 352 to io.Term.cout. This ensures compatibility with most tools, including
354 353 Windows (where plain stdout doesn't recognize ANSI escapes).
355 354
356 355 - Any object with 'write' and 'flush' attributes.
357 356 """
358 357 return io.Term.cout if self._ostream is None else self._ostream
359 358
360 359 def _set_ostream(self, val):
361 360 assert val is None or (hasattr(val, 'write') and hasattr(val, 'flush'))
362 361 self._ostream = val
363 362
364 363 ostream = property(_get_ostream, _set_ostream)
365 364
366 365 def set_colors(self,*args,**kw):
367 366 """Shorthand access to the color table scheme selector method."""
368 367
369 368 # Set own color table
370 369 self.color_scheme_table.set_active_scheme(*args,**kw)
371 370 # for convenience, set Colors to the active scheme
372 371 self.Colors = self.color_scheme_table.active_colors
373 372 # Also set colors of debugger
374 373 if hasattr(self,'pdb') and self.pdb is not None:
375 374 self.pdb.set_colors(*args,**kw)
376 375
377 376 def color_toggle(self):
378 377 """Toggle between the currently active color scheme and NoColor."""
379 378
380 379 if self.color_scheme_table.active_scheme_name == 'NoColor':
381 380 self.color_scheme_table.set_active_scheme(self.old_scheme)
382 381 self.Colors = self.color_scheme_table.active_colors
383 382 else:
384 383 self.old_scheme = self.color_scheme_table.active_scheme_name
385 384 self.color_scheme_table.set_active_scheme('NoColor')
386 385 self.Colors = self.color_scheme_table.active_colors
387 386
388 387 def stb2text(self, stb):
389 388 """Convert a structured traceback (a list) to a string."""
390 389 return '\n'.join(stb)
391 390
392 391 def text(self, etype, value, tb, tb_offset=None, context=5):
393 392 """Return formatted traceback.
394 393
395 394 Subclasses may override this if they add extra arguments.
396 395 """
397 396 tb_list = self.structured_traceback(etype, value, tb,
398 397 tb_offset, context)
399 398 return self.stb2text(tb_list)
400 399
401 400 def structured_traceback(self, etype, evalue, tb, tb_offset=None,
402 401 context=5, mode=None):
403 402 """Return a list of traceback frames.
404 403
405 404 Must be implemented by each class.
406 405 """
407 406 raise NotImplementedError()
408 407
409 408
410 409 #---------------------------------------------------------------------------
411 410 class ListTB(TBTools):
412 411 """Print traceback information from a traceback list, with optional color.
413 412
414 413 Calling: requires 3 arguments:
415 414 (etype, evalue, elist)
416 415 as would be obtained by:
417 416 etype, evalue, tb = sys.exc_info()
418 417 if tb:
419 418 elist = traceback.extract_tb(tb)
420 419 else:
421 420 elist = None
422 421
423 422 It can thus be used by programs which need to process the traceback before
424 423 printing (such as console replacements based on the code module from the
425 424 standard library).
426 425
427 426 Because they are meant to be called without a full traceback (only a
428 427 list), instances of this class can't call the interactive pdb debugger."""
429 428
430 429 def __init__(self,color_scheme = 'NoColor', call_pdb=False, ostream=None):
431 430 TBTools.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
432 431 ostream=ostream)
433 432
434 433 def __call__(self, etype, value, elist):
435 434 self.ostream.flush()
436 435 self.ostream.write(self.text(etype, value, elist))
437 436 self.ostream.write('\n')
438 437
439 438 def structured_traceback(self, etype, value, elist, tb_offset=None,
440 439 context=5):
441 440 """Return a color formatted string with the traceback info.
442 441
443 442 Parameters
444 443 ----------
445 444 etype : exception type
446 445 Type of the exception raised.
447 446
448 447 value : object
449 448 Data stored in the exception
450 449
451 450 elist : list
452 451 List of frames, see class docstring for details.
453 452
454 453 tb_offset : int, optional
455 454 Number of frames in the traceback to skip. If not given, the
456 455 instance value is used (set in constructor).
457 456
458 457 context : int, optional
459 458 Number of lines of context information to print.
460 459
461 460 Returns
462 461 -------
463 462 String with formatted exception.
464 463 """
465 464 tb_offset = self.tb_offset if tb_offset is None else tb_offset
466 465 Colors = self.Colors
467 466 out_list = []
468 467 if elist:
469 468
470 469 if tb_offset and len(elist) > tb_offset:
471 470 elist = elist[tb_offset:]
472 471
473 472 out_list.append('Traceback %s(most recent call last)%s:' %
474 473 (Colors.normalEm, Colors.Normal) + '\n')
475 474 out_list.extend(self._format_list(elist))
476 475 # The exception info should be a single entry in the list.
477 476 lines = ''.join(self._format_exception_only(etype, value))
478 477 out_list.append(lines)
479 478
480 479 # Note: this code originally read:
481 480
482 481 ## for line in lines[:-1]:
483 482 ## out_list.append(" "+line)
484 483 ## out_list.append(lines[-1])
485 484
486 485 # This means it was indenting everything but the last line by a little
487 486 # bit. I've disabled this for now, but if we see ugliness somewhre we
488 487 # can restore it.
489 488
490 489 return out_list
491 490
492 491 def _format_list(self, extracted_list):
493 492 """Format a list of traceback entry tuples for printing.
494 493
495 494 Given a list of tuples as returned by extract_tb() or
496 495 extract_stack(), return a list of strings ready for printing.
497 496 Each string in the resulting list corresponds to the item with the
498 497 same index in the argument list. Each string ends in a newline;
499 498 the strings may contain internal newlines as well, for those items
500 499 whose source text line is not None.
501 500
502 501 Lifted almost verbatim from traceback.py
503 502 """
504 503
505 504 Colors = self.Colors
506 505 list = []
507 506 for filename, lineno, name, line in extracted_list[:-1]:
508 507 item = ' File %s"%s"%s, line %s%d%s, in %s%s%s\n' % \
509 508 (Colors.filename, filename, Colors.Normal,
510 509 Colors.lineno, lineno, Colors.Normal,
511 510 Colors.name, name, Colors.Normal)
512 511 if line:
513 512 item = item + ' %s\n' % line.strip()
514 513 list.append(item)
515 514 # Emphasize the last entry
516 515 filename, lineno, name, line = extracted_list[-1]
517 516 item = '%s File %s"%s"%s, line %s%d%s, in %s%s%s%s\n' % \
518 517 (Colors.normalEm,
519 518 Colors.filenameEm, filename, Colors.normalEm,
520 519 Colors.linenoEm, lineno, Colors.normalEm,
521 520 Colors.nameEm, name, Colors.normalEm,
522 521 Colors.Normal)
523 522 if line:
524 523 item = item + '%s %s%s\n' % (Colors.line, line.strip(),
525 524 Colors.Normal)
526 525 list.append(item)
527 526 #from pprint import pformat; print 'LISTTB', pformat(list) # dbg
528 527 return list
529 528
530 529 def _format_exception_only(self, etype, value):
531 530 """Format the exception part of a traceback.
532 531
533 532 The arguments are the exception type and value such as given by
534 533 sys.exc_info()[:2]. The return value is a list of strings, each ending
535 534 in a newline. Normally, the list contains a single string; however,
536 535 for SyntaxError exceptions, it contains several lines that (when
537 536 printed) display detailed information about where the syntax error
538 537 occurred. The message indicating which exception occurred is the
539 538 always last string in the list.
540 539
541 540 Also lifted nearly verbatim from traceback.py
542 541 """
543 542
544 543 have_filedata = False
545 544 Colors = self.Colors
546 545 list = []
547 546 try:
548 547 stype = Colors.excName + etype.__name__ + Colors.Normal
549 548 except AttributeError:
550 549 stype = etype # String exceptions don't get special coloring
551 550 if value is None:
552 551 list.append( str(stype) + '\n')
553 552 else:
554 553 if etype is SyntaxError:
555 554 try:
556 555 msg, (filename, lineno, offset, line) = value
557 556 except:
558 557 have_filedata = False
559 558 else:
560 559 have_filedata = True
561 560 #print 'filename is',filename # dbg
562 561 if not filename: filename = "<string>"
563 562 list.append('%s File %s"%s"%s, line %s%d%s\n' % \
564 563 (Colors.normalEm,
565 564 Colors.filenameEm, filename, Colors.normalEm,
566 565 Colors.linenoEm, lineno, Colors.Normal ))
567 566 if line is not None:
568 567 i = 0
569 568 while i < len(line) and line[i].isspace():
570 569 i = i+1
571 570 list.append('%s %s%s\n' % (Colors.line,
572 571 line.strip(),
573 572 Colors.Normal))
574 573 if offset is not None:
575 574 s = ' '
576 575 for c in line[i:offset-1]:
577 576 if c.isspace():
578 577 s = s + c
579 578 else:
580 579 s = s + ' '
581 580 list.append('%s%s^%s\n' % (Colors.caret, s,
582 581 Colors.Normal) )
583 582 value = msg
584 583 s = self._some_str(value)
585 584 if s:
586 585 list.append('%s%s:%s %s\n' % (str(stype), Colors.excName,
587 586 Colors.Normal, s))
588 587 else:
589 588 list.append('%s\n' % str(stype))
590 589
591 590 # sync with user hooks
592 591 if have_filedata:
593 592 ipinst = ipapi.get()
594 593 if ipinst is not None:
595 594 ipinst.hooks.synchronize_with_editor(filename, lineno, 0)
596 595
597 596 return list
598 597
599 598 def get_exception_only(self, etype, value):
600 599 """Only print the exception type and message, without a traceback.
601 600
602 601 Parameters
603 602 ----------
604 603 etype : exception type
605 604 value : exception value
606 605 """
607 606 return ListTB.structured_traceback(self, etype, value, [])
608 607
609 608
610 609 def show_exception_only(self, etype, evalue):
611 610 """Only print the exception type and message, without a traceback.
612 611
613 612 Parameters
614 613 ----------
615 614 etype : exception type
616 615 value : exception value
617 616 """
618 617 # This method needs to use __call__ from *this* class, not the one from
619 618 # a subclass whose signature or behavior may be different
620 619 ostream = self.ostream
621 620 ostream.flush()
622 621 ostream.write('\n'.join(self.get_exception_only(etype, evalue)))
623 622 ostream.flush()
624 623
625 624 def _some_str(self, value):
626 625 # Lifted from traceback.py
627 626 try:
628 627 return str(value)
629 628 except:
630 629 return '<unprintable %s object>' % type(value).__name__
631 630
632 631 #----------------------------------------------------------------------------
633 632 class VerboseTB(TBTools):
634 633 """A port of Ka-Ping Yee's cgitb.py module that outputs color text instead
635 634 of HTML. Requires inspect and pydoc. Crazy, man.
636 635
637 636 Modified version which optionally strips the topmost entries from the
638 637 traceback, to be used with alternate interpreters (because their own code
639 638 would appear in the traceback)."""
640 639
641 640 def __init__(self,color_scheme = 'Linux', call_pdb=False, ostream=None,
642 641 tb_offset=0, long_header=False, include_vars=True,
643 642 check_cache=None):
644 643 """Specify traceback offset, headers and color scheme.
645 644
646 645 Define how many frames to drop from the tracebacks. Calling it with
647 646 tb_offset=1 allows use of this handler in interpreters which will have
648 647 their own code at the top of the traceback (VerboseTB will first
649 648 remove that frame before printing the traceback info)."""
650 649 TBTools.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
651 650 ostream=ostream)
652 651 self.tb_offset = tb_offset
653 652 self.long_header = long_header
654 653 self.include_vars = include_vars
655 654 # By default we use linecache.checkcache, but the user can provide a
656 655 # different check_cache implementation. This is used by the IPython
657 656 # kernel to provide tracebacks for interactive code that is cached,
658 657 # by a compiler instance that flushes the linecache but preserves its
659 658 # own code cache.
660 659 if check_cache is None:
661 660 check_cache = linecache.checkcache
662 661 self.check_cache = check_cache
663 662
664 663 def structured_traceback(self, etype, evalue, etb, tb_offset=None,
665 664 context=5):
666 665 """Return a nice text document describing the traceback."""
667 666
668 667 tb_offset = self.tb_offset if tb_offset is None else tb_offset
669 668
670 669 # some locals
671 670 try:
672 671 etype = etype.__name__
673 672 except AttributeError:
674 673 pass
675 674 Colors = self.Colors # just a shorthand + quicker name lookup
676 675 ColorsNormal = Colors.Normal # used a lot
677 676 col_scheme = self.color_scheme_table.active_scheme_name
678 677 indent = ' '*INDENT_SIZE
679 678 em_normal = '%s\n%s%s' % (Colors.valEm, indent,ColorsNormal)
680 679 undefined = '%sundefined%s' % (Colors.em, ColorsNormal)
681 680 exc = '%s%s%s' % (Colors.excName,etype,ColorsNormal)
682 681
683 682 # some internal-use functions
684 683 def text_repr(value):
685 684 """Hopefully pretty robust repr equivalent."""
686 685 # this is pretty horrible but should always return *something*
687 686 try:
688 687 return pydoc.text.repr(value)
689 688 except KeyboardInterrupt:
690 689 raise
691 690 except:
692 691 try:
693 692 return repr(value)
694 693 except KeyboardInterrupt:
695 694 raise
696 695 except:
697 696 try:
698 697 # all still in an except block so we catch
699 698 # getattr raising
700 699 name = getattr(value, '__name__', None)
701 700 if name:
702 701 # ick, recursion
703 702 return text_repr(name)
704 703 klass = getattr(value, '__class__', None)
705 704 if klass:
706 705 return '%s instance' % text_repr(klass)
707 706 except KeyboardInterrupt:
708 707 raise
709 708 except:
710 709 return 'UNRECOVERABLE REPR FAILURE'
711 710 def eqrepr(value, repr=text_repr): return '=%s' % repr(value)
712 711 def nullrepr(value, repr=text_repr): return ''
713 712
714 713 # meat of the code begins
715 714 try:
716 715 etype = etype.__name__
717 716 except AttributeError:
718 717 pass
719 718
720 719 if self.long_header:
721 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 722 date = time.ctime(time.time())
724 723
725 724 head = '%s%s%s\n%s%s%s\n%s' % (Colors.topline, '-'*75, ColorsNormal,
726 725 exc, ' '*(75-len(str(etype))-len(pyver)),
727 726 pyver, date.rjust(75) )
728 727 head += "\nA problem occured executing Python code. Here is the sequence of function"\
729 728 "\ncalls leading up to the error, with the most recent (innermost) call last."
730 729 else:
731 730 # Simplified header
732 731 head = '%s%s%s\n%s%s' % (Colors.topline, '-'*75, ColorsNormal,exc,
733 732 'Traceback (most recent call last)'.\
734 733 rjust(75 - len(str(etype)) ) )
735 734 frames = []
736 735 # Flush cache before calling inspect. This helps alleviate some of the
737 736 # problems with python 2.3's inspect.py.
738 737 ##self.check_cache()
739 738 # Drop topmost frames if requested
740 739 try:
741 740 # Try the default getinnerframes and Alex's: Alex's fixes some
742 741 # problems, but it generates empty tracebacks for console errors
743 742 # (5 blanks lines) where none should be returned.
744 743 #records = inspect.getinnerframes(etb, context)[tb_offset:]
745 744 #print 'python records:', records # dbg
746 745 records = _fixed_getinnerframes(etb, context, tb_offset)
747 746 #print 'alex records:', records # dbg
748 747 except:
749 748
750 749 # FIXME: I've been getting many crash reports from python 2.3
751 750 # users, traceable to inspect.py. If I can find a small test-case
752 751 # to reproduce this, I should either write a better workaround or
753 752 # file a bug report against inspect (if that's the real problem).
754 753 # So far, I haven't been able to find an isolated example to
755 754 # reproduce the problem.
756 755 inspect_error()
757 756 traceback.print_exc(file=self.ostream)
758 757 info('\nUnfortunately, your original traceback can not be constructed.\n')
759 758 return ''
760 759
761 760 # build some color string templates outside these nested loops
762 761 tpl_link = '%s%%s%s' % (Colors.filenameEm,ColorsNormal)
763 762 tpl_call = 'in %s%%s%s%%s%s' % (Colors.vName, Colors.valEm,
764 763 ColorsNormal)
765 764 tpl_call_fail = 'in %s%%s%s(***failed resolving arguments***)%s' % \
766 765 (Colors.vName, Colors.valEm, ColorsNormal)
767 766 tpl_local_var = '%s%%s%s' % (Colors.vName, ColorsNormal)
768 767 tpl_global_var = '%sglobal%s %s%%s%s' % (Colors.em, ColorsNormal,
769 768 Colors.vName, ColorsNormal)
770 769 tpl_name_val = '%%s %s= %%s%s' % (Colors.valEm, ColorsNormal)
771 770 tpl_line = '%s%%s%s %%s' % (Colors.lineno, ColorsNormal)
772 771 tpl_line_em = '%s%%s%s %%s%s' % (Colors.linenoEm,Colors.line,
773 772 ColorsNormal)
774 773
775 774 # now, loop over all records printing context and info
776 775 abspath = os.path.abspath
777 776 for frame, file, lnum, func, lines, index in records:
778 777 #print '*** record:',file,lnum,func,lines,index # dbg
779 778 try:
780 779 file = file and abspath(file) or '?'
781 780 except OSError:
782 781 # if file is '<console>' or something not in the filesystem,
783 782 # the abspath call will throw an OSError. Just ignore it and
784 783 # keep the original file string.
785 784 pass
786 785 link = tpl_link % file
787 786 try:
788 787 args, varargs, varkw, locals = inspect.getargvalues(frame)
789 788 except:
790 789 # This can happen due to a bug in python2.3. We should be
791 790 # able to remove this try/except when 2.4 becomes a
792 791 # requirement. Bug details at http://python.org/sf/1005466
793 792 inspect_error()
794 793 traceback.print_exc(file=self.ostream)
795 794 info("\nIPython's exception reporting continues...\n")
796 795
797 796 if func == '?':
798 797 call = ''
799 798 else:
800 799 # Decide whether to include variable details or not
801 800 var_repr = self.include_vars and eqrepr or nullrepr
802 801 try:
803 802 call = tpl_call % (func,inspect.formatargvalues(args,
804 803 varargs, varkw,
805 804 locals,formatvalue=var_repr))
806 805 except KeyError:
807 806 # This happens in situations like errors inside generator
808 807 # expressions, where local variables are listed in the
809 808 # line, but can't be extracted from the frame. I'm not
810 809 # 100% sure this isn't actually a bug in inspect itself,
811 810 # but since there's no info for us to compute with, the
812 811 # best we can do is report the failure and move on. Here
813 812 # we must *not* call any traceback construction again,
814 813 # because that would mess up use of %debug later on. So we
815 814 # simply report the failure and move on. The only
816 815 # limitation will be that this frame won't have locals
817 816 # listed in the call signature. Quite subtle problem...
818 817 # I can't think of a good way to validate this in a unit
819 818 # test, but running a script consisting of:
820 819 # dict( (k,v.strip()) for (k,v) in range(10) )
821 820 # will illustrate the error, if this exception catch is
822 821 # disabled.
823 822 call = tpl_call_fail % func
824 823
825 824 # Initialize a list of names on the current line, which the
826 825 # tokenizer below will populate.
827 826 names = []
828 827
829 828 def tokeneater(token_type, token, start, end, line):
830 829 """Stateful tokeneater which builds dotted names.
831 830
832 831 The list of names it appends to (from the enclosing scope) can
833 832 contain repeated composite names. This is unavoidable, since
834 833 there is no way to disambguate partial dotted structures until
835 834 the full list is known. The caller is responsible for pruning
836 835 the final list of duplicates before using it."""
837 836
838 837 # build composite names
839 838 if token == '.':
840 839 try:
841 840 names[-1] += '.'
842 841 # store state so the next token is added for x.y.z names
843 842 tokeneater.name_cont = True
844 843 return
845 844 except IndexError:
846 845 pass
847 846 if token_type == tokenize.NAME and token not in keyword.kwlist:
848 847 if tokeneater.name_cont:
849 848 # Dotted names
850 849 names[-1] += token
851 850 tokeneater.name_cont = False
852 851 else:
853 852 # Regular new names. We append everything, the caller
854 853 # will be responsible for pruning the list later. It's
855 854 # very tricky to try to prune as we go, b/c composite
856 855 # names can fool us. The pruning at the end is easy
857 856 # to do (or the caller can print a list with repeated
858 857 # names if so desired.
859 858 names.append(token)
860 859 elif token_type == tokenize.NEWLINE:
861 860 raise IndexError
862 861 # we need to store a bit of state in the tokenizer to build
863 862 # dotted names
864 863 tokeneater.name_cont = False
865 864
866 865 def linereader(file=file, lnum=[lnum], getline=linecache.getline):
867 866 line = getline(file, lnum[0])
868 867 lnum[0] += 1
869 868 return line
870 869
871 870 # Build the list of names on this line of code where the exception
872 871 # occurred.
873 872 try:
874 873 # This builds the names list in-place by capturing it from the
875 874 # enclosing scope.
876 875 tokenize.tokenize(linereader, tokeneater)
877 876 except IndexError:
878 877 # signals exit of tokenizer
879 878 pass
880 879 except tokenize.TokenError,msg:
881 880 _m = ("An unexpected error occurred while tokenizing input\n"
882 881 "The following traceback may be corrupted or invalid\n"
883 882 "The error message is: %s\n" % msg)
884 883 error(_m)
885 884
886 885 # prune names list of duplicates, but keep the right order
887 886 unique_names = uniq_stable(names)
888 887
889 888 # Start loop over vars
890 889 lvals = []
891 890 if self.include_vars:
892 891 for name_full in unique_names:
893 892 name_base = name_full.split('.',1)[0]
894 893 if name_base in frame.f_code.co_varnames:
895 894 if locals.has_key(name_base):
896 895 try:
897 896 value = repr(eval(name_full,locals))
898 897 except:
899 898 value = undefined
900 899 else:
901 900 value = undefined
902 901 name = tpl_local_var % name_full
903 902 else:
904 903 if frame.f_globals.has_key(name_base):
905 904 try:
906 905 value = repr(eval(name_full,frame.f_globals))
907 906 except:
908 907 value = undefined
909 908 else:
910 909 value = undefined
911 910 name = tpl_global_var % name_full
912 911 lvals.append(tpl_name_val % (name,value))
913 912 if lvals:
914 913 lvals = '%s%s' % (indent,em_normal.join(lvals))
915 914 else:
916 915 lvals = ''
917 916
918 917 level = '%s %s\n' % (link,call)
919 918
920 919 if index is None:
921 920 frames.append(level)
922 921 else:
923 922 frames.append('%s%s' % (level,''.join(
924 923 _format_traceback_lines(lnum,index,lines,Colors,lvals,
925 924 col_scheme))))
926 925
927 926 # Get (safely) a string form of the exception info
928 927 try:
929 928 etype_str,evalue_str = map(str,(etype,evalue))
930 929 except:
931 930 # User exception is improperly defined.
932 931 etype,evalue = str,sys.exc_info()[:2]
933 932 etype_str,evalue_str = map(str,(etype,evalue))
934 933 # ... and format it
935 934 exception = ['%s%s%s: %s' % (Colors.excName, etype_str,
936 935 ColorsNormal, evalue_str)]
937 936 if type(evalue) is types.InstanceType:
938 937 try:
939 938 names = [w for w in dir(evalue) if isinstance(w, basestring)]
940 939 except:
941 940 # Every now and then, an object with funny inernals blows up
942 941 # when dir() is called on it. We do the best we can to report
943 942 # the problem and continue
944 943 _m = '%sException reporting error (object with broken dir())%s:'
945 944 exception.append(_m % (Colors.excName,ColorsNormal))
946 945 etype_str,evalue_str = map(str,sys.exc_info()[:2])
947 946 exception.append('%s%s%s: %s' % (Colors.excName,etype_str,
948 947 ColorsNormal, evalue_str))
949 948 names = []
950 949 for name in names:
951 950 value = text_repr(getattr(evalue, name))
952 951 exception.append('\n%s%s = %s' % (indent, name, value))
953 952
954 953 # vds: >>
955 954 if records:
956 955 filepath, lnum = records[-1][1:3]
957 956 #print "file:", str(file), "linenb", str(lnum) # dbg
958 957 filepath = os.path.abspath(filepath)
959 958 ipinst = ipapi.get()
960 959 if ipinst is not None:
961 960 ipinst.hooks.synchronize_with_editor(filepath, lnum, 0)
962 961 # vds: <<
963 962
964 963 # return all our info assembled as a single string
965 964 # return '%s\n\n%s\n%s' % (head,'\n'.join(frames),''.join(exception[0]) )
966 965 return [head] + frames + [''.join(exception[0])]
967 966
968 967 def debugger(self,force=False):
969 968 """Call up the pdb debugger if desired, always clean up the tb
970 969 reference.
971 970
972 971 Keywords:
973 972
974 973 - force(False): by default, this routine checks the instance call_pdb
975 974 flag and does not actually invoke the debugger if the flag is false.
976 975 The 'force' option forces the debugger to activate even if the flag
977 976 is false.
978 977
979 978 If the call_pdb flag is set, the pdb interactive debugger is
980 979 invoked. In all cases, the self.tb reference to the current traceback
981 980 is deleted to prevent lingering references which hamper memory
982 981 management.
983 982
984 983 Note that each call to pdb() does an 'import readline', so if your app
985 984 requires a special setup for the readline completers, you'll have to
986 985 fix that by hand after invoking the exception handler."""
987 986
988 987 if force or self.call_pdb:
989 988 if self.pdb is None:
990 989 self.pdb = debugger.Pdb(
991 990 self.color_scheme_table.active_scheme_name)
992 991 # the system displayhook may have changed, restore the original
993 992 # for pdb
994 993 display_trap = DisplayTrap(hook=sys.__displayhook__)
995 994 with display_trap:
996 995 self.pdb.reset()
997 996 # Find the right frame so we don't pop up inside ipython itself
998 997 if hasattr(self,'tb') and self.tb is not None:
999 998 etb = self.tb
1000 999 else:
1001 1000 etb = self.tb = sys.last_traceback
1002 1001 while self.tb is not None and self.tb.tb_next is not None:
1003 1002 self.tb = self.tb.tb_next
1004 1003 if etb and etb.tb_next:
1005 1004 etb = etb.tb_next
1006 1005 self.pdb.botframe = etb.tb_frame
1007 1006 self.pdb.interaction(self.tb.tb_frame, self.tb)
1008 1007
1009 1008 if hasattr(self,'tb'):
1010 1009 del self.tb
1011 1010
1012 1011 def handler(self, info=None):
1013 1012 (etype, evalue, etb) = info or sys.exc_info()
1014 1013 self.tb = etb
1015 1014 ostream = self.ostream
1016 1015 ostream.flush()
1017 1016 ostream.write(self.text(etype, evalue, etb))
1018 1017 ostream.write('\n')
1019 1018 ostream.flush()
1020 1019
1021 1020 # Changed so an instance can just be called as VerboseTB_inst() and print
1022 1021 # out the right info on its own.
1023 1022 def __call__(self, etype=None, evalue=None, etb=None):
1024 1023 """This hook can replace sys.excepthook (for Python 2.1 or higher)."""
1025 1024 if etb is None:
1026 1025 self.handler()
1027 1026 else:
1028 1027 self.handler((etype, evalue, etb))
1029 1028 try:
1030 1029 self.debugger()
1031 1030 except KeyboardInterrupt:
1032 1031 print "\nKeyboardInterrupt"
1033 1032
1034 1033 #----------------------------------------------------------------------------
1035 1034 class FormattedTB(VerboseTB, ListTB):
1036 1035 """Subclass ListTB but allow calling with a traceback.
1037 1036
1038 1037 It can thus be used as a sys.excepthook for Python > 2.1.
1039 1038
1040 1039 Also adds 'Context' and 'Verbose' modes, not available in ListTB.
1041 1040
1042 1041 Allows a tb_offset to be specified. This is useful for situations where
1043 1042 one needs to remove a number of topmost frames from the traceback (such as
1044 1043 occurs with python programs that themselves execute other python code,
1045 1044 like Python shells). """
1046 1045
1047 1046 def __init__(self, mode='Plain', color_scheme='Linux', call_pdb=False,
1048 1047 ostream=None,
1049 1048 tb_offset=0, long_header=False, include_vars=False,
1050 1049 check_cache=None):
1051 1050
1052 1051 # NEVER change the order of this list. Put new modes at the end:
1053 1052 self.valid_modes = ['Plain','Context','Verbose']
1054 1053 self.verbose_modes = self.valid_modes[1:3]
1055 1054
1056 1055 VerboseTB.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
1057 1056 ostream=ostream, tb_offset=tb_offset,
1058 1057 long_header=long_header, include_vars=include_vars,
1059 1058 check_cache=check_cache)
1060 1059
1061 1060 # Different types of tracebacks are joined with different separators to
1062 1061 # form a single string. They are taken from this dict
1063 1062 self._join_chars = dict(Plain='', Context='\n', Verbose='\n')
1064 1063 # set_mode also sets the tb_join_char attribute
1065 1064 self.set_mode(mode)
1066 1065
1067 1066 def _extract_tb(self,tb):
1068 1067 if tb:
1069 1068 return traceback.extract_tb(tb)
1070 1069 else:
1071 1070 return None
1072 1071
1073 1072 def structured_traceback(self, etype, value, tb, tb_offset=None, context=5):
1074 1073 tb_offset = self.tb_offset if tb_offset is None else tb_offset
1075 1074 mode = self.mode
1076 1075 if mode in self.verbose_modes:
1077 1076 # Verbose modes need a full traceback
1078 1077 return VerboseTB.structured_traceback(
1079 1078 self, etype, value, tb, tb_offset, context
1080 1079 )
1081 1080 else:
1082 1081 # We must check the source cache because otherwise we can print
1083 1082 # out-of-date source code.
1084 1083 self.check_cache()
1085 1084 # Now we can extract and format the exception
1086 1085 elist = self._extract_tb(tb)
1087 1086 return ListTB.structured_traceback(
1088 1087 self, etype, value, elist, tb_offset, context
1089 1088 )
1090 1089
1091 1090 def stb2text(self, stb):
1092 1091 """Convert a structured traceback (a list) to a string."""
1093 1092 return self.tb_join_char.join(stb)
1094 1093
1095 1094
1096 1095 def set_mode(self,mode=None):
1097 1096 """Switch to the desired mode.
1098 1097
1099 1098 If mode is not specified, cycles through the available modes."""
1100 1099
1101 1100 if not mode:
1102 1101 new_idx = ( self.valid_modes.index(self.mode) + 1 ) % \
1103 1102 len(self.valid_modes)
1104 1103 self.mode = self.valid_modes[new_idx]
1105 1104 elif mode not in self.valid_modes:
1106 1105 raise ValueError, 'Unrecognized mode in FormattedTB: <'+mode+'>\n'\
1107 1106 'Valid modes: '+str(self.valid_modes)
1108 1107 else:
1109 1108 self.mode = mode
1110 1109 # include variable details only in 'Verbose' mode
1111 1110 self.include_vars = (self.mode == self.valid_modes[2])
1112 1111 # Set the join character for generating text tracebacks
1113 1112 self.tb_join_char = self._join_chars[self.mode]
1114 1113
1115 1114 # some convenient shorcuts
1116 1115 def plain(self):
1117 1116 self.set_mode(self.valid_modes[0])
1118 1117
1119 1118 def context(self):
1120 1119 self.set_mode(self.valid_modes[1])
1121 1120
1122 1121 def verbose(self):
1123 1122 self.set_mode(self.valid_modes[2])
1124 1123
1125 1124 #----------------------------------------------------------------------------
1126 1125 class AutoFormattedTB(FormattedTB):
1127 1126 """A traceback printer which can be called on the fly.
1128 1127
1129 1128 It will find out about exceptions by itself.
1130 1129
1131 1130 A brief example:
1132 1131
1133 1132 AutoTB = AutoFormattedTB(mode = 'Verbose',color_scheme='Linux')
1134 1133 try:
1135 1134 ...
1136 1135 except:
1137 1136 AutoTB() # or AutoTB(out=logfile) where logfile is an open file object
1138 1137 """
1139 1138
1140 1139 def __call__(self,etype=None,evalue=None,etb=None,
1141 1140 out=None,tb_offset=None):
1142 1141 """Print out a formatted exception traceback.
1143 1142
1144 1143 Optional arguments:
1145 1144 - out: an open file-like object to direct output to.
1146 1145
1147 1146 - tb_offset: the number of frames to skip over in the stack, on a
1148 1147 per-call basis (this overrides temporarily the instance's tb_offset
1149 1148 given at initialization time. """
1150 1149
1151 1150
1152 1151 if out is None:
1153 1152 out = self.ostream
1154 1153 out.flush()
1155 1154 out.write(self.text(etype, evalue, etb, tb_offset))
1156 1155 out.write('\n')
1157 1156 out.flush()
1158 1157 # FIXME: we should remove the auto pdb behavior from here and leave
1159 1158 # that to the clients.
1160 1159 try:
1161 1160 self.debugger()
1162 1161 except KeyboardInterrupt:
1163 1162 print "\nKeyboardInterrupt"
1164 1163
1165 1164 def structured_traceback(self, etype=None, value=None, tb=None,
1166 1165 tb_offset=None, context=5):
1167 1166 if etype is None:
1168 1167 etype,value,tb = sys.exc_info()
1169 1168 self.tb = tb
1170 1169 return FormattedTB.structured_traceback(
1171 1170 self, etype, value, tb, tb_offset, context)
1172 1171
1173 1172 #---------------------------------------------------------------------------
1174 1173
1175 1174 # A simple class to preserve Nathan's original functionality.
1176 1175 class ColorTB(FormattedTB):
1177 1176 """Shorthand to initialize a FormattedTB in Linux colors mode."""
1178 1177 def __init__(self,color_scheme='Linux',call_pdb=0):
1179 1178 FormattedTB.__init__(self,color_scheme=color_scheme,
1180 1179 call_pdb=call_pdb)
1181 1180
1182 1181
1183 1182 class SyntaxTB(ListTB):
1184 1183 """Extension which holds some state: the last exception value"""
1185 1184
1186 1185 def __init__(self,color_scheme = 'NoColor'):
1187 1186 ListTB.__init__(self,color_scheme)
1188 1187 self.last_syntax_error = None
1189 1188
1190 1189 def __call__(self, etype, value, elist):
1191 1190 self.last_syntax_error = value
1192 1191 ListTB.__call__(self,etype,value,elist)
1193 1192
1194 1193 def clear_err_state(self):
1195 1194 """Return the current error state and clear it"""
1196 1195 e = self.last_syntax_error
1197 1196 self.last_syntax_error = None
1198 1197 return e
1199 1198
1200 1199 def stb2text(self, stb):
1201 1200 """Convert a structured traceback (a list) to a string."""
1202 1201 return ''.join(stb)
1203 1202
1204 1203
1205 1204 #----------------------------------------------------------------------------
1206 1205 # module testing (minimal)
1207 1206 if __name__ == "__main__":
1208 1207 def spam(c, (d, e)):
1209 1208 x = c + d
1210 1209 y = c * d
1211 1210 foo(x, y)
1212 1211
1213 1212 def foo(a, b, bar=1):
1214 1213 eggs(a, b + bar)
1215 1214
1216 1215 def eggs(f, g, z=globals()):
1217 1216 h = f + g
1218 1217 i = f - g
1219 1218 return h / i
1220 1219
1221 1220 print ''
1222 1221 print '*** Before ***'
1223 1222 try:
1224 1223 print spam(1, (2, 3))
1225 1224 except:
1226 1225 traceback.print_exc()
1227 1226 print ''
1228 1227
1229 1228 handler = ColorTB()
1230 1229 print '*** ColorTB ***'
1231 1230 try:
1232 1231 print spam(1, (2, 3))
1233 1232 except:
1234 1233 apply(handler, sys.exc_info() )
1235 1234 print ''
1236 1235
1237 1236 handler = VerboseTB()
1238 1237 print '*** VerboseTB ***'
1239 1238 try:
1240 1239 print spam(1, (2, 3))
1241 1240 except:
1242 1241 apply(handler, sys.exc_info() )
1243 1242 print ''
1244 1243
@@ -1,275 +1,274 b''
1 1 # -*- coding: utf-8 -*-
2 2 """String interpolation for Python (by Ka-Ping Yee, 14 Feb 2000).
3 3
4 4 This module lets you quickly and conveniently interpolate values into
5 5 strings (in the flavour of Perl or Tcl, but with less extraneous
6 6 punctuation). You get a bit more power than in the other languages,
7 7 because this module allows subscripting, slicing, function calls,
8 8 attribute lookup, or arbitrary expressions. Variables and expressions
9 9 are evaluated in the namespace of the caller.
10 10
11 11 The itpl() function returns the result of interpolating a string, and
12 12 printpl() prints out an interpolated string. Here are some examples:
13 13
14 14 from Itpl import printpl
15 15 printpl("Here is a $string.")
16 16 printpl("Here is a $module.member.")
17 17 printpl("Here is an $object.member.")
18 18 printpl("Here is a $functioncall(with, arguments).")
19 19 printpl("Here is an ${arbitrary + expression}.")
20 20 printpl("Here is an $array[3] member.")
21 21 printpl("Here is a $dictionary['member'].")
22 22
23 23 The filter() function filters a file object so that output through it
24 24 is interpolated. This lets you produce the illusion that Python knows
25 25 how to do interpolation:
26 26
27 27 import Itpl
28 28 sys.stdout = Itpl.filter()
29 29 f = "fancy"
30 30 print "Is this not $f?"
31 31 print "Standard output has been replaced with a $sys.stdout object."
32 32 sys.stdout = Itpl.unfilter()
33 33 print "Okay, back $to $normal."
34 34
35 35 Under the hood, the Itpl class represents a string that knows how to
36 36 interpolate values. An instance of the class parses the string once
37 37 upon initialization; the evaluation and substitution can then be done
38 38 each time the instance is evaluated with str(instance). For example:
39 39
40 40 from Itpl import Itpl
41 41 s = Itpl("Here is $foo.")
42 42 foo = 5
43 43 print str(s)
44 44 foo = "bar"
45 45 print str(s)
46 46 """
47 47
48 48 #*****************************************************************************
49 49 #
50 50 # Copyright (c) 2001 Ka-Ping Yee <ping@lfw.org>
51 51 #
52 52 #
53 53 # Published under the terms of the MIT license, hereby reproduced:
54 54 #
55 55 # Permission is hereby granted, free of charge, to any person obtaining a copy
56 56 # of this software and associated documentation files (the "Software"), to
57 57 # deal in the Software without restriction, including without limitation the
58 58 # rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
59 59 # sell copies of the Software, and to permit persons to whom the Software is
60 60 # furnished to do so, subject to the following conditions:
61 61 #
62 62 # The above copyright notice and this permission notice shall be included in
63 63 # all copies or substantial portions of the Software.
64 64 #
65 65 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
66 66 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
67 67 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
68 68 # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
69 69 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
70 70 # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
71 71 # IN THE SOFTWARE.
72 72 #
73 73 #*****************************************************************************
74 74
75 75 __author__ = 'Ka-Ping Yee <ping@lfw.org>'
76 76 __license__ = 'MIT'
77 77
78 import string
79 78 import sys
80 79 from tokenize import tokenprog
81 80
82 81 class ItplError(ValueError):
83 82 def __init__(self, text, pos):
84 83 self.text = text
85 84 self.pos = pos
86 85 def __str__(self):
87 86 return "unfinished expression in %s at char %d" % (
88 87 repr(self.text), self.pos)
89 88
90 89 def matchorfail(text, pos):
91 90 match = tokenprog.match(text, pos)
92 91 if match is None:
93 92 raise ItplError(text, pos)
94 93 return match, match.end()
95 94
96 95 class Itpl:
97 96 """Class representing a string with interpolation abilities.
98 97
99 98 Upon creation, an instance works out what parts of the format
100 99 string are literal and what parts need to be evaluated. The
101 100 evaluation and substitution happens in the namespace of the
102 101 caller when str(instance) is called."""
103 102
104 103 def __init__(self, format,codec='utf_8',encoding_errors='backslashreplace'):
105 104 """The single mandatory argument to this constructor is a format
106 105 string.
107 106
108 107 The format string is parsed according to the following rules:
109 108
110 109 1. A dollar sign and a name, possibly followed by any of:
111 110 - an open-paren, and anything up to the matching paren
112 111 - an open-bracket, and anything up to the matching bracket
113 112 - a period and a name
114 113 any number of times, is evaluated as a Python expression.
115 114
116 115 2. A dollar sign immediately followed by an open-brace, and
117 116 anything up to the matching close-brace, is evaluated as
118 117 a Python expression.
119 118
120 119 3. Outside of the expressions described in the above two rules,
121 120 two dollar signs in a row give you one literal dollar sign.
122 121
123 122 Optional arguments:
124 123
125 124 - codec('utf_8'): a string containing the name of a valid Python
126 125 codec.
127 126
128 127 - encoding_errors('backslashreplace'): a string with a valid error handling
129 128 policy. See the codecs module documentation for details.
130 129
131 130 These are used to encode the format string if a call to str() fails on
132 131 the expanded result."""
133 132
134 133 if not isinstance(format,basestring):
135 134 raise TypeError, "needs string initializer"
136 135 self.format = format
137 136 self.codec = codec
138 137 self.encoding_errors = encoding_errors
139 138
140 139 namechars = "abcdefghijklmnopqrstuvwxyz" \
141 140 "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_";
142 141 chunks = []
143 142 pos = 0
144 143
145 144 while 1:
146 145 dollar = format.find("$", pos)
147 146 if dollar < 0: break
148 147 nextchar = format[dollar+1]
149 148
150 149 if nextchar == "{":
151 150 chunks.append((0, format[pos:dollar]))
152 151 pos, level = dollar+2, 1
153 152 while level:
154 153 match, pos = matchorfail(format, pos)
155 154 tstart, tend = match.regs[3]
156 155 token = format[tstart:tend]
157 156 if token == "{": level = level+1
158 157 elif token == "}": level = level-1
159 158 chunks.append((1, format[dollar+2:pos-1]))
160 159
161 160 elif nextchar in namechars:
162 161 chunks.append((0, format[pos:dollar]))
163 162 match, pos = matchorfail(format, dollar+1)
164 163 while pos < len(format):
165 164 if format[pos] == "." and \
166 165 pos+1 < len(format) and format[pos+1] in namechars:
167 166 match, pos = matchorfail(format, pos+1)
168 167 elif format[pos] in "([":
169 168 pos, level = pos+1, 1
170 169 while level:
171 170 match, pos = matchorfail(format, pos)
172 171 tstart, tend = match.regs[3]
173 172 token = format[tstart:tend]
174 173 if token[0] in "([": level = level+1
175 174 elif token[0] in ")]": level = level-1
176 175 else: break
177 176 chunks.append((1, format[dollar+1:pos]))
178 177
179 178 else:
180 179 chunks.append((0, format[pos:dollar+1]))
181 180 pos = dollar + 1 + (nextchar == "$")
182 181
183 182 if pos < len(format): chunks.append((0, format[pos:]))
184 183 self.chunks = chunks
185 184
186 185 def __repr__(self):
187 186 return "<Itpl %s >" % repr(self.format)
188 187
189 188 def _str(self,glob,loc):
190 189 """Evaluate to a string in the given globals/locals.
191 190
192 191 The final output is built by calling str(), but if this fails, the
193 192 result is encoded with the instance's codec and error handling policy,
194 193 via a call to out.encode(self.codec,self.encoding_errors)"""
195 194 result = []
196 195 app = result.append
197 196 for live, chunk in self.chunks:
198 197 if live: app(str(eval(chunk,glob,loc)))
199 198 else: app(chunk)
200 199 out = ''.join(result)
201 200 try:
202 201 return str(out)
203 202 except UnicodeError:
204 203 return out.encode(self.codec,self.encoding_errors)
205 204
206 205 def __str__(self):
207 206 """Evaluate and substitute the appropriate parts of the string."""
208 207
209 208 # We need to skip enough frames to get to the actual caller outside of
210 209 # Itpl.
211 210 frame = sys._getframe(1)
212 211 while frame.f_globals["__name__"] == __name__: frame = frame.f_back
213 212 loc, glob = frame.f_locals, frame.f_globals
214 213
215 214 return self._str(glob,loc)
216 215
217 216 class ItplNS(Itpl):
218 217 """Class representing a string with interpolation abilities.
219 218
220 219 This inherits from Itpl, but at creation time a namespace is provided
221 220 where the evaluation will occur. The interpolation becomes a bit more
222 221 efficient, as no traceback needs to be extracte. It also allows the
223 222 caller to supply a different namespace for the interpolation to occur than
224 223 its own."""
225 224
226 225 def __init__(self, format,globals,locals=None,
227 226 codec='utf_8',encoding_errors='backslashreplace'):
228 227 """ItplNS(format,globals[,locals]) -> interpolating string instance.
229 228
230 229 This constructor, besides a format string, takes a globals dictionary
231 230 and optionally a locals (which defaults to globals if not provided).
232 231
233 232 For further details, see the Itpl constructor."""
234 233
235 234 if locals is None:
236 235 locals = globals
237 236 self.globals = globals
238 237 self.locals = locals
239 238 Itpl.__init__(self,format,codec,encoding_errors)
240 239
241 240 def __str__(self):
242 241 """Evaluate and substitute the appropriate parts of the string."""
243 242 return self._str(self.globals,self.locals)
244 243
245 244 def __repr__(self):
246 245 return "<ItplNS %s >" % repr(self.format)
247 246
248 247 # utilities for fast printing
249 248 def itpl(text): return str(Itpl(text))
250 249 def printpl(text): print itpl(text)
251 250 # versions with namespace
252 251 def itplns(text,globals,locals=None): return str(ItplNS(text,globals,locals))
253 252 def printplns(text,globals,locals=None): print itplns(text,globals,locals)
254 253
255 254 class ItplFile:
256 255 """A file object that filters each write() through an interpolator."""
257 256 def __init__(self, file): self.file = file
258 257 def __repr__(self): return "<interpolated " + repr(self.file) + ">"
259 258 def __getattr__(self, attr): return getattr(self.file, attr)
260 259 def write(self, text): self.file.write(str(Itpl(text)))
261 260
262 261 def filter(file=sys.stdout):
263 262 """Return an ItplFile that filters writes to the given file object.
264 263
265 264 'file = filter(file)' replaces 'file' with a filtered object that
266 265 has a write() method. When called with no argument, this creates
267 266 a filter to sys.stdout."""
268 267 return ItplFile(file)
269 268
270 269 def unfilter(ifile=None):
271 270 """Return the original file that corresponds to the given ItplFile.
272 271
273 272 'file = unfilter(file)' undoes the effect of 'file = filter(file)'.
274 273 'sys.stdout = unfilter()' undoes the effect of 'sys.stdout = filter()'."""
275 274 return ifile and ifile.file or sys.stdout.file
@@ -1,1845 +1,1843 b''
1 1 """Pexpect is a Python module for spawning child applications and controlling
2 2 them automatically. Pexpect can be used for automating interactive applications
3 3 such as ssh, ftp, passwd, telnet, etc. It can be used to a automate setup
4 4 scripts for duplicating software package installations on different servers. It
5 5 can be used for automated software testing. Pexpect is in the spirit of Don
6 6 Libes' Expect, but Pexpect is pure Python. Other Expect-like modules for Python
7 7 require TCL and Expect or require C extensions to be compiled. Pexpect does not
8 8 use C, Expect, or TCL extensions. It should work on any platform that supports
9 9 the standard Python pty module. The Pexpect interface focuses on ease of use so
10 10 that simple tasks are easy.
11 11
12 12 There are two main interfaces to Pexpect -- the function, run() and the class,
13 13 spawn. You can call the run() function to execute a command and return the
14 14 output. This is a handy replacement for os.system().
15 15
16 16 For example::
17 17
18 18 pexpect.run('ls -la')
19 19
20 20 The more powerful interface is the spawn class. You can use this to spawn an
21 21 external child command and then interact with the child by sending lines and
22 22 expecting responses.
23 23
24 24 For example::
25 25
26 26 child = pexpect.spawn('scp foo myname@host.example.com:.')
27 27 child.expect ('Password:')
28 28 child.sendline (mypassword)
29 29
30 30 This works even for commands that ask for passwords or other input outside of
31 31 the normal stdio streams.
32 32
33 33 Credits: Noah Spurrier, Richard Holden, Marco Molteni, Kimberley Burchett,
34 34 Robert Stone, Hartmut Goebel, Chad Schroeder, Erick Tryzelaar, Dave Kirby, Ids
35 35 vander Molen, George Todd, Noel Taylor, Nicolas D. Cesar, Alexander Gattin,
36 36 Geoffrey Marshall, Francisco Lourenco, Glen Mabey, Karthik Gurusamy, Fernando
37 37 Perez, Corey Minyard, Jon Cohen, Guillaume Chazarain, Andrew Ryan, Nick
38 38 Craig-Wood, Andrew Stone, Jorgen Grahn (Let me know if I forgot anyone.)
39 39
40 40 Free, open source, and all that good stuff.
41 41
42 42 Permission is hereby granted, free of charge, to any person obtaining a copy of
43 43 this software and associated documentation files (the "Software"), to deal in
44 44 the Software without restriction, including without limitation the rights to
45 45 use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
46 46 of the Software, and to permit persons to whom the Software is furnished to do
47 47 so, subject to the following conditions:
48 48
49 49 The above copyright notice and this permission notice shall be included in all
50 50 copies or substantial portions of the Software.
51 51
52 52 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
53 53 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
54 54 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
55 55 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
56 56 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
57 57 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
58 58 SOFTWARE.
59 59
60 60 Pexpect Copyright (c) 2008 Noah Spurrier
61 61 http://pexpect.sourceforge.net/
62 62
63 63 $Id: pexpect.py 507 2007-12-27 02:40:52Z noah $
64 64 """
65 65
66 66 try:
67 67 import os, sys, time
68 68 import select
69 import string
70 69 import re
71 70 import struct
72 71 import resource
73 72 import types
74 73 import pty
75 74 import tty
76 75 import termios
77 76 import fcntl
78 77 import errno
79 78 import traceback
80 79 import signal
81 80 except ImportError, e:
82 81 raise ImportError (str(e) + """
83 82
84 83 A critical module was not found. Probably this operating system does not
85 84 support it. Pexpect is intended for UNIX-like operating systems.""")
86 85
87 86 __version__ = '2.3'
88 87 __revision__ = '$Revision: 399 $'
89 88 __all__ = ['ExceptionPexpect', 'EOF', 'TIMEOUT', 'spawn', 'run', 'which',
90 89 'split_command_line', '__version__', '__revision__']
91 90
92 91 # Exception classes used by this module.
93 92 class ExceptionPexpect(Exception):
94 93
95 94 """Base class for all exceptions raised by this module.
96 95 """
97 96
98 97 def __init__(self, value):
99 98
100 99 self.value = value
101 100
102 101 def __str__(self):
103 102
104 103 return str(self.value)
105 104
106 105 def get_trace(self):
107 106
108 107 """This returns an abbreviated stack trace with lines that only concern
109 108 the caller. In other words, the stack trace inside the Pexpect module
110 109 is not included. """
111 110
112 111 tblist = traceback.extract_tb(sys.exc_info()[2])
113 112 #tblist = filter(self.__filter_not_pexpect, tblist)
114 113 tblist = [item for item in tblist if self.__filter_not_pexpect(item)]
115 114 tblist = traceback.format_list(tblist)
116 115 return ''.join(tblist)
117 116
118 117 def __filter_not_pexpect(self, trace_list_item):
119 118
120 119 """This returns True if list item 0 the string 'pexpect.py' in it. """
121 120
122 121 if trace_list_item[0].find('pexpect.py') == -1:
123 122 return True
124 123 else:
125 124 return False
126 125
127 126 class EOF(ExceptionPexpect):
128 127
129 128 """Raised when EOF is read from a child. This usually means the child has exited."""
130 129
131 130 class TIMEOUT(ExceptionPexpect):
132 131
133 132 """Raised when a read time exceeds the timeout. """
134 133
135 134 ##class TIMEOUT_PATTERN(TIMEOUT):
136 135 ## """Raised when the pattern match time exceeds the timeout.
137 136 ## This is different than a read TIMEOUT because the child process may
138 137 ## give output, thus never give a TIMEOUT, but the output
139 138 ## may never match a pattern.
140 139 ## """
141 140 ##class MAXBUFFER(ExceptionPexpect):
142 141 ## """Raised when a scan buffer fills before matching an expected pattern."""
143 142
144 143 def run (command, timeout=-1, withexitstatus=False, events=None, extra_args=None, logfile=None, cwd=None, env=None):
145 144
146 145 """
147 146 This function runs the given command; waits for it to finish; then
148 147 returns all output as a string. STDERR is included in output. If the full
149 148 path to the command is not given then the path is searched.
150 149
151 150 Note that lines are terminated by CR/LF (\\r\\n) combination even on
152 151 UNIX-like systems because this is the standard for pseudo ttys. If you set
153 152 'withexitstatus' to true, then run will return a tuple of (command_output,
154 153 exitstatus). If 'withexitstatus' is false then this returns just
155 154 command_output.
156 155
157 156 The run() function can often be used instead of creating a spawn instance.
158 157 For example, the following code uses spawn::
159 158
160 159 from pexpect import *
161 160 child = spawn('scp foo myname@host.example.com:.')
162 161 child.expect ('(?i)password')
163 162 child.sendline (mypassword)
164 163
165 164 The previous code can be replace with the following::
166 165
167 166 from pexpect import *
168 167 run ('scp foo myname@host.example.com:.', events={'(?i)password': mypassword})
169 168
170 169 Examples
171 170 ========
172 171
173 172 Start the apache daemon on the local machine::
174 173
175 174 from pexpect import *
176 175 run ("/usr/local/apache/bin/apachectl start")
177 176
178 177 Check in a file using SVN::
179 178
180 179 from pexpect import *
181 180 run ("svn ci -m 'automatic commit' my_file.py")
182 181
183 182 Run a command and capture exit status::
184 183
185 184 from pexpect import *
186 185 (command_output, exitstatus) = run ('ls -l /bin', withexitstatus=1)
187 186
188 187 Tricky Examples
189 188 ===============
190 189
191 190 The following will run SSH and execute 'ls -l' on the remote machine. The
192 191 password 'secret' will be sent if the '(?i)password' pattern is ever seen::
193 192
194 193 run ("ssh username@machine.example.com 'ls -l'", events={'(?i)password':'secret\\n'})
195 194
196 195 This will start mencoder to rip a video from DVD. This will also display
197 196 progress ticks every 5 seconds as it runs. For example::
198 197
199 198 from pexpect import *
200 199 def print_ticks(d):
201 200 print d['event_count'],
202 201 run ("mencoder dvd://1 -o video.avi -oac copy -ovc copy", events={TIMEOUT:print_ticks}, timeout=5)
203 202
204 203 The 'events' argument should be a dictionary of patterns and responses.
205 204 Whenever one of the patterns is seen in the command out run() will send the
206 205 associated response string. Note that you should put newlines in your
207 206 string if Enter is necessary. The responses may also contain callback
208 207 functions. Any callback is function that takes a dictionary as an argument.
209 208 The dictionary contains all the locals from the run() function, so you can
210 209 access the child spawn object or any other variable defined in run()
211 210 (event_count, child, and extra_args are the most useful). A callback may
212 211 return True to stop the current run process otherwise run() continues until
213 212 the next event. A callback may also return a string which will be sent to
214 213 the child. 'extra_args' is not used by directly run(). It provides a way to
215 214 pass data to a callback function through run() through the locals
216 215 dictionary passed to a callback. """
217 216
218 217 if timeout == -1:
219 218 child = spawn(command, maxread=2000, logfile=logfile, cwd=cwd, env=env)
220 219 else:
221 220 child = spawn(command, timeout=timeout, maxread=2000, logfile=logfile, cwd=cwd, env=env)
222 221 if events is not None:
223 222 patterns = events.keys()
224 223 responses = events.values()
225 224 else:
226 225 patterns=None # We assume that EOF or TIMEOUT will save us.
227 226 responses=None
228 227 child_result_list = []
229 228 event_count = 0
230 229 while 1:
231 230 try:
232 231 index = child.expect (patterns)
233 232 if type(child.after) in types.StringTypes:
234 233 child_result_list.append(child.before + child.after)
235 234 else: # child.after may have been a TIMEOUT or EOF, so don't cat those.
236 235 child_result_list.append(child.before)
237 236 if type(responses[index]) in types.StringTypes:
238 237 child.send(responses[index])
239 238 elif type(responses[index]) is types.FunctionType:
240 239 callback_result = responses[index](locals())
241 240 sys.stdout.flush()
242 241 if type(callback_result) in types.StringTypes:
243 242 child.send(callback_result)
244 243 elif callback_result:
245 244 break
246 245 else:
247 246 raise TypeError ('The callback must be a string or function type.')
248 247 event_count = event_count + 1
249 248 except TIMEOUT, e:
250 249 child_result_list.append(child.before)
251 250 break
252 251 except EOF, e:
253 252 child_result_list.append(child.before)
254 253 break
255 254 child_result = ''.join(child_result_list)
256 255 if withexitstatus:
257 256 child.close()
258 257 return (child_result, child.exitstatus)
259 258 else:
260 259 return child_result
261 260
262 261 class spawn (object):
263 262
264 263 """This is the main class interface for Pexpect. Use this class to start
265 264 and control child applications. """
266 265
267 266 def __init__(self, command, args=[], timeout=30, maxread=2000, searchwindowsize=None, logfile=None, cwd=None, env=None):
268 267
269 268 """This is the constructor. The command parameter may be a string that
270 269 includes a command and any arguments to the command. For example::
271 270
272 271 child = pexpect.spawn ('/usr/bin/ftp')
273 272 child = pexpect.spawn ('/usr/bin/ssh user@example.com')
274 273 child = pexpect.spawn ('ls -latr /tmp')
275 274
276 275 You may also construct it with a list of arguments like so::
277 276
278 277 child = pexpect.spawn ('/usr/bin/ftp', [])
279 278 child = pexpect.spawn ('/usr/bin/ssh', ['user@example.com'])
280 279 child = pexpect.spawn ('ls', ['-latr', '/tmp'])
281 280
282 281 After this the child application will be created and will be ready to
283 282 talk to. For normal use, see expect() and send() and sendline().
284 283
285 284 Remember that Pexpect does NOT interpret shell meta characters such as
286 285 redirect, pipe, or wild cards (>, |, or *). This is a common mistake.
287 286 If you want to run a command and pipe it through another command then
288 287 you must also start a shell. For example::
289 288
290 289 child = pexpect.spawn('/bin/bash -c "ls -l | grep LOG > log_list.txt"')
291 290 child.expect(pexpect.EOF)
292 291
293 292 The second form of spawn (where you pass a list of arguments) is useful
294 293 in situations where you wish to spawn a command and pass it its own
295 294 argument list. This can make syntax more clear. For example, the
296 295 following is equivalent to the previous example::
297 296
298 297 shell_cmd = 'ls -l | grep LOG > log_list.txt'
299 298 child = pexpect.spawn('/bin/bash', ['-c', shell_cmd])
300 299 child.expect(pexpect.EOF)
301 300
302 301 The maxread attribute sets the read buffer size. This is maximum number
303 302 of bytes that Pexpect will try to read from a TTY at one time. Setting
304 303 the maxread size to 1 will turn off buffering. Setting the maxread
305 304 value higher may help performance in cases where large amounts of
306 305 output are read back from the child. This feature is useful in
307 306 conjunction with searchwindowsize.
308 307
309 308 The searchwindowsize attribute sets the how far back in the incomming
310 309 seach buffer Pexpect will search for pattern matches. Every time
311 310 Pexpect reads some data from the child it will append the data to the
312 311 incomming buffer. The default is to search from the beginning of the
313 312 imcomming buffer each time new data is read from the child. But this is
314 313 very inefficient if you are running a command that generates a large
315 314 amount of data where you want to match The searchwindowsize does not
316 315 effect the size of the incomming data buffer. You will still have
317 316 access to the full buffer after expect() returns.
318 317
319 318 The logfile member turns on or off logging. All input and output will
320 319 be copied to the given file object. Set logfile to None to stop
321 320 logging. This is the default. Set logfile to sys.stdout to echo
322 321 everything to standard output. The logfile is flushed after each write.
323 322
324 323 Example log input and output to a file::
325 324
326 325 child = pexpect.spawn('some_command')
327 326 fout = file('mylog.txt','w')
328 327 child.logfile = fout
329 328
330 329 Example log to stdout::
331 330
332 331 child = pexpect.spawn('some_command')
333 332 child.logfile = sys.stdout
334 333
335 334 The logfile_read and logfile_send members can be used to separately log
336 335 the input from the child and output sent to the child. Sometimes you
337 336 don't want to see everything you write to the child. You only want to
338 337 log what the child sends back. For example::
339 338
340 339 child = pexpect.spawn('some_command')
341 340 child.logfile_read = sys.stdout
342 341
343 342 To separately log output sent to the child use logfile_send::
344 343
345 344 self.logfile_send = fout
346 345
347 346 The delaybeforesend helps overcome a weird behavior that many users
348 347 were experiencing. The typical problem was that a user would expect() a
349 348 "Password:" prompt and then immediately call sendline() to send the
350 349 password. The user would then see that their password was echoed back
351 350 to them. Passwords don't normally echo. The problem is caused by the
352 351 fact that most applications print out the "Password" prompt and then
353 352 turn off stdin echo, but if you send your password before the
354 353 application turned off echo, then you get your password echoed.
355 354 Normally this wouldn't be a problem when interacting with a human at a
356 355 real keyboard. If you introduce a slight delay just before writing then
357 356 this seems to clear up the problem. This was such a common problem for
358 357 many users that I decided that the default pexpect behavior should be
359 358 to sleep just before writing to the child application. 1/20th of a
360 359 second (50 ms) seems to be enough to clear up the problem. You can set
361 360 delaybeforesend to 0 to return to the old behavior. Most Linux machines
362 361 don't like this to be below 0.03. I don't know why.
363 362
364 363 Note that spawn is clever about finding commands on your path.
365 364 It uses the same logic that "which" uses to find executables.
366 365
367 366 If you wish to get the exit status of the child you must call the
368 367 close() method. The exit or signal status of the child will be stored
369 368 in self.exitstatus or self.signalstatus. If the child exited normally
370 369 then exitstatus will store the exit return code and signalstatus will
371 370 be None. If the child was terminated abnormally with a signal then
372 371 signalstatus will store the signal value and exitstatus will be None.
373 372 If you need more detail you can also read the self.status member which
374 373 stores the status returned by os.waitpid. You can interpret this using
375 374 os.WIFEXITED/os.WEXITSTATUS or os.WIFSIGNALED/os.TERMSIG. """
376 375
377 376 self.STDIN_FILENO = pty.STDIN_FILENO
378 377 self.STDOUT_FILENO = pty.STDOUT_FILENO
379 378 self.STDERR_FILENO = pty.STDERR_FILENO
380 379 self.stdin = sys.stdin
381 380 self.stdout = sys.stdout
382 381 self.stderr = sys.stderr
383 382
384 383 self.searcher = None
385 384 self.ignorecase = False
386 385 self.before = None
387 386 self.after = None
388 387 self.match = None
389 388 self.match_index = None
390 389 self.terminated = True
391 390 self.exitstatus = None
392 391 self.signalstatus = None
393 392 self.status = None # status returned by os.waitpid
394 393 self.flag_eof = False
395 394 self.pid = None
396 395 self.child_fd = -1 # initially closed
397 396 self.timeout = timeout
398 397 self.delimiter = EOF
399 398 self.logfile = logfile
400 399 self.logfile_read = None # input from child (read_nonblocking)
401 400 self.logfile_send = None # output to send (send, sendline)
402 401 self.maxread = maxread # max bytes to read at one time into buffer
403 402 self.buffer = '' # This is the read buffer. See maxread.
404 403 self.searchwindowsize = searchwindowsize # Anything before searchwindowsize point is preserved, but not searched.
405 404 # Most Linux machines don't like delaybeforesend to be below 0.03 (30 ms).
406 405 self.delaybeforesend = 0.05 # Sets sleep time used just before sending data to child. Time in seconds.
407 406 self.delayafterclose = 0.1 # Sets delay in close() method to allow kernel time to update process status. Time in seconds.
408 407 self.delayafterterminate = 0.1 # Sets delay in terminate() method to allow kernel time to update process status. Time in seconds.
409 408 self.softspace = False # File-like object.
410 409 self.name = '<' + repr(self) + '>' # File-like object.
411 410 self.encoding = None # File-like object.
412 411 self.closed = True # File-like object.
413 412 self.cwd = cwd
414 413 self.env = env
415 414 self.__irix_hack = (sys.platform.lower().find('irix')>=0) # This flags if we are running on irix
416 415 # Solaris uses internal __fork_pty(). All others use pty.fork().
417 416 if (sys.platform.lower().find('solaris')>=0) or (sys.platform.lower().find('sunos5')>=0):
418 417 self.use_native_pty_fork = False
419 418 else:
420 419 self.use_native_pty_fork = True
421 420
422 421
423 422 # allow dummy instances for subclasses that may not use command or args.
424 423 if command is None:
425 424 self.command = None
426 425 self.args = None
427 426 self.name = '<pexpect factory incomplete>'
428 427 else:
429 428 self._spawn (command, args)
430 429
431 430 def __del__(self):
432 431
433 432 """This makes sure that no system resources are left open. Python only
434 433 garbage collects Python objects. OS file descriptors are not Python
435 434 objects, so they must be handled explicitly. If the child file
436 435 descriptor was opened outside of this class (passed to the constructor)
437 436 then this does not close it. """
438 437
439 438 if not self.closed:
440 439 # It is possible for __del__ methods to execute during the
441 440 # teardown of the Python VM itself. Thus self.close() may
442 441 # trigger an exception because os.close may be None.
443 442 # -- Fernando Perez
444 443 try:
445 444 self.close()
446 445 except AttributeError:
447 446 pass
448 447
449 448 def __str__(self):
450 449
451 450 """This returns a human-readable string that represents the state of
452 451 the object. """
453 452
454 453 s = []
455 454 s.append(repr(self))
456 455 s.append('version: ' + __version__ + ' (' + __revision__ + ')')
457 456 s.append('command: ' + str(self.command))
458 457 s.append('args: ' + str(self.args))
459 458 s.append('searcher: ' + str(self.searcher))
460 459 s.append('buffer (last 100 chars): ' + str(self.buffer)[-100:])
461 460 s.append('before (last 100 chars): ' + str(self.before)[-100:])
462 461 s.append('after: ' + str(self.after))
463 462 s.append('match: ' + str(self.match))
464 463 s.append('match_index: ' + str(self.match_index))
465 464 s.append('exitstatus: ' + str(self.exitstatus))
466 465 s.append('flag_eof: ' + str(self.flag_eof))
467 466 s.append('pid: ' + str(self.pid))
468 467 s.append('child_fd: ' + str(self.child_fd))
469 468 s.append('closed: ' + str(self.closed))
470 469 s.append('timeout: ' + str(self.timeout))
471 470 s.append('delimiter: ' + str(self.delimiter))
472 471 s.append('logfile: ' + str(self.logfile))
473 472 s.append('logfile_read: ' + str(self.logfile_read))
474 473 s.append('logfile_send: ' + str(self.logfile_send))
475 474 s.append('maxread: ' + str(self.maxread))
476 475 s.append('ignorecase: ' + str(self.ignorecase))
477 476 s.append('searchwindowsize: ' + str(self.searchwindowsize))
478 477 s.append('delaybeforesend: ' + str(self.delaybeforesend))
479 478 s.append('delayafterclose: ' + str(self.delayafterclose))
480 479 s.append('delayafterterminate: ' + str(self.delayafterterminate))
481 480 return '\n'.join(s)
482 481
483 482 def _spawn(self,command,args=[]):
484 483
485 484 """This starts the given command in a child process. This does all the
486 485 fork/exec type of stuff for a pty. This is called by __init__. If args
487 486 is empty then command will be parsed (split on spaces) and args will be
488 487 set to parsed arguments. """
489 488
490 489 # The pid and child_fd of this object get set by this method.
491 490 # Note that it is difficult for this method to fail.
492 491 # You cannot detect if the child process cannot start.
493 492 # So the only way you can tell if the child process started
494 493 # or not is to try to read from the file descriptor. If you get
495 494 # EOF immediately then it means that the child is already dead.
496 495 # That may not necessarily be bad because you may haved spawned a child
497 496 # that performs some task; creates no stdout output; and then dies.
498 497
499 498 # If command is an int type then it may represent a file descriptor.
500 499 if type(command) == type(0):
501 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 502 if type (args) != type([]):
504 503 raise TypeError ('The argument, args, must be a list.')
505 504
506 505 if args == []:
507 506 self.args = split_command_line(command)
508 507 self.command = self.args[0]
509 508 else:
510 509 self.args = args[:] # work with a copy
511 510 self.args.insert (0, command)
512 511 self.command = command
513 512
514 513 command_with_path = which(self.command)
515 514 if command_with_path is None:
516 515 raise ExceptionPexpect ('The command was not found or was not executable: %s.' % self.command)
517 516 self.command = command_with_path
518 517 self.args[0] = self.command
519 518
520 519 self.name = '<' + ' '.join (self.args) + '>'
521 520
522 521 assert self.pid is None, 'The pid member should be None.'
523 522 assert self.command is not None, 'The command member should not be None.'
524 523
525 524 if self.use_native_pty_fork:
526 525 try:
527 526 self.pid, self.child_fd = pty.fork()
528 527 except OSError, e:
529 528 raise ExceptionPexpect('Error! pty.fork() failed: ' + str(e))
530 529 else: # Use internal __fork_pty
531 530 self.pid, self.child_fd = self.__fork_pty()
532 531
533 532 if self.pid == 0: # Child
534 533 try:
535 534 self.child_fd = sys.stdout.fileno() # used by setwinsize()
536 535 self.setwinsize(24, 80)
537 536 except:
538 537 # Some platforms do not like setwinsize (Cygwin).
539 538 # This will cause problem when running applications that
540 539 # are very picky about window size.
541 540 # This is a serious limitation, but not a show stopper.
542 541 pass
543 542 # Do not allow child to inherit open file descriptors from parent.
544 543 max_fd = resource.getrlimit(resource.RLIMIT_NOFILE)[0]
545 544 for i in range (3, max_fd):
546 545 try:
547 546 os.close (i)
548 547 except OSError:
549 548 pass
550 549
551 550 # I don't know why this works, but ignoring SIGHUP fixes a
552 551 # problem when trying to start a Java daemon with sudo
553 552 # (specifically, Tomcat).
554 553 signal.signal(signal.SIGHUP, signal.SIG_IGN)
555 554
556 555 if self.cwd is not None:
557 556 os.chdir(self.cwd)
558 557 if self.env is None:
559 558 os.execv(self.command, self.args)
560 559 else:
561 560 os.execvpe(self.command, self.args, self.env)
562 561
563 562 # Parent
564 563 self.terminated = False
565 564 self.closed = False
566 565
567 566 def __fork_pty(self):
568 567
569 568 """This implements a substitute for the forkpty system call. This
570 569 should be more portable than the pty.fork() function. Specifically,
571 570 this should work on Solaris.
572 571
573 572 Modified 10.06.05 by Geoff Marshall: Implemented __fork_pty() method to
574 573 resolve the issue with Python's pty.fork() not supporting Solaris,
575 574 particularly ssh. Based on patch to posixmodule.c authored by Noah
576 575 Spurrier::
577 576
578 577 http://mail.python.org/pipermail/python-dev/2003-May/035281.html
579 578
580 579 """
581 580
582 581 parent_fd, child_fd = os.openpty()
583 582 if parent_fd < 0 or child_fd < 0:
584 583 raise ExceptionPexpect, "Error! Could not open pty with os.openpty()."
585 584
586 585 pid = os.fork()
587 586 if pid < 0:
588 587 raise ExceptionPexpect, "Error! Failed os.fork()."
589 588 elif pid == 0:
590 589 # Child.
591 590 os.close(parent_fd)
592 591 self.__pty_make_controlling_tty(child_fd)
593 592
594 593 os.dup2(child_fd, 0)
595 594 os.dup2(child_fd, 1)
596 595 os.dup2(child_fd, 2)
597 596
598 597 if child_fd > 2:
599 598 os.close(child_fd)
600 599 else:
601 600 # Parent.
602 601 os.close(child_fd)
603 602
604 603 return pid, parent_fd
605 604
606 605 def __pty_make_controlling_tty(self, tty_fd):
607 606
608 607 """This makes the pseudo-terminal the controlling tty. This should be
609 608 more portable than the pty.fork() function. Specifically, this should
610 609 work on Solaris. """
611 610
612 611 child_name = os.ttyname(tty_fd)
613 612
614 613 # Disconnect from controlling tty if still connected.
615 614 fd = os.open("/dev/tty", os.O_RDWR | os.O_NOCTTY);
616 615 if fd >= 0:
617 616 os.close(fd)
618 617
619 618 os.setsid()
620 619
621 620 # Verify we are disconnected from controlling tty
622 621 try:
623 622 fd = os.open("/dev/tty", os.O_RDWR | os.O_NOCTTY);
624 623 if fd >= 0:
625 624 os.close(fd)
626 625 raise ExceptionPexpect, "Error! We are not disconnected from a controlling tty."
627 626 except:
628 627 # Good! We are disconnected from a controlling tty.
629 628 pass
630 629
631 630 # Verify we can open child pty.
632 631 fd = os.open(child_name, os.O_RDWR);
633 632 if fd < 0:
634 633 raise ExceptionPexpect, "Error! Could not open child pty, " + child_name
635 634 else:
636 635 os.close(fd)
637 636
638 637 # Verify we now have a controlling tty.
639 638 fd = os.open("/dev/tty", os.O_WRONLY)
640 639 if fd < 0:
641 640 raise ExceptionPexpect, "Error! Could not open controlling tty, /dev/tty"
642 641 else:
643 642 os.close(fd)
644 643
645 644 def fileno (self): # File-like object.
646 645
647 646 """This returns the file descriptor of the pty for the child.
648 647 """
649 648
650 649 return self.child_fd
651 650
652 651 def close (self, force=True): # File-like object.
653 652
654 653 """This closes the connection with the child application. Note that
655 654 calling close() more than once is valid. This emulates standard Python
656 655 behavior with files. Set force to True if you want to make sure that
657 656 the child is terminated (SIGKILL is sent if the child ignores SIGHUP
658 657 and SIGINT). """
659 658
660 659 if not self.closed:
661 660 self.flush()
662 661 os.close (self.child_fd)
663 662 time.sleep(self.delayafterclose) # Give kernel time to update process status.
664 663 if self.isalive():
665 664 if not self.terminate(force):
666 665 raise ExceptionPexpect ('close() could not terminate the child using terminate()')
667 666 self.child_fd = -1
668 667 self.closed = True
669 668 #self.pid = None
670 669
671 670 def flush (self): # File-like object.
672 671
673 672 """This does nothing. It is here to support the interface for a
674 673 File-like object. """
675 674
676 675 pass
677 676
678 677 def isatty (self): # File-like object.
679 678
680 679 """This returns True if the file descriptor is open and connected to a
681 680 tty(-like) device, else False. """
682 681
683 682 return os.isatty(self.child_fd)
684 683
685 684 def waitnoecho (self, timeout=-1):
686 685
687 686 """This waits until the terminal ECHO flag is set False. This returns
688 687 True if the echo mode is off. This returns False if the ECHO flag was
689 688 not set False before the timeout. This can be used to detect when the
690 689 child is waiting for a password. Usually a child application will turn
691 690 off echo mode when it is waiting for the user to enter a password. For
692 691 example, instead of expecting the "password:" prompt you can wait for
693 692 the child to set ECHO off::
694 693
695 694 p = pexpect.spawn ('ssh user@example.com')
696 695 p.waitnoecho()
697 696 p.sendline(mypassword)
698 697
699 698 If timeout is None then this method to block forever until ECHO flag is
700 699 False.
701 700
702 701 """
703 702
704 703 if timeout == -1:
705 704 timeout = self.timeout
706 705 if timeout is not None:
707 706 end_time = time.time() + timeout
708 707 while True:
709 708 if not self.getecho():
710 709 return True
711 710 if timeout < 0 and timeout is not None:
712 711 return False
713 712 if timeout is not None:
714 713 timeout = end_time - time.time()
715 714 time.sleep(0.1)
716 715
717 716 def getecho (self):
718 717
719 718 """This returns the terminal echo mode. This returns True if echo is
720 719 on or False if echo is off. Child applications that are expecting you
721 720 to enter a password often set ECHO False. See waitnoecho(). """
722 721
723 722 attr = termios.tcgetattr(self.child_fd)
724 723 if attr[3] & termios.ECHO:
725 724 return True
726 725 return False
727 726
728 727 def setecho (self, state):
729 728
730 729 """This sets the terminal echo mode on or off. Note that anything the
731 730 child sent before the echo will be lost, so you should be sure that
732 731 your input buffer is empty before you call setecho(). For example, the
733 732 following will work as expected::
734 733
735 734 p = pexpect.spawn('cat')
736 735 p.sendline ('1234') # We will see this twice (once from tty echo and again from cat).
737 736 p.expect (['1234'])
738 737 p.expect (['1234'])
739 738 p.setecho(False) # Turn off tty echo
740 739 p.sendline ('abcd') # We will set this only once (echoed by cat).
741 740 p.sendline ('wxyz') # We will set this only once (echoed by cat)
742 741 p.expect (['abcd'])
743 742 p.expect (['wxyz'])
744 743
745 744 The following WILL NOT WORK because the lines sent before the setecho
746 745 will be lost::
747 746
748 747 p = pexpect.spawn('cat')
749 748 p.sendline ('1234') # We will see this twice (once from tty echo and again from cat).
750 749 p.setecho(False) # Turn off tty echo
751 750 p.sendline ('abcd') # We will set this only once (echoed by cat).
752 751 p.sendline ('wxyz') # We will set this only once (echoed by cat)
753 752 p.expect (['1234'])
754 753 p.expect (['1234'])
755 754 p.expect (['abcd'])
756 755 p.expect (['wxyz'])
757 756 """
758 757
759 758 self.child_fd
760 759 attr = termios.tcgetattr(self.child_fd)
761 760 if state:
762 761 attr[3] = attr[3] | termios.ECHO
763 762 else:
764 763 attr[3] = attr[3] & ~termios.ECHO
765 764 # I tried TCSADRAIN and TCSAFLUSH, but these were inconsistent
766 765 # and blocked on some platforms. TCSADRAIN is probably ideal if it worked.
767 766 termios.tcsetattr(self.child_fd, termios.TCSANOW, attr)
768 767
769 768 def read_nonblocking (self, size = 1, timeout = -1):
770 769
771 770 """This reads at most size characters from the child application. It
772 771 includes a timeout. If the read does not complete within the timeout
773 772 period then a TIMEOUT exception is raised. If the end of file is read
774 773 then an EOF exception will be raised. If a log file was set using
775 774 setlog() then all data will also be written to the log file.
776 775
777 776 If timeout is None then the read may block indefinitely. If timeout is -1
778 777 then the self.timeout value is used. If timeout is 0 then the child is
779 778 polled and if there was no data immediately ready then this will raise
780 779 a TIMEOUT exception.
781 780
782 781 The timeout refers only to the amount of time to read at least one
783 782 character. This is not effected by the 'size' parameter, so if you call
784 783 read_nonblocking(size=100, timeout=30) and only one character is
785 784 available right away then one character will be returned immediately.
786 785 It will not wait for 30 seconds for another 99 characters to come in.
787 786
788 787 This is a wrapper around os.read(). It uses select.select() to
789 788 implement the timeout. """
790 789
791 790 if self.closed:
792 791 raise ValueError ('I/O operation on closed file in read_nonblocking().')
793 792
794 793 if timeout == -1:
795 794 timeout = self.timeout
796 795
797 796 # Note that some systems such as Solaris do not give an EOF when
798 797 # the child dies. In fact, you can still try to read
799 798 # from the child_fd -- it will block forever or until TIMEOUT.
800 799 # For this case, I test isalive() before doing any reading.
801 800 # If isalive() is false, then I pretend that this is the same as EOF.
802 801 if not self.isalive():
803 802 r,w,e = self.__select([self.child_fd], [], [], 0) # timeout of 0 means "poll"
804 803 if not r:
805 804 self.flag_eof = True
806 805 raise EOF ('End Of File (EOF) in read_nonblocking(). Braindead platform.')
807 806 elif self.__irix_hack:
808 807 # This is a hack for Irix. It seems that Irix requires a long delay before checking isalive.
809 808 # This adds a 2 second delay, but only when the child is terminated.
810 809 r, w, e = self.__select([self.child_fd], [], [], 2)
811 810 if not r and not self.isalive():
812 811 self.flag_eof = True
813 812 raise EOF ('End Of File (EOF) in read_nonblocking(). Pokey platform.')
814 813
815 814 r,w,e = self.__select([self.child_fd], [], [], timeout)
816 815
817 816 if not r:
818 817 if not self.isalive():
819 818 # Some platforms, such as Irix, will claim that their processes are alive;
820 819 # then timeout on the select; and then finally admit that they are not alive.
821 820 self.flag_eof = True
822 821 raise EOF ('End of File (EOF) in read_nonblocking(). Very pokey platform.')
823 822 else:
824 823 raise TIMEOUT ('Timeout exceeded in read_nonblocking().')
825 824
826 825 if self.child_fd in r:
827 826 try:
828 827 s = os.read(self.child_fd, size)
829 828 except OSError, e: # Linux does this
830 829 self.flag_eof = True
831 830 raise EOF ('End Of File (EOF) in read_nonblocking(). Exception style platform.')
832 831 if s == '': # BSD style
833 832 self.flag_eof = True
834 833 raise EOF ('End Of File (EOF) in read_nonblocking(). Empty string style platform.')
835 834
836 835 if self.logfile is not None:
837 836 self.logfile.write (s)
838 837 self.logfile.flush()
839 838 if self.logfile_read is not None:
840 839 self.logfile_read.write (s)
841 840 self.logfile_read.flush()
842 841
843 842 return s
844 843
845 844 raise ExceptionPexpect ('Reached an unexpected state in read_nonblocking().')
846 845
847 846 def read (self, size = -1): # File-like object.
848 847
849 848 """This reads at most "size" bytes from the file (less if the read hits
850 849 EOF before obtaining size bytes). If the size argument is negative or
851 850 omitted, read all data until EOF is reached. The bytes are returned as
852 851 a string object. An empty string is returned when EOF is encountered
853 852 immediately. """
854 853
855 854 if size == 0:
856 855 return ''
857 856 if size < 0:
858 857 self.expect (self.delimiter) # delimiter default is EOF
859 858 return self.before
860 859
861 860 # I could have done this more directly by not using expect(), but
862 861 # I deliberately decided to couple read() to expect() so that
863 862 # I would catch any bugs early and ensure consistant behavior.
864 863 # It's a little less efficient, but there is less for me to
865 864 # worry about if I have to later modify read() or expect().
866 865 # Note, it's OK if size==-1 in the regex. That just means it
867 866 # will never match anything in which case we stop only on EOF.
868 867 cre = re.compile('.{%d}' % size, re.DOTALL)
869 868 index = self.expect ([cre, self.delimiter]) # delimiter default is EOF
870 869 if index == 0:
871 870 return self.after ### self.before should be ''. Should I assert this?
872 871 return self.before
873 872
874 873 def readline (self, size = -1): # File-like object.
875 874
876 875 """This reads and returns one entire line. A trailing newline is kept
877 876 in the string, but may be absent when a file ends with an incomplete
878 877 line. Note: This readline() looks for a \\r\\n pair even on UNIX
879 878 because this is what the pseudo tty device returns. So contrary to what
880 879 you may expect you will receive the newline as \\r\\n. An empty string
881 880 is returned when EOF is hit immediately. Currently, the size argument is
882 881 mostly ignored, so this behavior is not standard for a file-like
883 882 object. If size is 0 then an empty string is returned. """
884 883
885 884 if size == 0:
886 885 return ''
887 886 index = self.expect (['\r\n', self.delimiter]) # delimiter default is EOF
888 887 if index == 0:
889 888 return self.before + '\r\n'
890 889 else:
891 890 return self.before
892 891
893 892 def __iter__ (self): # File-like object.
894 893
895 894 """This is to support iterators over a file-like object.
896 895 """
897 896
898 897 return self
899 898
900 899 def next (self): # File-like object.
901 900
902 901 """This is to support iterators over a file-like object.
903 902 """
904 903
905 904 result = self.readline()
906 905 if result == "":
907 906 raise StopIteration
908 907 return result
909 908
910 909 def readlines (self, sizehint = -1): # File-like object.
911 910
912 911 """This reads until EOF using readline() and returns a list containing
913 912 the lines thus read. The optional "sizehint" argument is ignored. """
914 913
915 914 lines = []
916 915 while True:
917 916 line = self.readline()
918 917 if not line:
919 918 break
920 919 lines.append(line)
921 920 return lines
922 921
923 922 def write(self, s): # File-like object.
924 923
925 924 """This is similar to send() except that there is no return value.
926 925 """
927 926
928 927 self.send (s)
929 928
930 929 def writelines (self, sequence): # File-like object.
931 930
932 931 """This calls write() for each element in the sequence. The sequence
933 932 can be any iterable object producing strings, typically a list of
934 933 strings. This does not add line separators There is no return value.
935 934 """
936 935
937 936 for s in sequence:
938 937 self.write (s)
939 938
940 939 def send(self, s):
941 940
942 941 """This sends a string to the child process. This returns the number of
943 942 bytes written. If a log file was set then the data is also written to
944 943 the log. """
945 944
946 945 time.sleep(self.delaybeforesend)
947 946 if self.logfile is not None:
948 947 self.logfile.write (s)
949 948 self.logfile.flush()
950 949 if self.logfile_send is not None:
951 950 self.logfile_send.write (s)
952 951 self.logfile_send.flush()
953 952 c = os.write(self.child_fd, s)
954 953 return c
955 954
956 955 def sendline(self, s=''):
957 956
958 957 """This is like send(), but it adds a line feed (os.linesep). This
959 958 returns the number of bytes written. """
960 959
961 960 n = self.send(s)
962 961 n = n + self.send (os.linesep)
963 962 return n
964 963
965 964 def sendcontrol(self, char):
966 965
967 966 """This sends a control character to the child such as Ctrl-C or
968 967 Ctrl-D. For example, to send a Ctrl-G (ASCII 7)::
969 968
970 969 child.sendcontrol('g')
971 970
972 971 See also, sendintr() and sendeof().
973 972 """
974 973
975 974 char = char.lower()
976 975 a = ord(char)
977 976 if a>=97 and a<=122:
978 977 a = a - ord('a') + 1
979 978 return self.send (chr(a))
980 979 d = {'@':0, '`':0,
981 980 '[':27, '{':27,
982 981 '\\':28, '|':28,
983 982 ']':29, '}': 29,
984 983 '^':30, '~':30,
985 984 '_':31,
986 985 '?':127}
987 986 if char not in d:
988 987 return 0
989 988 return self.send (chr(d[char]))
990 989
991 990 def sendeof(self):
992 991
993 992 """This sends an EOF to the child. This sends a character which causes
994 993 the pending parent output buffer to be sent to the waiting child
995 994 program without waiting for end-of-line. If it is the first character
996 995 of the line, the read() in the user program returns 0, which signifies
997 996 end-of-file. This means to work as expected a sendeof() has to be
998 997 called at the beginning of a line. This method does not send a newline.
999 998 It is the responsibility of the caller to ensure the eof is sent at the
1000 999 beginning of a line. """
1001 1000
1002 1001 ### Hmmm... how do I send an EOF?
1003 1002 ###C if ((m = write(pty, *buf, p - *buf)) < 0)
1004 1003 ###C return (errno == EWOULDBLOCK) ? n : -1;
1005 1004 #fd = sys.stdin.fileno()
1006 1005 #old = termios.tcgetattr(fd) # remember current state
1007 1006 #attr = termios.tcgetattr(fd)
1008 1007 #attr[3] = attr[3] | termios.ICANON # ICANON must be set to recognize EOF
1009 1008 #try: # use try/finally to ensure state gets restored
1010 1009 # termios.tcsetattr(fd, termios.TCSADRAIN, attr)
1011 1010 # if hasattr(termios, 'CEOF'):
1012 1011 # os.write (self.child_fd, '%c' % termios.CEOF)
1013 1012 # else:
1014 1013 # # Silly platform does not define CEOF so assume CTRL-D
1015 1014 # os.write (self.child_fd, '%c' % 4)
1016 1015 #finally: # restore state
1017 1016 # termios.tcsetattr(fd, termios.TCSADRAIN, old)
1018 1017 if hasattr(termios, 'VEOF'):
1019 1018 char = termios.tcgetattr(self.child_fd)[6][termios.VEOF]
1020 1019 else:
1021 1020 # platform does not define VEOF so assume CTRL-D
1022 1021 char = chr(4)
1023 1022 self.send(char)
1024 1023
1025 1024 def sendintr(self):
1026 1025
1027 1026 """This sends a SIGINT to the child. It does not require
1028 1027 the SIGINT to be the first character on a line. """
1029 1028
1030 1029 if hasattr(termios, 'VINTR'):
1031 1030 char = termios.tcgetattr(self.child_fd)[6][termios.VINTR]
1032 1031 else:
1033 1032 # platform does not define VINTR so assume CTRL-C
1034 1033 char = chr(3)
1035 1034 self.send (char)
1036 1035
1037 1036 def eof (self):
1038 1037
1039 1038 """This returns True if the EOF exception was ever raised.
1040 1039 """
1041 1040
1042 1041 return self.flag_eof
1043 1042
1044 1043 def terminate(self, force=False):
1045 1044
1046 1045 """This forces a child process to terminate. It starts nicely with
1047 1046 SIGHUP and SIGINT. If "force" is True then moves onto SIGKILL. This
1048 1047 returns True if the child was terminated. This returns False if the
1049 1048 child could not be terminated. """
1050 1049
1051 1050 if not self.isalive():
1052 1051 return True
1053 1052 try:
1054 1053 self.kill(signal.SIGHUP)
1055 1054 time.sleep(self.delayafterterminate)
1056 1055 if not self.isalive():
1057 1056 return True
1058 1057 self.kill(signal.SIGCONT)
1059 1058 time.sleep(self.delayafterterminate)
1060 1059 if not self.isalive():
1061 1060 return True
1062 1061 self.kill(signal.SIGINT)
1063 1062 time.sleep(self.delayafterterminate)
1064 1063 if not self.isalive():
1065 1064 return True
1066 1065 if force:
1067 1066 self.kill(signal.SIGKILL)
1068 1067 time.sleep(self.delayafterterminate)
1069 1068 if not self.isalive():
1070 1069 return True
1071 1070 else:
1072 1071 return False
1073 1072 return False
1074 1073 except OSError, e:
1075 1074 # I think there are kernel timing issues that sometimes cause
1076 1075 # this to happen. I think isalive() reports True, but the
1077 1076 # process is dead to the kernel.
1078 1077 # Make one last attempt to see if the kernel is up to date.
1079 1078 time.sleep(self.delayafterterminate)
1080 1079 if not self.isalive():
1081 1080 return True
1082 1081 else:
1083 1082 return False
1084 1083
1085 1084 def wait(self):
1086 1085
1087 1086 """This waits until the child exits. This is a blocking call. This will
1088 1087 not read any data from the child, so this will block forever if the
1089 1088 child has unread output and has terminated. In other words, the child
1090 1089 may have printed output then called exit(); but, technically, the child
1091 1090 is still alive until its output is read. """
1092 1091
1093 1092 if self.isalive():
1094 1093 pid, status = os.waitpid(self.pid, 0)
1095 1094 else:
1096 1095 raise ExceptionPexpect ('Cannot wait for dead child process.')
1097 1096 self.exitstatus = os.WEXITSTATUS(status)
1098 1097 if os.WIFEXITED (status):
1099 1098 self.status = status
1100 1099 self.exitstatus = os.WEXITSTATUS(status)
1101 1100 self.signalstatus = None
1102 1101 self.terminated = True
1103 1102 elif os.WIFSIGNALED (status):
1104 1103 self.status = status
1105 1104 self.exitstatus = None
1106 1105 self.signalstatus = os.WTERMSIG(status)
1107 1106 self.terminated = True
1108 1107 elif os.WIFSTOPPED (status):
1109 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 1109 return self.exitstatus
1111 1110
1112 1111 def isalive(self):
1113 1112
1114 1113 """This tests if the child process is running or not. This is
1115 1114 non-blocking. If the child was terminated then this will read the
1116 1115 exitstatus or signalstatus of the child. This returns True if the child
1117 1116 process appears to be running or False if not. It can take literally
1118 1117 SECONDS for Solaris to return the right status. """
1119 1118
1120 1119 if self.terminated:
1121 1120 return False
1122 1121
1123 1122 if self.flag_eof:
1124 1123 # This is for Linux, which requires the blocking form of waitpid to get
1125 1124 # status of a defunct process. This is super-lame. The flag_eof would have
1126 1125 # been set in read_nonblocking(), so this should be safe.
1127 1126 waitpid_options = 0
1128 1127 else:
1129 1128 waitpid_options = os.WNOHANG
1130 1129
1131 1130 try:
1132 1131 pid, status = os.waitpid(self.pid, waitpid_options)
1133 1132 except OSError, e: # No child processes
1134 1133 if e[0] == errno.ECHILD:
1135 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 1135 else:
1137 1136 raise e
1138 1137
1139 1138 # I have to do this twice for Solaris. I can't even believe that I figured this out...
1140 1139 # If waitpid() returns 0 it means that no child process wishes to
1141 1140 # report, and the value of status is undefined.
1142 1141 if pid == 0:
1143 1142 try:
1144 1143 pid, status = os.waitpid(self.pid, waitpid_options) ### os.WNOHANG) # Solaris!
1145 1144 except OSError, e: # This should never happen...
1146 1145 if e[0] == errno.ECHILD:
1147 1146 raise ExceptionPexpect ('isalive() encountered condition that should never happen. There was no child process. Did someone else call waitpid() on our process?')
1148 1147 else:
1149 1148 raise e
1150 1149
1151 1150 # If pid is still 0 after two calls to waitpid() then
1152 1151 # the process really is alive. This seems to work on all platforms, except
1153 1152 # for Irix which seems to require a blocking call on waitpid or select, so I let read_nonblocking
1154 1153 # take care of this situation (unfortunately, this requires waiting through the timeout).
1155 1154 if pid == 0:
1156 1155 return True
1157 1156
1158 1157 if pid == 0:
1159 1158 return True
1160 1159
1161 1160 if os.WIFEXITED (status):
1162 1161 self.status = status
1163 1162 self.exitstatus = os.WEXITSTATUS(status)
1164 1163 self.signalstatus = None
1165 1164 self.terminated = True
1166 1165 elif os.WIFSIGNALED (status):
1167 1166 self.status = status
1168 1167 self.exitstatus = None
1169 1168 self.signalstatus = os.WTERMSIG(status)
1170 1169 self.terminated = True
1171 1170 elif os.WIFSTOPPED (status):
1172 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 1172 return False
1174 1173
1175 1174 def kill(self, sig):
1176 1175
1177 1176 """This sends the given signal to the child application. In keeping
1178 1177 with UNIX tradition it has a misleading name. It does not necessarily
1179 1178 kill the child unless you send the right signal. """
1180 1179
1181 1180 # Same as os.kill, but the pid is given for you.
1182 1181 if self.isalive():
1183 1182 os.kill(self.pid, sig)
1184 1183
1185 1184 def compile_pattern_list(self, patterns):
1186 1185
1187 1186 """This compiles a pattern-string or a list of pattern-strings.
1188 1187 Patterns must be a StringType, EOF, TIMEOUT, SRE_Pattern, or a list of
1189 1188 those. Patterns may also be None which results in an empty list (you
1190 1189 might do this if waiting for an EOF or TIMEOUT condition without
1191 1190 expecting any pattern).
1192 1191
1193 1192 This is used by expect() when calling expect_list(). Thus expect() is
1194 1193 nothing more than::
1195 1194
1196 1195 cpl = self.compile_pattern_list(pl)
1197 1196 return self.expect_list(cpl, timeout)
1198 1197
1199 1198 If you are using expect() within a loop it may be more
1200 1199 efficient to compile the patterns first and then call expect_list().
1201 1200 This avoid calls in a loop to compile_pattern_list()::
1202 1201
1203 1202 cpl = self.compile_pattern_list(my_pattern)
1204 1203 while some_condition:
1205 1204 ...
1206 1205 i = self.expect_list(clp, timeout)
1207 1206 ...
1208 1207 """
1209 1208
1210 1209 if patterns is None:
1211 1210 return []
1212 1211 if type(patterns) is not types.ListType:
1213 1212 patterns = [patterns]
1214 1213
1215 1214 compile_flags = re.DOTALL # Allow dot to match \n
1216 1215 if self.ignorecase:
1217 1216 compile_flags = compile_flags | re.IGNORECASE
1218 1217 compiled_pattern_list = []
1219 1218 for p in patterns:
1220 1219 if type(p) in types.StringTypes:
1221 1220 compiled_pattern_list.append(re.compile(p, compile_flags))
1222 1221 elif p is EOF:
1223 1222 compiled_pattern_list.append(EOF)
1224 1223 elif p is TIMEOUT:
1225 1224 compiled_pattern_list.append(TIMEOUT)
1226 1225 elif type(p) is type(re.compile('')):
1227 1226 compiled_pattern_list.append(p)
1228 1227 else:
1229 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 1230 return compiled_pattern_list
1232 1231
1233 1232 def expect(self, pattern, timeout = -1, searchwindowsize=None):
1234 1233
1235 1234 """This seeks through the stream until a pattern is matched. The
1236 1235 pattern is overloaded and may take several types. The pattern can be a
1237 1236 StringType, EOF, a compiled re, or a list of any of those types.
1238 1237 Strings will be compiled to re types. This returns the index into the
1239 1238 pattern list. If the pattern was not a list this returns index 0 on a
1240 1239 successful match. This may raise exceptions for EOF or TIMEOUT. To
1241 1240 avoid the EOF or TIMEOUT exceptions add EOF or TIMEOUT to the pattern
1242 1241 list. That will cause expect to match an EOF or TIMEOUT condition
1243 1242 instead of raising an exception.
1244 1243
1245 1244 If you pass a list of patterns and more than one matches, the first match
1246 1245 in the stream is chosen. If more than one pattern matches at that point,
1247 1246 the leftmost in the pattern list is chosen. For example::
1248 1247
1249 1248 # the input is 'foobar'
1250 1249 index = p.expect (['bar', 'foo', 'foobar'])
1251 1250 # returns 1 ('foo') even though 'foobar' is a "better" match
1252 1251
1253 1252 Please note, however, that buffering can affect this behavior, since
1254 1253 input arrives in unpredictable chunks. For example::
1255 1254
1256 1255 # the input is 'foobar'
1257 1256 index = p.expect (['foobar', 'foo'])
1258 1257 # returns 0 ('foobar') if all input is available at once,
1259 1258 # but returs 1 ('foo') if parts of the final 'bar' arrive late
1260 1259
1261 1260 After a match is found the instance attributes 'before', 'after' and
1262 1261 'match' will be set. You can see all the data read before the match in
1263 1262 'before'. You can see the data that was matched in 'after'. The
1264 1263 re.MatchObject used in the re match will be in 'match'. If an error
1265 1264 occurred then 'before' will be set to all the data read so far and
1266 1265 'after' and 'match' will be None.
1267 1266
1268 1267 If timeout is -1 then timeout will be set to the self.timeout value.
1269 1268
1270 1269 A list entry may be EOF or TIMEOUT instead of a string. This will
1271 1270 catch these exceptions and return the index of the list entry instead
1272 1271 of raising the exception. The attribute 'after' will be set to the
1273 1272 exception type. The attribute 'match' will be None. This allows you to
1274 1273 write code like this::
1275 1274
1276 1275 index = p.expect (['good', 'bad', pexpect.EOF, pexpect.TIMEOUT])
1277 1276 if index == 0:
1278 1277 do_something()
1279 1278 elif index == 1:
1280 1279 do_something_else()
1281 1280 elif index == 2:
1282 1281 do_some_other_thing()
1283 1282 elif index == 3:
1284 1283 do_something_completely_different()
1285 1284
1286 1285 instead of code like this::
1287 1286
1288 1287 try:
1289 1288 index = p.expect (['good', 'bad'])
1290 1289 if index == 0:
1291 1290 do_something()
1292 1291 elif index == 1:
1293 1292 do_something_else()
1294 1293 except EOF:
1295 1294 do_some_other_thing()
1296 1295 except TIMEOUT:
1297 1296 do_something_completely_different()
1298 1297
1299 1298 These two forms are equivalent. It all depends on what you want. You
1300 1299 can also just expect the EOF if you are waiting for all output of a
1301 1300 child to finish. For example::
1302 1301
1303 1302 p = pexpect.spawn('/bin/ls')
1304 1303 p.expect (pexpect.EOF)
1305 1304 print p.before
1306 1305
1307 1306 If you are trying to optimize for speed then see expect_list().
1308 1307 """
1309 1308
1310 1309 compiled_pattern_list = self.compile_pattern_list(pattern)
1311 1310 return self.expect_list(compiled_pattern_list, timeout, searchwindowsize)
1312 1311
1313 1312 def expect_list(self, pattern_list, timeout = -1, searchwindowsize = -1):
1314 1313
1315 1314 """This takes a list of compiled regular expressions and returns the
1316 1315 index into the pattern_list that matched the child output. The list may
1317 1316 also contain EOF or TIMEOUT (which are not compiled regular
1318 1317 expressions). This method is similar to the expect() method except that
1319 1318 expect_list() does not recompile the pattern list on every call. This
1320 1319 may help if you are trying to optimize for speed, otherwise just use
1321 1320 the expect() method. This is called by expect(). If timeout==-1 then
1322 1321 the self.timeout value is used. If searchwindowsize==-1 then the
1323 1322 self.searchwindowsize value is used. """
1324 1323
1325 1324 return self.expect_loop(searcher_re(pattern_list), timeout, searchwindowsize)
1326 1325
1327 1326 def expect_exact(self, pattern_list, timeout = -1, searchwindowsize = -1):
1328 1327
1329 1328 """This is similar to expect(), but uses plain string matching instead
1330 1329 of compiled regular expressions in 'pattern_list'. The 'pattern_list'
1331 1330 may be a string; a list or other sequence of strings; or TIMEOUT and
1332 1331 EOF.
1333 1332
1334 1333 This call might be faster than expect() for two reasons: string
1335 1334 searching is faster than RE matching and it is possible to limit the
1336 1335 search to just the end of the input buffer.
1337 1336
1338 1337 This method is also useful when you don't want to have to worry about
1339 1338 escaping regular expression characters that you want to match."""
1340 1339
1341 1340 if type(pattern_list) in types.StringTypes or pattern_list in (TIMEOUT, EOF):
1342 1341 pattern_list = [pattern_list]
1343 1342 return self.expect_loop(searcher_string(pattern_list), timeout, searchwindowsize)
1344 1343
1345 1344 def expect_loop(self, searcher, timeout = -1, searchwindowsize = -1):
1346 1345
1347 1346 """This is the common loop used inside expect. The 'searcher' should be
1348 1347 an instance of searcher_re or searcher_string, which describes how and what
1349 1348 to search for in the input.
1350 1349
1351 1350 See expect() for other arguments, return value and exceptions. """
1352 1351
1353 1352 self.searcher = searcher
1354 1353
1355 1354 if timeout == -1:
1356 1355 timeout = self.timeout
1357 1356 if timeout is not None:
1358 1357 end_time = time.time() + timeout
1359 1358 if searchwindowsize == -1:
1360 1359 searchwindowsize = self.searchwindowsize
1361 1360
1362 1361 try:
1363 1362 incoming = self.buffer
1364 1363 freshlen = len(incoming)
1365 1364 while True: # Keep reading until exception or return.
1366 1365 index = searcher.search(incoming, freshlen, searchwindowsize)
1367 1366 if index >= 0:
1368 1367 self.buffer = incoming[searcher.end : ]
1369 1368 self.before = incoming[ : searcher.start]
1370 1369 self.after = incoming[searcher.start : searcher.end]
1371 1370 self.match = searcher.match
1372 1371 self.match_index = index
1373 1372 return self.match_index
1374 1373 # No match at this point
1375 1374 if timeout < 0 and timeout is not None:
1376 1375 raise TIMEOUT ('Timeout exceeded in expect_any().')
1377 1376 # Still have time left, so read more data
1378 1377 c = self.read_nonblocking (self.maxread, timeout)
1379 1378 freshlen = len(c)
1380 1379 time.sleep (0.0001)
1381 1380 incoming = incoming + c
1382 1381 if timeout is not None:
1383 1382 timeout = end_time - time.time()
1384 1383 except EOF, e:
1385 1384 self.buffer = ''
1386 1385 self.before = incoming
1387 1386 self.after = EOF
1388 1387 index = searcher.eof_index
1389 1388 if index >= 0:
1390 1389 self.match = EOF
1391 1390 self.match_index = index
1392 1391 return self.match_index
1393 1392 else:
1394 1393 self.match = None
1395 1394 self.match_index = None
1396 1395 raise EOF (str(e) + '\n' + str(self))
1397 1396 except TIMEOUT, e:
1398 1397 self.buffer = incoming
1399 1398 self.before = incoming
1400 1399 self.after = TIMEOUT
1401 1400 index = searcher.timeout_index
1402 1401 if index >= 0:
1403 1402 self.match = TIMEOUT
1404 1403 self.match_index = index
1405 1404 return self.match_index
1406 1405 else:
1407 1406 self.match = None
1408 1407 self.match_index = None
1409 1408 raise TIMEOUT (str(e) + '\n' + str(self))
1410 1409 except:
1411 1410 self.before = incoming
1412 1411 self.after = None
1413 1412 self.match = None
1414 1413 self.match_index = None
1415 1414 raise
1416 1415
1417 1416 def getwinsize(self):
1418 1417
1419 1418 """This returns the terminal window size of the child tty. The return
1420 1419 value is a tuple of (rows, cols). """
1421 1420
1422 1421 TIOCGWINSZ = getattr(termios, 'TIOCGWINSZ', 1074295912L)
1423 1422 s = struct.pack('HHHH', 0, 0, 0, 0)
1424 1423 x = fcntl.ioctl(self.fileno(), TIOCGWINSZ, s)
1425 1424 return struct.unpack('HHHH', x)[0:2]
1426 1425
1427 1426 def setwinsize(self, r, c):
1428 1427
1429 1428 """This sets the terminal window size of the child tty. This will cause
1430 1429 a SIGWINCH signal to be sent to the child. This does not change the
1431 1430 physical window size. It changes the size reported to TTY-aware
1432 1431 applications like vi or curses -- applications that respond to the
1433 1432 SIGWINCH signal. """
1434 1433
1435 1434 # Check for buggy platforms. Some Python versions on some platforms
1436 1435 # (notably OSF1 Alpha and RedHat 7.1) truncate the value for
1437 1436 # termios.TIOCSWINSZ. It is not clear why this happens.
1438 1437 # These platforms don't seem to handle the signed int very well;
1439 1438 # yet other platforms like OpenBSD have a large negative value for
1440 1439 # TIOCSWINSZ and they don't have a truncate problem.
1441 1440 # Newer versions of Linux have totally different values for TIOCSWINSZ.
1442 1441 # Note that this fix is a hack.
1443 1442 TIOCSWINSZ = getattr(termios, 'TIOCSWINSZ', -2146929561)
1444 1443 if TIOCSWINSZ == 2148037735L: # L is not required in Python >= 2.2.
1445 1444 TIOCSWINSZ = -2146929561 # Same bits, but with sign.
1446 1445 # Note, assume ws_xpixel and ws_ypixel are zero.
1447 1446 s = struct.pack('HHHH', r, c, 0, 0)
1448 1447 fcntl.ioctl(self.fileno(), TIOCSWINSZ, s)
1449 1448
1450 1449 def interact(self, escape_character = chr(29), input_filter = None, output_filter = None):
1451 1450
1452 1451 """This gives control of the child process to the interactive user (the
1453 1452 human at the keyboard). Keystrokes are sent to the child process, and
1454 1453 the stdout and stderr output of the child process is printed. This
1455 1454 simply echos the child stdout and child stderr to the real stdout and
1456 1455 it echos the real stdin to the child stdin. When the user types the
1457 1456 escape_character this method will stop. The default for
1458 1457 escape_character is ^]. This should not be confused with ASCII 27 --
1459 1458 the ESC character. ASCII 29 was chosen for historical merit because
1460 1459 this is the character used by 'telnet' as the escape character. The
1461 1460 escape_character will not be sent to the child process.
1462 1461
1463 1462 You may pass in optional input and output filter functions. These
1464 1463 functions should take a string and return a string. The output_filter
1465 1464 will be passed all the output from the child process. The input_filter
1466 1465 will be passed all the keyboard input from the user. The input_filter
1467 1466 is run BEFORE the check for the escape_character.
1468 1467
1469 1468 Note that if you change the window size of the parent the SIGWINCH
1470 1469 signal will not be passed through to the child. If you want the child
1471 1470 window size to change when the parent's window size changes then do
1472 1471 something like the following example::
1473 1472
1474 1473 import pexpect, struct, fcntl, termios, signal, sys
1475 1474 def sigwinch_passthrough (sig, data):
1476 1475 s = struct.pack("HHHH", 0, 0, 0, 0)
1477 1476 a = struct.unpack('hhhh', fcntl.ioctl(sys.stdout.fileno(), termios.TIOCGWINSZ , s))
1478 1477 global p
1479 1478 p.setwinsize(a[0],a[1])
1480 1479 p = pexpect.spawn('/bin/bash') # Note this is global and used in sigwinch_passthrough.
1481 1480 signal.signal(signal.SIGWINCH, sigwinch_passthrough)
1482 1481 p.interact()
1483 1482 """
1484 1483
1485 1484 # Flush the buffer.
1486 1485 self.stdout.write (self.buffer)
1487 1486 self.stdout.flush()
1488 1487 self.buffer = ''
1489 1488 mode = tty.tcgetattr(self.STDIN_FILENO)
1490 1489 tty.setraw(self.STDIN_FILENO)
1491 1490 try:
1492 1491 self.__interact_copy(escape_character, input_filter, output_filter)
1493 1492 finally:
1494 1493 tty.tcsetattr(self.STDIN_FILENO, tty.TCSAFLUSH, mode)
1495 1494
1496 1495 def __interact_writen(self, fd, data):
1497 1496
1498 1497 """This is used by the interact() method.
1499 1498 """
1500 1499
1501 1500 while data != '' and self.isalive():
1502 1501 n = os.write(fd, data)
1503 1502 data = data[n:]
1504 1503
1505 1504 def __interact_read(self, fd):
1506 1505
1507 1506 """This is used by the interact() method.
1508 1507 """
1509 1508
1510 1509 return os.read(fd, 1000)
1511 1510
1512 1511 def __interact_copy(self, escape_character = None, input_filter = None, output_filter = None):
1513 1512
1514 1513 """This is used by the interact() method.
1515 1514 """
1516 1515
1517 1516 while self.isalive():
1518 1517 r,w,e = self.__select([self.child_fd, self.STDIN_FILENO], [], [])
1519 1518 if self.child_fd in r:
1520 1519 data = self.__interact_read(self.child_fd)
1521 1520 if output_filter: data = output_filter(data)
1522 1521 if self.logfile is not None:
1523 1522 self.logfile.write (data)
1524 1523 self.logfile.flush()
1525 1524 os.write(self.STDOUT_FILENO, data)
1526 1525 if self.STDIN_FILENO in r:
1527 1526 data = self.__interact_read(self.STDIN_FILENO)
1528 1527 if input_filter: data = input_filter(data)
1529 1528 i = data.rfind(escape_character)
1530 1529 if i != -1:
1531 1530 data = data[:i]
1532 1531 self.__interact_writen(self.child_fd, data)
1533 1532 break
1534 1533 self.__interact_writen(self.child_fd, data)
1535 1534
1536 1535 def __select (self, iwtd, owtd, ewtd, timeout=None):
1537 1536
1538 1537 """This is a wrapper around select.select() that ignores signals. If
1539 1538 select.select raises a select.error exception and errno is an EINTR
1540 1539 error then it is ignored. Mainly this is used to ignore sigwinch
1541 1540 (terminal resize). """
1542 1541
1543 1542 # if select() is interrupted by a signal (errno==EINTR) then
1544 1543 # we loop back and enter the select() again.
1545 1544 if timeout is not None:
1546 1545 end_time = time.time() + timeout
1547 1546 while True:
1548 1547 try:
1549 1548 return select.select (iwtd, owtd, ewtd, timeout)
1550 1549 except select.error, e:
1551 1550 if e[0] == errno.EINTR:
1552 1551 # if we loop back we have to subtract the amount of time we already waited.
1553 1552 if timeout is not None:
1554 1553 timeout = end_time - time.time()
1555 1554 if timeout < 0:
1556 1555 return ([],[],[])
1557 1556 else: # something else caused the select.error, so this really is an exception
1558 1557 raise
1559 1558
1560 1559 ##############################################################################
1561 1560 # The following methods are no longer supported or allowed.
1562 1561
1563 1562 def setmaxread (self, maxread):
1564 1563
1565 1564 """This method is no longer supported or allowed. I don't like getters
1566 1565 and setters without a good reason. """
1567 1566
1568 1567 raise ExceptionPexpect ('This method is no longer supported or allowed. Just assign a value to the maxread member variable.')
1569 1568
1570 1569 def setlog (self, fileobject):
1571 1570
1572 1571 """This method is no longer supported or allowed.
1573 1572 """
1574 1573
1575 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 1577 # End of spawn class
1579 1578 ##############################################################################
1580 1579
1581 1580 class searcher_string (object):
1582 1581
1583 1582 """This is a plain string search helper for the spawn.expect_any() method.
1584 1583
1585 1584 Attributes:
1586 1585
1587 1586 eof_index - index of EOF, or -1
1588 1587 timeout_index - index of TIMEOUT, or -1
1589 1588
1590 1589 After a successful match by the search() method the following attributes
1591 1590 are available:
1592 1591
1593 1592 start - index into the buffer, first byte of match
1594 1593 end - index into the buffer, first byte after match
1595 1594 match - the matching string itself
1596 1595 """
1597 1596
1598 1597 def __init__(self, strings):
1599 1598
1600 1599 """This creates an instance of searcher_string. This argument 'strings'
1601 1600 may be a list; a sequence of strings; or the EOF or TIMEOUT types. """
1602 1601
1603 1602 self.eof_index = -1
1604 1603 self.timeout_index = -1
1605 1604 self._strings = []
1606 1605 for n, s in zip(range(len(strings)), strings):
1607 1606 if s is EOF:
1608 1607 self.eof_index = n
1609 1608 continue
1610 1609 if s is TIMEOUT:
1611 1610 self.timeout_index = n
1612 1611 continue
1613 1612 self._strings.append((n, s))
1614 1613
1615 1614 def __str__(self):
1616 1615
1617 1616 """This returns a human-readable string that represents the state of
1618 1617 the object."""
1619 1618
1620 1619 ss = [ (ns[0],' %d: "%s"' % ns) for ns in self._strings ]
1621 1620 ss.append((-1,'searcher_string:'))
1622 1621 if self.eof_index >= 0:
1623 1622 ss.append ((self.eof_index,' %d: EOF' % self.eof_index))
1624 1623 if self.timeout_index >= 0:
1625 1624 ss.append ((self.timeout_index,' %d: TIMEOUT' % self.timeout_index))
1626 1625 ss.sort()
1627 1626 ss = zip(*ss)[1]
1628 1627 return '\n'.join(ss)
1629 1628
1630 1629 def search(self, buffer, freshlen, searchwindowsize=None):
1631 1630
1632 1631 """This searches 'buffer' for the first occurence of one of the search
1633 1632 strings. 'freshlen' must indicate the number of bytes at the end of
1634 1633 'buffer' which have not been searched before. It helps to avoid
1635 1634 searching the same, possibly big, buffer over and over again.
1636 1635
1637 1636 See class spawn for the 'searchwindowsize' argument.
1638 1637
1639 1638 If there is a match this returns the index of that string, and sets
1640 1639 'start', 'end' and 'match'. Otherwise, this returns -1. """
1641 1640
1642 1641 absurd_match = len(buffer)
1643 1642 first_match = absurd_match
1644 1643
1645 1644 # 'freshlen' helps a lot here. Further optimizations could
1646 1645 # possibly include:
1647 1646 #
1648 1647 # using something like the Boyer-Moore Fast String Searching
1649 1648 # Algorithm; pre-compiling the search through a list of
1650 1649 # strings into something that can scan the input once to
1651 1650 # search for all N strings; realize that if we search for
1652 1651 # ['bar', 'baz'] and the input is '...foo' we need not bother
1653 1652 # rescanning until we've read three more bytes.
1654 1653 #
1655 1654 # Sadly, I don't know enough about this interesting topic. /grahn
1656 1655
1657 1656 for index, s in self._strings:
1658 1657 if searchwindowsize is None:
1659 1658 # the match, if any, can only be in the fresh data,
1660 1659 # or at the very end of the old data
1661 1660 offset = -(freshlen+len(s))
1662 1661 else:
1663 1662 # better obey searchwindowsize
1664 1663 offset = -searchwindowsize
1665 1664 n = buffer.find(s, offset)
1666 1665 if n >= 0 and n < first_match:
1667 1666 first_match = n
1668 1667 best_index, best_match = index, s
1669 1668 if first_match == absurd_match:
1670 1669 return -1
1671 1670 self.match = best_match
1672 1671 self.start = first_match
1673 1672 self.end = self.start + len(self.match)
1674 1673 return best_index
1675 1674
1676 1675 class searcher_re (object):
1677 1676
1678 1677 """This is regular expression string search helper for the
1679 1678 spawn.expect_any() method.
1680 1679
1681 1680 Attributes:
1682 1681
1683 1682 eof_index - index of EOF, or -1
1684 1683 timeout_index - index of TIMEOUT, or -1
1685 1684
1686 1685 After a successful match by the search() method the following attributes
1687 1686 are available:
1688 1687
1689 1688 start - index into the buffer, first byte of match
1690 1689 end - index into the buffer, first byte after match
1691 1690 match - the re.match object returned by a succesful re.search
1692 1691
1693 1692 """
1694 1693
1695 1694 def __init__(self, patterns):
1696 1695
1697 1696 """This creates an instance that searches for 'patterns' Where
1698 1697 'patterns' may be a list or other sequence of compiled regular
1699 1698 expressions, or the EOF or TIMEOUT types."""
1700 1699
1701 1700 self.eof_index = -1
1702 1701 self.timeout_index = -1
1703 1702 self._searches = []
1704 1703 for n, s in zip(range(len(patterns)), patterns):
1705 1704 if s is EOF:
1706 1705 self.eof_index = n
1707 1706 continue
1708 1707 if s is TIMEOUT:
1709 1708 self.timeout_index = n
1710 1709 continue
1711 1710 self._searches.append((n, s))
1712 1711
1713 1712 def __str__(self):
1714 1713
1715 1714 """This returns a human-readable string that represents the state of
1716 1715 the object."""
1717 1716
1718 1717 ss = [ (n,' %d: re.compile("%s")' % (n,str(s.pattern))) for n,s in self._searches]
1719 1718 ss.append((-1,'searcher_re:'))
1720 1719 if self.eof_index >= 0:
1721 1720 ss.append ((self.eof_index,' %d: EOF' % self.eof_index))
1722 1721 if self.timeout_index >= 0:
1723 1722 ss.append ((self.timeout_index,' %d: TIMEOUT' % self.timeout_index))
1724 1723 ss.sort()
1725 1724 ss = zip(*ss)[1]
1726 1725 return '\n'.join(ss)
1727 1726
1728 1727 def search(self, buffer, freshlen, searchwindowsize=None):
1729 1728
1730 1729 """This searches 'buffer' for the first occurence of one of the regular
1731 1730 expressions. 'freshlen' must indicate the number of bytes at the end of
1732 1731 'buffer' which have not been searched before.
1733 1732
1734 1733 See class spawn for the 'searchwindowsize' argument.
1735 1734
1736 1735 If there is a match this returns the index of that string, and sets
1737 1736 'start', 'end' and 'match'. Otherwise, returns -1."""
1738 1737
1739 1738 absurd_match = len(buffer)
1740 1739 first_match = absurd_match
1741 1740 # 'freshlen' doesn't help here -- we cannot predict the
1742 1741 # length of a match, and the re module provides no help.
1743 1742 if searchwindowsize is None:
1744 1743 searchstart = 0
1745 1744 else:
1746 1745 searchstart = max(0, len(buffer)-searchwindowsize)
1747 1746 for index, s in self._searches:
1748 1747 match = s.search(buffer, searchstart)
1749 1748 if match is None:
1750 1749 continue
1751 1750 n = match.start()
1752 1751 if n < first_match:
1753 1752 first_match = n
1754 1753 the_match = match
1755 1754 best_index = index
1756 1755 if first_match == absurd_match:
1757 1756 return -1
1758 1757 self.start = first_match
1759 1758 self.match = the_match
1760 1759 self.end = self.match.end()
1761 1760 return best_index
1762 1761
1763 1762 def which (filename):
1764 1763
1765 1764 """This takes a given filename; tries to find it in the environment path;
1766 1765 then checks if it is executable. This returns the full path to the filename
1767 1766 if found and executable. Otherwise this returns None."""
1768 1767
1769 1768 # Special case where filename already contains a path.
1770 1769 if os.path.dirname(filename) != '':
1771 1770 if os.access (filename, os.X_OK):
1772 1771 return filename
1773 1772
1774 1773 if not os.environ.has_key('PATH') or os.environ['PATH'] == '':
1775 1774 p = os.defpath
1776 1775 else:
1777 1776 p = os.environ['PATH']
1778 1777
1779 1778 # Oddly enough this was the one line that made Pexpect
1780 1779 # incompatible with Python 1.5.2.
1781 #pathlist = p.split (os.pathsep)
1782 pathlist = string.split (p, os.pathsep)
1780 pathlist = p.split(os.pathsep)
1783 1781
1784 1782 for path in pathlist:
1785 1783 f = os.path.join(path, filename)
1786 1784 if os.access(f, os.X_OK):
1787 1785 return f
1788 1786 return None
1789 1787
1790 1788 def split_command_line(command_line):
1791 1789
1792 1790 """This splits a command line into a list of arguments. It splits arguments
1793 1791 on spaces, but handles embedded quotes, doublequotes, and escaped
1794 1792 characters. It's impossible to do this with a regular expression, so I
1795 1793 wrote a little state machine to parse the command line. """
1796 1794
1797 1795 arg_list = []
1798 1796 arg = ''
1799 1797
1800 1798 # Constants to name the states we can be in.
1801 1799 state_basic = 0
1802 1800 state_esc = 1
1803 1801 state_singlequote = 2
1804 1802 state_doublequote = 3
1805 1803 state_whitespace = 4 # The state of consuming whitespace between commands.
1806 1804 state = state_basic
1807 1805
1808 1806 for c in command_line:
1809 1807 if state == state_basic or state == state_whitespace:
1810 1808 if c == '\\': # Escape the next character
1811 1809 state = state_esc
1812 1810 elif c == r"'": # Handle single quote
1813 1811 state = state_singlequote
1814 1812 elif c == r'"': # Handle double quote
1815 1813 state = state_doublequote
1816 1814 elif c.isspace():
1817 1815 # Add arg to arg_list if we aren't in the middle of whitespace.
1818 1816 if state == state_whitespace:
1819 1817 None # Do nothing.
1820 1818 else:
1821 1819 arg_list.append(arg)
1822 1820 arg = ''
1823 1821 state = state_whitespace
1824 1822 else:
1825 1823 arg = arg + c
1826 1824 state = state_basic
1827 1825 elif state == state_esc:
1828 1826 arg = arg + c
1829 1827 state = state_basic
1830 1828 elif state == state_singlequote:
1831 1829 if c == r"'":
1832 1830 state = state_basic
1833 1831 else:
1834 1832 arg = arg + c
1835 1833 elif state == state_doublequote:
1836 1834 if c == r'"':
1837 1835 state = state_basic
1838 1836 else:
1839 1837 arg = arg + c
1840 1838
1841 1839 if arg != '':
1842 1840 arg_list.append(arg)
1843 1841 return arg_list
1844 1842
1845 1843 # vi:ts=4:sw=4:expandtab:ft=python:
General Comments 0
You need to be logged in to leave comments. Login now