##// END OF EJS Templates
* IPython/iplib.py (runsource): remove self.code_to_run_src attribute. I...
fperez -
Show More

The requested changes are too big and content was truncated. Show full diff

@@ -1,887 +1,886 b''
1 1 # -*- coding: utf-8 -*-
2 2 """IPython Shell classes.
3 3
4 4 All the matplotlib support code was co-developed with John Hunter,
5 5 matplotlib's author.
6 6
7 $Id: Shell.py 634 2005-07-17 01:56:45Z tzanko $"""
7 $Id: Shell.py 703 2005-08-16 17:34:44Z fperez $"""
8 8
9 9 #*****************************************************************************
10 10 # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
11 11 #
12 12 # Distributed under the terms of the BSD License. The full license is in
13 13 # the file COPYING, distributed as part of this software.
14 14 #*****************************************************************************
15 15
16 16 from IPython import Release
17 17 __author__ = '%s <%s>' % Release.authors['Fernando']
18 18 __license__ = Release.license
19 19
20 20 # Code begins
21 21 import __main__
22 22 import __builtin__
23 23 import sys
24 24 import os
25 25 import code
26 26 import threading
27 27 import signal
28 28
29 29 import IPython
30 30 from IPython.iplib import InteractiveShell
31 31 from IPython.ipmaker import make_IPython
32 32 from IPython.genutils import Term,warn,error,flag_calls
33 33 from IPython.Struct import Struct
34 34 from IPython.Magic import Magic
35 35 from IPython import ultraTB
36 36
37 37 # global flag to pass around information about Ctrl-C without exceptions
38 38 KBINT = False
39 39
40 40 # global flag to turn on/off Tk support.
41 41 USE_TK = False
42 42
43 43 #-----------------------------------------------------------------------------
44 44 # This class is trivial now, but I want to have it in to publish a clean
45 45 # interface. Later when the internals are reorganized, code that uses this
46 46 # shouldn't have to change.
47 47
48 48 class IPShell:
49 49 """Create an IPython instance."""
50 50
51 51 def __init__(self,argv=None,user_ns=None,debug=1,
52 52 shell_class=InteractiveShell):
53 53 self.IP = make_IPython(argv,user_ns=user_ns,debug=debug,
54 54 shell_class=shell_class)
55 55
56 56 def mainloop(self,sys_exit=0,banner=None):
57 57 self.IP.mainloop(banner)
58 58 if sys_exit:
59 59 sys.exit()
60 60
61 61 #-----------------------------------------------------------------------------
62 62 class IPShellEmbed:
63 63 """Allow embedding an IPython shell into a running program.
64 64
65 65 Instances of this class are callable, with the __call__ method being an
66 66 alias to the embed() method of an InteractiveShell instance.
67 67
68 68 Usage (see also the example-embed.py file for a running example):
69 69
70 70 ipshell = IPShellEmbed([argv,banner,exit_msg,rc_override])
71 71
72 72 - argv: list containing valid command-line options for IPython, as they
73 73 would appear in sys.argv[1:].
74 74
75 75 For example, the following command-line options:
76 76
77 77 $ ipython -prompt_in1 'Input <\\#>' -colors LightBG
78 78
79 79 would be passed in the argv list as:
80 80
81 81 ['-prompt_in1','Input <\\#>','-colors','LightBG']
82 82
83 83 - banner: string which gets printed every time the interpreter starts.
84 84
85 85 - exit_msg: string which gets printed every time the interpreter exits.
86 86
87 87 - rc_override: a dict or Struct of configuration options such as those
88 88 used by IPython. These options are read from your ~/.ipython/ipythonrc
89 89 file when the Shell object is created. Passing an explicit rc_override
90 90 dict with any options you want allows you to override those values at
91 91 creation time without having to modify the file. This way you can create
92 92 embeddable instances configured in any way you want without editing any
93 93 global files (thus keeping your interactive IPython configuration
94 94 unchanged).
95 95
96 96 Then the ipshell instance can be called anywhere inside your code:
97 97
98 98 ipshell(header='') -> Opens up an IPython shell.
99 99
100 100 - header: string printed by the IPython shell upon startup. This can let
101 101 you know where in your code you are when dropping into the shell. Note
102 102 that 'banner' gets prepended to all calls, so header is used for
103 103 location-specific information.
104 104
105 105 For more details, see the __call__ method below.
106 106
107 107 When the IPython shell is exited with Ctrl-D, normal program execution
108 108 resumes.
109 109
110 110 This functionality was inspired by a posting on comp.lang.python by cmkl
111 111 <cmkleffner@gmx.de> on Dec. 06/01 concerning similar uses of pyrepl, and
112 112 by the IDL stop/continue commands."""
113 113
114 114 def __init__(self,argv=None,banner='',exit_msg=None,rc_override=None):
115 115 """Note that argv here is a string, NOT a list."""
116 116 self.set_banner(banner)
117 117 self.set_exit_msg(exit_msg)
118 118 self.set_dummy_mode(0)
119 119
120 120 # sys.displayhook is a global, we need to save the user's original
121 121 # Don't rely on __displayhook__, as the user may have changed that.
122 122 self.sys_displayhook_ori = sys.displayhook
123 123
124 124 # save readline completer status
125 125 try:
126 126 #print 'Save completer',sys.ipcompleter # dbg
127 127 self.sys_ipcompleter_ori = sys.ipcompleter
128 128 except:
129 129 pass # not nested with IPython
130 130
131 131 # FIXME. Passing user_ns breaks namespace handling.
132 132 #self.IP = make_IPython(argv,user_ns=__main__.__dict__)
133 133 self.IP = make_IPython(argv,rc_override=rc_override,embedded=True)
134 134
135 135 self.IP.name_space_init()
136 136 # mark this as an embedded instance so we know if we get a crash
137 137 # post-mortem
138 138 self.IP.rc.embedded = 1
139 139 # copy our own displayhook also
140 140 self.sys_displayhook_embed = sys.displayhook
141 141 # and leave the system's display hook clean
142 142 sys.displayhook = self.sys_displayhook_ori
143 143 # don't use the ipython crash handler so that user exceptions aren't
144 144 # trapped
145 145 sys.excepthook = ultraTB.FormattedTB(color_scheme = self.IP.rc.colors,
146 146 mode = self.IP.rc.xmode,
147 147 call_pdb = self.IP.rc.pdb)
148 148 self.restore_system_completer()
149 149
150 150 def restore_system_completer(self):
151 151 """Restores the readline completer which was in place.
152 152
153 153 This allows embedded IPython within IPython not to disrupt the
154 154 parent's completion.
155 155 """
156 156
157 157 try:
158 158 self.IP.readline.set_completer(self.sys_ipcompleter_ori)
159 159 sys.ipcompleter = self.sys_ipcompleter_ori
160 160 except:
161 161 pass
162 162
163 163 def __call__(self,header='',local_ns=None,global_ns=None,dummy=None):
164 164 """Activate the interactive interpreter.
165 165
166 166 __call__(self,header='',local_ns=None,global_ns,dummy=None) -> Start
167 167 the interpreter shell with the given local and global namespaces, and
168 168 optionally print a header string at startup.
169 169
170 170 The shell can be globally activated/deactivated using the
171 171 set/get_dummy_mode methods. This allows you to turn off a shell used
172 172 for debugging globally.
173 173
174 174 However, *each* time you call the shell you can override the current
175 175 state of dummy_mode with the optional keyword parameter 'dummy'. For
176 176 example, if you set dummy mode on with IPShell.set_dummy_mode(1), you
177 177 can still have a specific call work by making it as IPShell(dummy=0).
178 178
179 179 The optional keyword parameter dummy controls whether the call
180 180 actually does anything. """
181 181
182 182 # Allow the dummy parameter to override the global __dummy_mode
183 183 if dummy or (dummy != 0 and self.__dummy_mode):
184 184 return
185 185
186 186 # Set global subsystems (display,completions) to our values
187 187 sys.displayhook = self.sys_displayhook_embed
188 188 if self.IP.has_readline:
189 189 self.IP.readline.set_completer(self.IP.Completer.complete)
190 190
191 191 if self.banner and header:
192 192 format = '%s\n%s\n'
193 193 else:
194 194 format = '%s%s\n'
195 195 banner = format % (self.banner,header)
196 196
197 197 # Call the embedding code with a stack depth of 1 so it can skip over
198 198 # our call and get the original caller's namespaces.
199 199 self.IP.embed_mainloop(banner,local_ns,global_ns,stack_depth=1)
200 200
201 201 if self.exit_msg:
202 202 print self.exit_msg
203 203
204 204 # Restore global systems (display, completion)
205 205 sys.displayhook = self.sys_displayhook_ori
206 206 self.restore_system_completer()
207 207
208 208 def set_dummy_mode(self,dummy):
209 209 """Sets the embeddable shell's dummy mode parameter.
210 210
211 211 set_dummy_mode(dummy): dummy = 0 or 1.
212 212
213 213 This parameter is persistent and makes calls to the embeddable shell
214 214 silently return without performing any action. This allows you to
215 215 globally activate or deactivate a shell you're using with a single call.
216 216
217 217 If you need to manually"""
218 218
219 219 if dummy not in [0,1]:
220 220 raise ValueError,'dummy parameter must be 0 or 1'
221 221 self.__dummy_mode = dummy
222 222
223 223 def get_dummy_mode(self):
224 224 """Return the current value of the dummy mode parameter.
225 225 """
226 226 return self.__dummy_mode
227 227
228 228 def set_banner(self,banner):
229 229 """Sets the global banner.
230 230
231 231 This banner gets prepended to every header printed when the shell
232 232 instance is called."""
233 233
234 234 self.banner = banner
235 235
236 236 def set_exit_msg(self,exit_msg):
237 237 """Sets the global exit_msg.
238 238
239 239 This exit message gets printed upon exiting every time the embedded
240 240 shell is called. It is None by default. """
241 241
242 242 self.exit_msg = exit_msg
243 243
244 244 #-----------------------------------------------------------------------------
245 245 def sigint_handler (signum,stack_frame):
246 246 """Sigint handler for threaded apps.
247 247
248 248 This is a horrible hack to pass information about SIGINT _without_ using
249 249 exceptions, since I haven't been able to properly manage cross-thread
250 250 exceptions in GTK/WX. In fact, I don't think it can be done (or at least
251 251 that's my understanding from a c.l.py thread where this was discussed)."""
252 252
253 253 global KBINT
254 254
255 255 print '\nKeyboardInterrupt - Press <Enter> to continue.',
256 256 Term.cout.flush()
257 257 # Set global flag so that runsource can know that Ctrl-C was hit
258 258 KBINT = True
259 259
260 260 class MTInteractiveShell(InteractiveShell):
261 261 """Simple multi-threaded shell."""
262 262
263 263 # Threading strategy taken from:
264 264 # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65109, by Brian
265 265 # McErlean and John Finlay. Modified with corrections by Antoon Pardon,
266 266 # from the pygtk mailing list, to avoid lockups with system calls.
267 267
268 268 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
269 269 user_ns = None, banner2='',**kw):
270 270 """Similar to the normal InteractiveShell, but with threading control"""
271 271
272 272 IPython.iplib.InteractiveShell.__init__(self,name,usage,rc,user_ns,banner2)
273 273
274 274 # Locking control variable
275 275 self.thread_ready = threading.Condition()
276 276
277 277 # Stuff to do at closing time
278 278 self._kill = False
279 279 on_kill = kw.get('on_kill')
280 280 if on_kill is None:
281 281 on_kill = []
282 282 # Check that all things to kill are callable:
283 283 for t in on_kill:
284 284 if not callable(t):
285 285 raise TypeError,'on_kill must be a list of callables'
286 286 self.on_kill = on_kill
287 287
288 288 def runsource(self, source, filename="<input>", symbol="single"):
289 289 """Compile and run some source in the interpreter.
290 290
291 291 Modified version of code.py's runsource(), to handle threading issues.
292 292 See the original for full docstring details."""
293 293
294 294 global KBINT
295 295
296 296 # If Ctrl-C was typed, we reset the flag and return right away
297 297 if KBINT:
298 298 KBINT = False
299 299 return False
300 300
301 301 try:
302 302 code = self.compile(source, filename, symbol)
303 303 except (OverflowError, SyntaxError, ValueError):
304 304 # Case 1
305 305 self.showsyntaxerror(filename)
306 306 return False
307 307
308 308 if code is None:
309 309 # Case 2
310 310 return True
311 311
312 312 # Case 3
313 313 # Store code in self, so the execution thread can handle it
314 314 self.thread_ready.acquire()
315 self.code_to_run_src = source
316 315 self.code_to_run = code
317 316 self.thread_ready.wait() # Wait until processed in timeout interval
318 317 self.thread_ready.release()
319 318
320 319 return False
321 320
322 321 def runcode(self):
323 322 """Execute a code object.
324 323
325 324 Multithreaded wrapper around IPython's runcode()."""
326 325
327 326 # lock thread-protected stuff
328 327 self.thread_ready.acquire()
329 328
330 329 # Install sigint handler
331 330 try:
332 331 signal.signal(signal.SIGINT, sigint_handler)
333 332 except SystemError:
334 333 # This happens under Windows, which seems to have all sorts
335 334 # of problems with signal handling. Oh well...
336 335 pass
337 336
338 337 if self._kill:
339 338 print >>Term.cout, 'Closing threads...',
340 339 Term.cout.flush()
341 340 for tokill in self.on_kill:
342 341 tokill()
343 342 print >>Term.cout, 'Done.'
344 343
345 344 # Run pending code by calling parent class
346 345 if self.code_to_run is not None:
347 346 self.thread_ready.notify()
348 347 InteractiveShell.runcode(self,self.code_to_run)
349 348
350 349 # We're done with thread-protected variables
351 350 self.thread_ready.release()
352 351 # This MUST return true for gtk threading to work
353 352 return True
354 353
355 354 def kill (self):
356 355 """Kill the thread, returning when it has been shut down."""
357 356 self.thread_ready.acquire()
358 357 self._kill = True
359 358 self.thread_ready.release()
360 359
361 360 class MatplotlibShellBase:
362 361 """Mixin class to provide the necessary modifications to regular IPython
363 362 shell classes for matplotlib support.
364 363
365 364 Given Python's MRO, this should be used as the FIRST class in the
366 365 inheritance hierarchy, so that it overrides the relevant methods."""
367 366
368 367 def _matplotlib_config(self,name):
369 368 """Return various items needed to setup the user's shell with matplotlib"""
370 369
371 370 # Initialize matplotlib to interactive mode always
372 371 import matplotlib
373 372 from matplotlib import backends
374 373 matplotlib.interactive(True)
375 374
376 375 def use(arg):
377 376 """IPython wrapper for matplotlib's backend switcher.
378 377
379 378 In interactive use, we can not allow switching to a different
380 379 interactive backend, since thread conflicts will most likely crash
381 380 the python interpreter. This routine does a safety check first,
382 381 and refuses to perform a dangerous switch. It still allows
383 382 switching to non-interactive backends."""
384 383
385 384 if arg in backends.interactive_bk and arg != self.mpl_backend:
386 385 m=('invalid matplotlib backend switch.\n'
387 386 'This script attempted to switch to the interactive '
388 387 'backend: `%s`\n'
389 388 'Your current choice of interactive backend is: `%s`\n\n'
390 389 'Switching interactive matplotlib backends at runtime\n'
391 390 'would crash the python interpreter, '
392 391 'and IPython has blocked it.\n\n'
393 392 'You need to either change your choice of matplotlib backend\n'
394 393 'by editing your .matplotlibrc file, or run this script as a \n'
395 394 'standalone file from the command line, not using IPython.\n' %
396 395 (arg,self.mpl_backend) )
397 396 raise RuntimeError, m
398 397 else:
399 398 self.mpl_use(arg)
400 399 self.mpl_use._called = True
401 400
402 401 self.matplotlib = matplotlib
403 402 self.mpl_backend = matplotlib.rcParams['backend']
404 403
405 404 # we also need to block switching of interactive backends by use()
406 405 self.mpl_use = matplotlib.use
407 406 self.mpl_use._called = False
408 407 # overwrite the original matplotlib.use with our wrapper
409 408 matplotlib.use = use
410 409
411 410
412 411 # This must be imported last in the matplotlib series, after
413 412 # backend/interactivity choices have been made
414 413 try:
415 414 import matplotlib.pylab as pylab
416 415 self.pylab = pylab
417 416 self.pylab_name = 'pylab'
418 417 except ImportError:
419 418 import matplotlib.matlab as matlab
420 419 self.pylab = matlab
421 420 self.pylab_name = 'matlab'
422 421
423 422 self.pylab.show._needmain = False
424 423 # We need to detect at runtime whether show() is called by the user.
425 424 # For this, we wrap it into a decorator which adds a 'called' flag.
426 425 self.pylab.draw_if_interactive = flag_calls(self.pylab.draw_if_interactive)
427 426
428 427 # Build a user namespace initialized with matplotlib/matlab features.
429 428 user_ns = {'__name__':'__main__',
430 429 '__builtins__' : __builtin__ }
431 430
432 431 # Be careful not to remove the final \n in the code string below, or
433 432 # things will break badly with py22 (I think it's a python bug, 2.3 is
434 433 # OK).
435 434 pname = self.pylab_name # Python can't interpolate dotted var names
436 435 exec ("import matplotlib\n"
437 436 "import matplotlib.%(pname)s as %(pname)s\n"
438 437 "from matplotlib.%(pname)s import *\n" % locals()) in user_ns
439 438
440 439 # Build matplotlib info banner
441 440 b="""
442 441 Welcome to pylab, a matplotlib-based Python environment.
443 442 For more information, type 'help(pylab)'.
444 443 """
445 444 return user_ns,b
446 445
447 446 def mplot_exec(self,fname,*where,**kw):
448 447 """Execute a matplotlib script.
449 448
450 449 This is a call to execfile(), but wrapped in safeties to properly
451 450 handle interactive rendering and backend switching."""
452 451
453 452 #print '*** Matplotlib runner ***' # dbg
454 453 # turn off rendering until end of script
455 454 isInteractive = self.matplotlib.rcParams['interactive']
456 455 self.matplotlib.interactive(False)
457 456 self.safe_execfile(fname,*where,**kw)
458 457 self.matplotlib.interactive(isInteractive)
459 458 # make rendering call now, if the user tried to do it
460 459 if self.pylab.draw_if_interactive.called:
461 460 self.pylab.draw()
462 461 self.pylab.draw_if_interactive.called = False
463 462
464 463 # if a backend switch was performed, reverse it now
465 464 if self.mpl_use._called:
466 465 self.matplotlib.rcParams['backend'] = self.mpl_backend
467 466
468 467 def magic_run(self,parameter_s=''):
469 468 Magic.magic_run(self,parameter_s,runner=self.mplot_exec)
470 469
471 470 # Fix the docstring so users see the original as well
472 471 magic_run.__doc__ = "%s\n%s" % (Magic.magic_run.__doc__,
473 472 "\n *** Modified %run for Matplotlib,"
474 473 " with proper interactive handling ***")
475 474
476 475 # Now we provide 2 versions of a matplotlib-aware IPython base shells, single
477 476 # and multithreaded. Note that these are meant for internal use, the IPShell*
478 477 # classes below are the ones meant for public consumption.
479 478
480 479 class MatplotlibShell(MatplotlibShellBase,InteractiveShell):
481 480 """Single-threaded shell with matplotlib support."""
482 481
483 482 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
484 483 user_ns = None, **kw):
485 484 user_ns,b2 = self._matplotlib_config(name)
486 485 InteractiveShell.__init__(self,name,usage,rc,user_ns,banner2=b2,**kw)
487 486
488 487 class MatplotlibMTShell(MatplotlibShellBase,MTInteractiveShell):
489 488 """Multi-threaded shell with matplotlib support."""
490 489
491 490 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
492 491 user_ns = None, **kw):
493 492 user_ns,b2 = self._matplotlib_config(name)
494 493 MTInteractiveShell.__init__(self,name,usage,rc,user_ns,banner2=b2,**kw)
495 494
496 495 #-----------------------------------------------------------------------------
497 496 # Utility functions for the different GUI enabled IPShell* classes.
498 497
499 498 def get_tk():
500 499 """Tries to import Tkinter and returns a withdrawn Tkinter root
501 500 window. If Tkinter is already imported or not available, this
502 501 returns None. This function calls `hijack_tk` underneath.
503 502 """
504 503 if not USE_TK or sys.modules.has_key('Tkinter'):
505 504 return None
506 505 else:
507 506 try:
508 507 import Tkinter
509 508 except ImportError:
510 509 return None
511 510 else:
512 511 hijack_tk()
513 512 r = Tkinter.Tk()
514 513 r.withdraw()
515 514 return r
516 515
517 516 def hijack_tk():
518 517 """Modifies Tkinter's mainloop with a dummy so when a module calls
519 518 mainloop, it does not block.
520 519
521 520 """
522 521 def misc_mainloop(self, n=0):
523 522 pass
524 523 def tkinter_mainloop(n=0):
525 524 pass
526 525
527 526 import Tkinter
528 527 Tkinter.Misc.mainloop = misc_mainloop
529 528 Tkinter.mainloop = tkinter_mainloop
530 529
531 530 def update_tk(tk):
532 531 """Updates the Tkinter event loop. This is typically called from
533 532 the respective WX or GTK mainloops.
534 533 """
535 534 if tk:
536 535 tk.update()
537 536
538 537 def hijack_wx():
539 538 """Modifies wxPython's MainLoop with a dummy so user code does not
540 539 block IPython. The hijacked mainloop function is returned.
541 540 """
542 541 def dummy_mainloop(*args, **kw):
543 542 pass
544 543 import wxPython
545 544 ver = wxPython.__version__
546 545 orig_mainloop = None
547 546 if ver[:3] >= '2.5':
548 547 import wx
549 548 if hasattr(wx, '_core_'): core = getattr(wx, '_core_')
550 549 elif hasattr(wx, '_core'): core = getattr(wx, '_core')
551 550 else: raise AttributeError('Could not find wx core module')
552 551 orig_mainloop = core.PyApp_MainLoop
553 552 core.PyApp_MainLoop = dummy_mainloop
554 553 elif ver[:3] == '2.4':
555 554 orig_mainloop = wxPython.wxc.wxPyApp_MainLoop
556 555 wxPython.wxc.wxPyApp_MainLoop = dummy_mainloop
557 556 else:
558 557 warn("Unable to find either wxPython version 2.4 or >= 2.5.")
559 558 return orig_mainloop
560 559
561 560 def hijack_gtk():
562 561 """Modifies pyGTK's mainloop with a dummy so user code does not
563 562 block IPython. This function returns the original `gtk.mainloop`
564 563 function that has been hijacked.
565 564
566 565 NOTE: Make sure you import this *AFTER* you call
567 566 pygtk.require(...).
568 567 """
569 568 def dummy_mainloop(*args, **kw):
570 569 pass
571 570 import gtk
572 571 if gtk.pygtk_version >= (2,4,0): orig_mainloop = gtk.main
573 572 else: orig_mainloop = gtk.mainloop
574 573 gtk.mainloop = dummy_mainloop
575 574 gtk.main = dummy_mainloop
576 575 return orig_mainloop
577 576
578 577 #-----------------------------------------------------------------------------
579 578 # The IPShell* classes below are the ones meant to be run by external code as
580 579 # IPython instances. Note that unless a specific threading strategy is
581 580 # desired, the factory function start() below should be used instead (it
582 581 # selects the proper threaded class).
583 582
584 583 class IPShellGTK(threading.Thread):
585 584 """Run a gtk mainloop() in a separate thread.
586 585
587 586 Python commands can be passed to the thread where they will be executed.
588 587 This is implemented by periodically checking for passed code using a
589 588 GTK timeout callback."""
590 589
591 590 TIMEOUT = 100 # Millisecond interval between timeouts.
592 591
593 592 def __init__(self,argv=None,user_ns=None,debug=1,
594 593 shell_class=MTInteractiveShell):
595 594
596 595 import pygtk
597 596 pygtk.require("2.0")
598 597 import gtk
599 598
600 599 self.gtk = gtk
601 600 self.gtk_mainloop = hijack_gtk()
602 601
603 602 # Allows us to use both Tk and GTK.
604 603 self.tk = get_tk()
605 604
606 605 if gtk.pygtk_version >= (2,4,0): mainquit = self.gtk.main_quit
607 606 else: mainquit = self.gtk.mainquit
608 607
609 608 self.IP = make_IPython(argv,user_ns=user_ns,debug=debug,
610 609 shell_class=shell_class,
611 610 on_kill=[mainquit])
612 611 threading.Thread.__init__(self)
613 612
614 613 def run(self):
615 614 self.IP.mainloop()
616 615 self.IP.kill()
617 616
618 617 def mainloop(self):
619 618
620 619 if self.gtk.pygtk_version >= (2,4,0):
621 620 import gobject
622 621 gobject.timeout_add(self.TIMEOUT, self.on_timer)
623 622 else:
624 623 self.gtk.timeout_add(self.TIMEOUT, self.on_timer)
625 624
626 625 if sys.platform != 'win32':
627 626 try:
628 627 if self.gtk.gtk_version[0] >= 2:
629 628 self.gtk.threads_init()
630 629 except AttributeError:
631 630 pass
632 631 except RuntimeError:
633 632 error('Your pyGTK likely has not been compiled with '
634 633 'threading support.\n'
635 634 'The exception printout is below.\n'
636 635 'You can either rebuild pyGTK with threads, or '
637 636 'try using \n'
638 637 'matplotlib with a different backend (like Tk or WX).\n'
639 638 'Note that matplotlib will most likely not work in its '
640 639 'current state!')
641 640 self.IP.InteractiveTB()
642 641 self.start()
643 642 self.gtk.threads_enter()
644 643 self.gtk_mainloop()
645 644 self.gtk.threads_leave()
646 645 self.join()
647 646
648 647 def on_timer(self):
649 648 update_tk(self.tk)
650 649 return self.IP.runcode()
651 650
652 651
653 652 class IPShellWX(threading.Thread):
654 653 """Run a wx mainloop() in a separate thread.
655 654
656 655 Python commands can be passed to the thread where they will be executed.
657 656 This is implemented by periodically checking for passed code using a
658 657 GTK timeout callback."""
659 658
660 659 TIMEOUT = 100 # Millisecond interval between timeouts.
661 660
662 661 def __init__(self,argv=None,user_ns=None,debug=1,
663 662 shell_class=MTInteractiveShell):
664 663
665 664 import wxPython.wx as wx
666 665
667 666 threading.Thread.__init__(self)
668 667 self.wx = wx
669 668 self.wx_mainloop = hijack_wx()
670 669
671 670 # Allows us to use both Tk and GTK.
672 671 self.tk = get_tk()
673 672
674 673 self.IP = make_IPython(argv,user_ns=user_ns,debug=debug,
675 674 shell_class=shell_class,
676 675 on_kill=[self.wxexit])
677 676 self.app = None
678 677
679 678 def wxexit(self, *args):
680 679 if self.app is not None:
681 680 self.app.agent.timer.Stop()
682 681 self.app.ExitMainLoop()
683 682
684 683 def run(self):
685 684 self.IP.mainloop()
686 685 self.IP.kill()
687 686
688 687 def mainloop(self):
689 688
690 689 self.start()
691 690
692 691 class TimerAgent(self.wx.wxMiniFrame):
693 692 wx = self.wx
694 693 IP = self.IP
695 694 tk = self.tk
696 695 def __init__(self, parent, interval):
697 696 style = self.wx.wxDEFAULT_FRAME_STYLE | self.wx.wxTINY_CAPTION_HORIZ
698 697 self.wx.wxMiniFrame.__init__(self, parent, -1, ' ', pos=(200, 200),
699 698 size=(100, 100),style=style)
700 699 self.Show(False)
701 700 self.interval = interval
702 701 self.timerId = self.wx.wxNewId()
703 702
704 703 def StartWork(self):
705 704 self.timer = self.wx.wxTimer(self, self.timerId)
706 705 self.wx.EVT_TIMER(self, self.timerId, self.OnTimer)
707 706 self.timer.Start(self.interval)
708 707
709 708 def OnTimer(self, event):
710 709 update_tk(self.tk)
711 710 self.IP.runcode()
712 711
713 712 class App(self.wx.wxApp):
714 713 wx = self.wx
715 714 TIMEOUT = self.TIMEOUT
716 715 def OnInit(self):
717 716 'Create the main window and insert the custom frame'
718 717 self.agent = TimerAgent(None, self.TIMEOUT)
719 718 self.agent.Show(self.wx.false)
720 719 self.agent.StartWork()
721 720 return self.wx.true
722 721
723 722 self.app = App(redirect=False)
724 723 self.wx_mainloop(self.app)
725 724 self.join()
726 725
727 726
728 727 class IPShellQt(threading.Thread):
729 728 """Run a Qt event loop in a separate thread.
730 729
731 730 Python commands can be passed to the thread where they will be executed.
732 731 This is implemented by periodically checking for passed code using a
733 732 Qt timer / slot."""
734 733
735 734 TIMEOUT = 100 # Millisecond interval between timeouts.
736 735
737 736 def __init__(self,argv=None,user_ns=None,debug=0,
738 737 shell_class=MTInteractiveShell):
739 738
740 739 import qt
741 740
742 741 class newQApplication:
743 742 def __init__( self ):
744 743 self.QApplication = qt.QApplication
745 744
746 745 def __call__( *args, **kwargs ):
747 746 return qt.qApp
748 747
749 748 def exec_loop( *args, **kwargs ):
750 749 pass
751 750
752 751 def __getattr__( self, name ):
753 752 return getattr( self.QApplication, name )
754 753
755 754 qt.QApplication = newQApplication()
756 755
757 756 # Allows us to use both Tk and QT.
758 757 self.tk = get_tk()
759 758
760 759 self.IP = make_IPython(argv,user_ns=user_ns,debug=debug,
761 760 shell_class=shell_class,
762 761 on_kill=[qt.qApp.exit])
763 762
764 763 threading.Thread.__init__(self)
765 764
766 765 def run(self):
767 766 #sys.excepthook = self.IP.excepthook # dbg
768 767 self.IP.mainloop()
769 768 self.IP.kill()
770 769
771 770 def mainloop(self):
772 771 import qt, sys
773 772 if qt.QApplication.startingUp():
774 773 a = qt.QApplication.QApplication( sys.argv )
775 774 self.timer = qt.QTimer()
776 775 qt.QObject.connect( self.timer, qt.SIGNAL( 'timeout()' ), self.on_timer )
777 776
778 777 self.start()
779 778 self.timer.start( self.TIMEOUT, True )
780 779 while True:
781 780 if self.IP._kill: break
782 781 qt.qApp.exec_loop()
783 782 self.join()
784 783
785 784 def on_timer(self):
786 785 update_tk(self.tk)
787 786 result = self.IP.runcode()
788 787 self.timer.start( self.TIMEOUT, True )
789 788 return result
790 789
791 790 # A set of matplotlib public IPython shell classes, for single-threaded
792 791 # (Tk* and FLTK* backends) and multithreaded (GTK* and WX* backends) use.
793 792 class IPShellMatplotlib(IPShell):
794 793 """Subclass IPShell with MatplotlibShell as the internal shell.
795 794
796 795 Single-threaded class, meant for the Tk* and FLTK* backends.
797 796
798 797 Having this on a separate class simplifies the external driver code."""
799 798
800 799 def __init__(self,argv=None,user_ns=None,debug=1):
801 800 IPShell.__init__(self,argv,user_ns,debug,shell_class=MatplotlibShell)
802 801
803 802 class IPShellMatplotlibGTK(IPShellGTK):
804 803 """Subclass IPShellGTK with MatplotlibMTShell as the internal shell.
805 804
806 805 Multi-threaded class, meant for the GTK* backends."""
807 806
808 807 def __init__(self,argv=None,user_ns=None,debug=1):
809 808 IPShellGTK.__init__(self,argv,user_ns,debug,shell_class=MatplotlibMTShell)
810 809
811 810 class IPShellMatplotlibWX(IPShellWX):
812 811 """Subclass IPShellWX with MatplotlibMTShell as the internal shell.
813 812
814 813 Multi-threaded class, meant for the WX* backends."""
815 814
816 815 def __init__(self,argv=None,user_ns=None,debug=1):
817 816 IPShellWX.__init__(self,argv,user_ns,debug,shell_class=MatplotlibMTShell)
818 817
819 818 class IPShellMatplotlibQt(IPShellQt):
820 819 """Subclass IPShellQt with MatplotlibMTShell as the internal shell.
821 820
822 821 Multi-threaded class, meant for the Qt* backends."""
823 822
824 823 def __init__(self,argv=None,user_ns=None,debug=1):
825 824 IPShellQt.__init__(self,argv,user_ns,debug,shell_class=MatplotlibMTShell)
826 825
827 826 #-----------------------------------------------------------------------------
828 827 # Factory functions to actually start the proper thread-aware shell
829 828
830 829 def _matplotlib_shell_class():
831 830 """Factory function to handle shell class selection for matplotlib.
832 831
833 832 The proper shell class to use depends on the matplotlib backend, since
834 833 each backend requires a different threading strategy."""
835 834
836 835 try:
837 836 import matplotlib
838 837 except ImportError:
839 838 error('matplotlib could NOT be imported! Starting normal IPython.')
840 839 sh_class = IPShell
841 840 else:
842 841 backend = matplotlib.rcParams['backend']
843 842 if backend.startswith('GTK'):
844 843 sh_class = IPShellMatplotlibGTK
845 844 elif backend.startswith('WX'):
846 845 sh_class = IPShellMatplotlibWX
847 846 elif backend.startswith('Qt'):
848 847 sh_class = IPShellMatplotlibQt
849 848 else:
850 849 sh_class = IPShellMatplotlib
851 850 #print 'Using %s with the %s backend.' % (sh_class,backend) # dbg
852 851 return sh_class
853 852
854 853 # This is the one which should be called by external code.
855 854 def start():
856 855 """Return a running shell instance, dealing with threading options.
857 856
858 857 This is a factory function which will instantiate the proper IPython shell
859 858 based on the user's threading choice. Such a selector is needed because
860 859 different GUI toolkits require different thread handling details."""
861 860
862 861 global USE_TK
863 862 # Crude sys.argv hack to extract the threading options.
864 863 if len(sys.argv) > 1:
865 864 if len(sys.argv) > 2:
866 865 arg2 = sys.argv[2]
867 866 if arg2.endswith('-tk'):
868 867 USE_TK = True
869 868 arg1 = sys.argv[1]
870 869 if arg1.endswith('-gthread'):
871 870 shell = IPShellGTK
872 871 elif arg1.endswith( '-qthread' ):
873 872 shell = IPShellQt
874 873 elif arg1.endswith('-wthread'):
875 874 shell = IPShellWX
876 875 elif arg1.endswith('-pylab'):
877 876 shell = _matplotlib_shell_class()
878 877 else:
879 878 shell = IPShell
880 879 else:
881 880 shell = IPShell
882 881 return shell()
883 882
884 883 # Some aliases for backwards compatibility
885 884 IPythonShell = IPShell
886 885 IPythonShellEmbed = IPShellEmbed
887 886 #************************ End of file <Shell.py> ***************************
@@ -1,1520 +1,1521 b''
1 1 # -*- coding: utf-8 -*-
2 2 """
3 3 General purpose utilities.
4 4
5 5 This is a grab-bag of stuff I find useful in most programs I write. Some of
6 6 these things are also convenient when working at the command line.
7 7
8 $Id: genutils.py 645 2005-07-19 01:59:26Z fperez $"""
8 $Id: genutils.py 703 2005-08-16 17:34:44Z fperez $"""
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 from __future__ import generators # 2.2 compatibility
18
17 19 from IPython import Release
18 20 __author__ = '%s <%s>' % Release.authors['Fernando']
19 21 __license__ = Release.license
20 22
21 23 #****************************************************************************
22 24 # required modules
23 25 import __main__
24 26 import types,commands,time,sys,os,re,shutil
25 27 import tempfile
26 import codecs
27 28 from IPython.Itpl import Itpl,itpl,printpl
28 29 from IPython import DPyGetOpt
29 30
30 31 # Build objects which appeared in Python 2.3 for 2.2, to make ipython
31 32 # 2.2-friendly
32 33 try:
33 34 basestring
34 35 except NameError:
35 36 import types
36 37 basestring = (types.StringType, types.UnicodeType)
37 38 True = 1==1
38 39 False = 1==0
39 40
40 41 def enumerate(obj):
41 42 i = -1
42 43 for item in obj:
43 44 i += 1
44 45 yield i, item
45 46
46 47 # add these to the builtin namespace, so that all modules find them
47 48 import __builtin__
48 49 __builtin__.basestring = basestring
49 50 __builtin__.True = True
50 51 __builtin__.False = False
51 52 __builtin__.enumerate = enumerate
52 53
53 54 #****************************************************************************
54 55 # Exceptions
55 56 class Error(Exception):
56 57 """Base class for exceptions in this module."""
57 58 pass
58 59
59 60 #----------------------------------------------------------------------------
60 61 class IOStream:
61 62 def __init__(self,stream,fallback):
62 63 if not hasattr(stream,'write') or not hasattr(stream,'flush'):
63 64 stream = fallback
64 65 self.stream = stream
65 66 self._swrite = stream.write
66 67 self.flush = stream.flush
67 68
68 69 def write(self,data):
69 70 try:
70 71 self._swrite(data)
71 72 except:
72 73 try:
73 74 # print handles some unicode issues which may trip a plain
74 75 # write() call. Attempt to emulate write() by using a
75 76 # trailing comma
76 77 print >> self.stream, data,
77 78 except:
78 79 # if we get here, something is seriously broken.
79 80 print >> sys.stderr, \
80 81 'ERROR - failed to write data to stream:', stream
81 82
82 83 class IOTerm:
83 84 """ Term holds the file or file-like objects for handling I/O operations.
84 85
85 86 These are normally just sys.stdin, sys.stdout and sys.stderr but for
86 87 Windows they can can replaced to allow editing the strings before they are
87 88 displayed."""
88 89
89 90 # In the future, having IPython channel all its I/O operations through
90 91 # this class will make it easier to embed it into other environments which
91 92 # are not a normal terminal (such as a GUI-based shell)
92 93 def __init__(self,cin=None,cout=None,cerr=None):
93 94 self.cin = IOStream(cin,sys.stdin)
94 95 self.cout = IOStream(cout,sys.stdout)
95 96 self.cerr = IOStream(cerr,sys.stderr)
96 97
97 98 # Global variable to be used for all I/O
98 99 Term = IOTerm()
99 100
100 101 # Windows-specific code to load Gary Bishop's readline and configure it
101 102 # automatically for the users
102 103 # Note: os.name on cygwin returns posix, so this should only pick up 'native'
103 104 # windows. Cygwin returns 'cygwin' for sys.platform.
104 105 if os.name == 'nt':
105 106 try:
106 107 import readline
107 108 except ImportError:
108 109 pass
109 110 else:
110 111 try:
111 112 _out = readline.GetOutputFile()
112 113 except AttributeError:
113 114 pass
114 115 else:
115 116 # Remake Term to use the readline i/o facilities
116 117 Term = IOTerm(cout=_out,cerr=_out)
117 118 del _out
118 119
119 120 #****************************************************************************
120 121 # Generic warning/error printer, used by everything else
121 122 def warn(msg,level=2,exit_val=1):
122 123 """Standard warning printer. Gives formatting consistency.
123 124
124 125 Output is sent to Term.cerr (sys.stderr by default).
125 126
126 127 Options:
127 128
128 129 -level(2): allows finer control:
129 130 0 -> Do nothing, dummy function.
130 131 1 -> Print message.
131 132 2 -> Print 'WARNING:' + message. (Default level).
132 133 3 -> Print 'ERROR:' + message.
133 134 4 -> Print 'FATAL ERROR:' + message and trigger a sys.exit(exit_val).
134 135
135 136 -exit_val (1): exit value returned by sys.exit() for a level 4
136 137 warning. Ignored for all other levels."""
137 138
138 139 if level>0:
139 140 header = ['','','WARNING: ','ERROR: ','FATAL ERROR: ']
140 141 print >> Term.cerr, '%s%s' % (header[level],msg)
141 142 if level == 4:
142 143 print >> Term.cerr,'Exiting.\n'
143 144 sys.exit(exit_val)
144 145
145 146 def info(msg):
146 147 """Equivalent to warn(msg,level=1)."""
147 148
148 149 warn(msg,level=1)
149 150
150 151 def error(msg):
151 152 """Equivalent to warn(msg,level=3)."""
152 153
153 154 warn(msg,level=3)
154 155
155 156 def fatal(msg,exit_val=1):
156 157 """Equivalent to warn(msg,exit_val=exit_val,level=4)."""
157 158
158 159 warn(msg,exit_val=exit_val,level=4)
159 160
160 161 #----------------------------------------------------------------------------
161 162 StringTypes = types.StringTypes
162 163
163 164 # Basic timing functionality
164 165
165 166 # If possible (Unix), use the resource module instead of time.clock()
166 167 try:
167 168 import resource
168 169 def clock():
169 170 """clock() -> floating point number
170 171
171 172 Return the CPU time in seconds (user time only, system time is
172 173 ignored) since the start of the process. This is done via a call to
173 174 resource.getrusage, so it avoids the wraparound problems in
174 175 time.clock()."""
175 176
176 177 return resource.getrusage(resource.RUSAGE_SELF)[0]
177 178
178 179 def clock2():
179 180 """clock2() -> (t_user,t_system)
180 181
181 182 Similar to clock(), but return a tuple of user/system times."""
182 183 return resource.getrusage(resource.RUSAGE_SELF)[:2]
183 184
184 185 except ImportError:
185 186 clock = time.clock
186 187 def clock2():
187 188 """Under windows, system CPU time can't be measured.
188 189
189 190 This just returns clock() and zero."""
190 191 return time.clock(),0.0
191 192
192 193 def timings_out(reps,func,*args,**kw):
193 194 """timings_out(reps,func,*args,**kw) -> (t_total,t_per_call,output)
194 195
195 196 Execute a function reps times, return a tuple with the elapsed total
196 197 CPU time in seconds, the time per call and the function's output.
197 198
198 199 Under Unix, the return value is the sum of user+system time consumed by
199 200 the process, computed via the resource module. This prevents problems
200 201 related to the wraparound effect which the time.clock() function has.
201 202
202 203 Under Windows the return value is in wall clock seconds. See the
203 204 documentation for the time module for more details."""
204 205
205 206 reps = int(reps)
206 207 assert reps >=1, 'reps must be >= 1'
207 208 if reps==1:
208 209 start = clock()
209 210 out = func(*args,**kw)
210 211 tot_time = clock()-start
211 212 else:
212 213 rng = xrange(reps-1) # the last time is executed separately to store output
213 214 start = clock()
214 215 for dummy in rng: func(*args,**kw)
215 216 out = func(*args,**kw) # one last time
216 217 tot_time = clock()-start
217 218 av_time = tot_time / reps
218 219 return tot_time,av_time,out
219 220
220 221 def timings(reps,func,*args,**kw):
221 222 """timings(reps,func,*args,**kw) -> (t_total,t_per_call)
222 223
223 224 Execute a function reps times, return a tuple with the elapsed total CPU
224 225 time in seconds and the time per call. These are just the first two values
225 226 in timings_out()."""
226 227
227 228 return timings_out(reps,func,*args,**kw)[0:2]
228 229
229 230 def timing(func,*args,**kw):
230 231 """timing(func,*args,**kw) -> t_total
231 232
232 233 Execute a function once, return the elapsed total CPU time in
233 234 seconds. This is just the first value in timings_out()."""
234 235
235 236 return timings_out(1,func,*args,**kw)[0]
236 237
237 238 #****************************************************************************
238 239 # file and system
239 240
240 241 def system(cmd,verbose=0,debug=0,header=''):
241 242 """Execute a system command, return its exit status.
242 243
243 244 Options:
244 245
245 246 - verbose (0): print the command to be executed.
246 247
247 248 - debug (0): only print, do not actually execute.
248 249
249 250 - header (''): Header to print on screen prior to the executed command (it
250 251 is only prepended to the command, no newlines are added).
251 252
252 253 Note: a stateful version of this function is available through the
253 254 SystemExec class."""
254 255
255 256 stat = 0
256 257 if verbose or debug: print header+cmd
257 258 sys.stdout.flush()
258 259 if not debug: stat = os.system(cmd)
259 260 return stat
260 261
261 262 def shell(cmd,verbose=0,debug=0,header=''):
262 263 """Execute a command in the system shell, always return None.
263 264
264 265 Options:
265 266
266 267 - verbose (0): print the command to be executed.
267 268
268 269 - debug (0): only print, do not actually execute.
269 270
270 271 - header (''): Header to print on screen prior to the executed command (it
271 272 is only prepended to the command, no newlines are added).
272 273
273 274 Note: this is similar to genutils.system(), but it returns None so it can
274 275 be conveniently used in interactive loops without getting the return value
275 276 (typically 0) printed many times."""
276 277
277 278 stat = 0
278 279 if verbose or debug: print header+cmd
279 280 # flush stdout so we don't mangle python's buffering
280 281 sys.stdout.flush()
281 282 if not debug:
282 283 os.system(cmd)
283 284
284 285 def getoutput(cmd,verbose=0,debug=0,header='',split=0):
285 286 """Dummy substitute for perl's backquotes.
286 287
287 288 Executes a command and returns the output.
288 289
289 290 Accepts the same arguments as system(), plus:
290 291
291 292 - split(0): if true, the output is returned as a list split on newlines.
292 293
293 294 Note: a stateful version of this function is available through the
294 295 SystemExec class."""
295 296
296 297 if verbose or debug: print header+cmd
297 298 if not debug:
298 299 output = commands.getoutput(cmd)
299 300 if split:
300 301 return output.split('\n')
301 302 else:
302 303 return output
303 304
304 305 def getoutputerror(cmd,verbose=0,debug=0,header='',split=0):
305 306 """Return (standard output,standard error) of executing cmd in a shell.
306 307
307 308 Accepts the same arguments as system(), plus:
308 309
309 310 - split(0): if true, each of stdout/err is returned as a list split on
310 311 newlines.
311 312
312 313 Note: a stateful version of this function is available through the
313 314 SystemExec class."""
314 315
315 316 if verbose or debug: print header+cmd
316 317 if not cmd:
317 318 if split:
318 319 return [],[]
319 320 else:
320 321 return '',''
321 322 if not debug:
322 323 pin,pout,perr = os.popen3(cmd)
323 324 tout = pout.read().rstrip()
324 325 terr = perr.read().rstrip()
325 326 pin.close()
326 327 pout.close()
327 328 perr.close()
328 329 if split:
329 330 return tout.split('\n'),terr.split('\n')
330 331 else:
331 332 return tout,terr
332 333
333 334 # for compatibility with older naming conventions
334 335 xsys = system
335 336 bq = getoutput
336 337
337 338 class SystemExec:
338 339 """Access the system and getoutput functions through a stateful interface.
339 340
340 341 Note: here we refer to the system and getoutput functions from this
341 342 library, not the ones from the standard python library.
342 343
343 344 This class offers the system and getoutput functions as methods, but the
344 345 verbose, debug and header parameters can be set for the instance (at
345 346 creation time or later) so that they don't need to be specified on each
346 347 call.
347 348
348 349 For efficiency reasons, there's no way to override the parameters on a
349 350 per-call basis other than by setting instance attributes. If you need
350 351 local overrides, it's best to directly call system() or getoutput().
351 352
352 353 The following names are provided as alternate options:
353 354 - xsys: alias to system
354 355 - bq: alias to getoutput
355 356
356 357 An instance can then be created as:
357 358 >>> sysexec = SystemExec(verbose=1,debug=0,header='Calling: ')
358 359
359 360 And used as:
360 361 >>> sysexec.xsys('pwd')
361 362 >>> dirlist = sysexec.bq('ls -l')
362 363 """
363 364
364 365 def __init__(self,verbose=0,debug=0,header='',split=0):
365 366 """Specify the instance's values for verbose, debug and header."""
366 367 setattr_list(self,'verbose debug header split')
367 368
368 369 def system(self,cmd):
369 370 """Stateful interface to system(), with the same keyword parameters."""
370 371
371 372 system(cmd,self.verbose,self.debug,self.header)
372 373
373 374 def shell(self,cmd):
374 375 """Stateful interface to shell(), with the same keyword parameters."""
375 376
376 377 shell(cmd,self.verbose,self.debug,self.header)
377 378
378 379 xsys = system # alias
379 380
380 381 def getoutput(self,cmd):
381 382 """Stateful interface to getoutput()."""
382 383
383 384 return getoutput(cmd,self.verbose,self.debug,self.header,self.split)
384 385
385 386 def getoutputerror(self,cmd):
386 387 """Stateful interface to getoutputerror()."""
387 388
388 389 return getoutputerror(cmd,self.verbose,self.debug,self.header,self.split)
389 390
390 391 bq = getoutput # alias
391 392
392 393 #-----------------------------------------------------------------------------
393 394 def mutex_opts(dict,ex_op):
394 395 """Check for presence of mutually exclusive keys in a dict.
395 396
396 397 Call: mutex_opts(dict,[[op1a,op1b],[op2a,op2b]...]"""
397 398 for op1,op2 in ex_op:
398 399 if op1 in dict and op2 in dict:
399 400 raise ValueError,'\n*** ERROR in Arguments *** '\
400 401 'Options '+op1+' and '+op2+' are mutually exclusive.'
401 402
402 403 #-----------------------------------------------------------------------------
403 404 def filefind(fname,alt_dirs = None):
404 405 """Return the given filename either in the current directory, if it
405 406 exists, or in a specified list of directories.
406 407
407 408 ~ expansion is done on all file and directory names.
408 409
409 410 Upon an unsuccessful search, raise an IOError exception."""
410 411
411 412 if alt_dirs is None:
412 413 try:
413 414 alt_dirs = get_home_dir()
414 415 except HomeDirError:
415 416 alt_dirs = os.getcwd()
416 417 search = [fname] + list_strings(alt_dirs)
417 418 search = map(os.path.expanduser,search)
418 419 #print 'search list for',fname,'list:',search # dbg
419 420 fname = search[0]
420 421 if os.path.isfile(fname):
421 422 return fname
422 423 for direc in search[1:]:
423 424 testname = os.path.join(direc,fname)
424 425 #print 'testname',testname # dbg
425 426 if os.path.isfile(testname):
426 427 return testname
427 428 raise IOError,'File' + `fname` + \
428 429 ' not found in current or supplied directories:' + `alt_dirs`
429 430
430 431 #----------------------------------------------------------------------------
431 432 def target_outdated(target,deps):
432 433 """Determine whether a target is out of date.
433 434
434 435 target_outdated(target,deps) -> 1/0
435 436
436 437 deps: list of filenames which MUST exist.
437 438 target: single filename which may or may not exist.
438 439
439 440 If target doesn't exist or is older than any file listed in deps, return
440 441 true, otherwise return false.
441 442 """
442 443 try:
443 444 target_time = os.path.getmtime(target)
444 445 except os.error:
445 446 return 1
446 447 for dep in deps:
447 448 dep_time = os.path.getmtime(dep)
448 449 if dep_time > target_time:
449 450 #print "For target",target,"Dep failed:",dep # dbg
450 451 #print "times (dep,tar):",dep_time,target_time # dbg
451 452 return 1
452 453 return 0
453 454
454 455 #-----------------------------------------------------------------------------
455 456 def target_update(target,deps,cmd):
456 457 """Update a target with a given command given a list of dependencies.
457 458
458 459 target_update(target,deps,cmd) -> runs cmd if target is outdated.
459 460
460 461 This is just a wrapper around target_outdated() which calls the given
461 462 command if target is outdated."""
462 463
463 464 if target_outdated(target,deps):
464 465 xsys(cmd)
465 466
466 467 #----------------------------------------------------------------------------
467 468 def unquote_ends(istr):
468 469 """Remove a single pair of quotes from the endpoints of a string."""
469 470
470 471 if not istr:
471 472 return istr
472 473 if (istr[0]=="'" and istr[-1]=="'") or \
473 474 (istr[0]=='"' and istr[-1]=='"'):
474 475 return istr[1:-1]
475 476 else:
476 477 return istr
477 478
478 479 #----------------------------------------------------------------------------
479 480 def process_cmdline(argv,names=[],defaults={},usage=''):
480 481 """ Process command-line options and arguments.
481 482
482 483 Arguments:
483 484
484 485 - argv: list of arguments, typically sys.argv.
485 486
486 487 - names: list of option names. See DPyGetOpt docs for details on options
487 488 syntax.
488 489
489 490 - defaults: dict of default values.
490 491
491 492 - usage: optional usage notice to print if a wrong argument is passed.
492 493
493 494 Return a dict of options and a list of free arguments."""
494 495
495 496 getopt = DPyGetOpt.DPyGetOpt()
496 497 getopt.setIgnoreCase(0)
497 498 getopt.parseConfiguration(names)
498 499
499 500 try:
500 501 getopt.processArguments(argv)
501 502 except:
502 503 print usage
503 504 warn(`sys.exc_value`,level=4)
504 505
505 506 defaults.update(getopt.optionValues)
506 507 args = getopt.freeValues
507 508
508 509 return defaults,args
509 510
510 511 #----------------------------------------------------------------------------
511 512 def optstr2types(ostr):
512 513 """Convert a string of option names to a dict of type mappings.
513 514
514 515 optstr2types(str) -> {None:'string_opts',int:'int_opts',float:'float_opts'}
515 516
516 517 This is used to get the types of all the options in a string formatted
517 518 with the conventions of DPyGetOpt. The 'type' None is used for options
518 519 which are strings (they need no further conversion). This function's main
519 520 use is to get a typemap for use with read_dict().
520 521 """
521 522
522 523 typeconv = {None:'',int:'',float:''}
523 524 typemap = {'s':None,'i':int,'f':float}
524 525 opt_re = re.compile(r'([\w]*)([^:=]*:?=?)([sif]?)')
525 526
526 527 for w in ostr.split():
527 528 oname,alias,otype = opt_re.match(w).groups()
528 529 if otype == '' or alias == '!': # simple switches are integers too
529 530 otype = 'i'
530 531 typeconv[typemap[otype]] += oname + ' '
531 532 return typeconv
532 533
533 534 #----------------------------------------------------------------------------
534 535 def read_dict(filename,type_conv=None,**opt):
535 536
536 537 """Read a dictionary of key=value pairs from an input file, optionally
537 538 performing conversions on the resulting values.
538 539
539 540 read_dict(filename,type_conv,**opt) -> dict
540 541
541 542 Only one value per line is accepted, the format should be
542 543 # optional comments are ignored
543 544 key value\n
544 545
545 546 Args:
546 547
547 548 - type_conv: A dictionary specifying which keys need to be converted to
548 549 which types. By default all keys are read as strings. This dictionary
549 550 should have as its keys valid conversion functions for strings
550 551 (int,long,float,complex, or your own). The value for each key
551 552 (converter) should be a whitespace separated string containing the names
552 553 of all the entries in the file to be converted using that function. For
553 554 keys to be left alone, use None as the conversion function (only needed
554 555 with purge=1, see below).
555 556
556 557 - opt: dictionary with extra options as below (default in parens)
557 558
558 559 purge(0): if set to 1, all keys *not* listed in type_conv are purged out
559 560 of the dictionary to be returned. If purge is going to be used, the
560 561 set of keys to be left as strings also has to be explicitly specified
561 562 using the (non-existent) conversion function None.
562 563
563 564 fs(None): field separator. This is the key/value separator to be used
564 565 when parsing the file. The None default means any whitespace [behavior
565 566 of string.split()].
566 567
567 568 strip(0): if 1, strip string values of leading/trailinig whitespace.
568 569
569 570 warn(1): warning level if requested keys are not found in file.
570 571 - 0: silently ignore.
571 572 - 1: inform but proceed.
572 573 - 2: raise KeyError exception.
573 574
574 575 no_empty(0): if 1, remove keys with whitespace strings as a value.
575 576
576 577 unique([]): list of keys (or space separated string) which can't be
577 578 repeated. If one such key is found in the file, each new instance
578 579 overwrites the previous one. For keys not listed here, the behavior is
579 580 to make a list of all appearances.
580 581
581 582 Example:
582 583 If the input file test.ini has:
583 584 i 3
584 585 x 4.5
585 586 y 5.5
586 587 s hi ho
587 588 Then:
588 589
589 590 >>> type_conv={int:'i',float:'x',None:'s'}
590 591 >>> read_dict('test.ini')
591 592 {'i': '3', 's': 'hi ho', 'x': '4.5', 'y': '5.5'}
592 593 >>> read_dict('test.ini',type_conv)
593 594 {'i': 3, 's': 'hi ho', 'x': 4.5, 'y': '5.5'}
594 595 >>> read_dict('test.ini',type_conv,purge=1)
595 596 {'i': 3, 's': 'hi ho', 'x': 4.5}
596 597 """
597 598
598 599 # starting config
599 600 opt.setdefault('purge',0)
600 601 opt.setdefault('fs',None) # field sep defaults to any whitespace
601 602 opt.setdefault('strip',0)
602 603 opt.setdefault('warn',1)
603 604 opt.setdefault('no_empty',0)
604 605 opt.setdefault('unique','')
605 606 if type(opt['unique']) in StringTypes:
606 607 unique_keys = qw(opt['unique'])
607 608 elif type(opt['unique']) in (types.TupleType,types.ListType):
608 609 unique_keys = opt['unique']
609 610 else:
610 611 raise ValueError, 'Unique keys must be given as a string, List or Tuple'
611 612
612 613 dict = {}
613 614 # first read in table of values as strings
614 615 file = open(filename,'r')
615 616 for line in file.readlines():
616 617 line = line.strip()
617 618 if len(line) and line[0]=='#': continue
618 619 if len(line)>0:
619 620 lsplit = line.split(opt['fs'],1)
620 621 try:
621 622 key,val = lsplit
622 623 except ValueError:
623 624 key,val = lsplit[0],''
624 625 key = key.strip()
625 626 if opt['strip']: val = val.strip()
626 627 if val == "''" or val == '""': val = ''
627 628 if opt['no_empty'] and (val=='' or val.isspace()):
628 629 continue
629 630 # if a key is found more than once in the file, build a list
630 631 # unless it's in the 'unique' list. In that case, last found in file
631 632 # takes precedence. User beware.
632 633 try:
633 634 if dict[key] and key in unique_keys:
634 635 dict[key] = val
635 636 elif type(dict[key]) is types.ListType:
636 637 dict[key].append(val)
637 638 else:
638 639 dict[key] = [dict[key],val]
639 640 except KeyError:
640 641 dict[key] = val
641 642 # purge if requested
642 643 if opt['purge']:
643 644 accepted_keys = qwflat(type_conv.values())
644 645 for key in dict.keys():
645 646 if key in accepted_keys: continue
646 647 del(dict[key])
647 648 # now convert if requested
648 649 if type_conv==None: return dict
649 650 conversions = type_conv.keys()
650 651 try: conversions.remove(None)
651 652 except: pass
652 653 for convert in conversions:
653 654 for val in qw(type_conv[convert]):
654 655 try:
655 656 dict[val] = convert(dict[val])
656 657 except KeyError,e:
657 658 if opt['warn'] == 0:
658 659 pass
659 660 elif opt['warn'] == 1:
660 661 print >>sys.stderr, 'Warning: key',val,\
661 662 'not found in file',filename
662 663 elif opt['warn'] == 2:
663 664 raise KeyError,e
664 665 else:
665 666 raise ValueError,'Warning level must be 0,1 or 2'
666 667
667 668 return dict
668 669
669 670 #----------------------------------------------------------------------------
670 671 def flag_calls(func):
671 672 """Wrap a function to detect and flag when it gets called.
672 673
673 674 This is a decorator which takes a function and wraps it in a function with
674 675 a 'called' attribute. wrapper.called is initialized to False.
675 676
676 677 The wrapper.called attribute is set to False right before each call to the
677 678 wrapped function, so if the call fails it remains False. After the call
678 679 completes, wrapper.called is set to True and the output is returned.
679 680
680 681 Testing for truth in wrapper.called allows you to determine if a call to
681 682 func() was attempted and succeeded."""
682 683
683 684 def wrapper(*args,**kw):
684 685 wrapper.called = False
685 686 out = func(*args,**kw)
686 687 wrapper.called = True
687 688 return out
688 689
689 690 wrapper.called = False
690 691 wrapper.__doc__ = func.__doc__
691 692 return wrapper
692 693
693 694 #----------------------------------------------------------------------------
694 695 class HomeDirError(Error):
695 696 pass
696 697
697 698 def get_home_dir():
698 699 """Return the closest possible equivalent to a 'home' directory.
699 700
700 701 We first try $HOME. Absent that, on NT it's $HOMEDRIVE\$HOMEPATH.
701 702
702 703 Currently only Posix and NT are implemented, a HomeDirError exception is
703 704 raised for all other OSes. """
704 705
705 706 isdir = os.path.isdir
706 707 env = os.environ
707 708 try:
708 709 homedir = env['HOME']
709 710 if not isdir(homedir):
710 711 # in case a user stuck some string which does NOT resolve to a
711 712 # valid path, it's as good as if we hadn't foud it
712 713 raise KeyError
713 714 return homedir
714 715 except KeyError:
715 716 if os.name == 'posix':
716 717 raise HomeDirError,'undefined $HOME, IPython can not proceed.'
717 718 elif os.name == 'nt':
718 719 # For some strange reason, win9x returns 'nt' for os.name.
719 720 try:
720 721 homedir = os.path.join(env['HOMEDRIVE'],env['HOMEPATH'])
721 722 if not isdir(homedir):
722 723 homedir = os.path.join(env['USERPROFILE'])
723 724 if not isdir(homedir):
724 725 raise HomeDirError
725 726 return homedir
726 727 except:
727 728 try:
728 729 # Use the registry to get the 'My Documents' folder.
729 730 import _winreg as wreg
730 731 key = wreg.OpenKey(wreg.HKEY_CURRENT_USER,
731 732 "Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders")
732 733 homedir = wreg.QueryValueEx(key,'Personal')[0]
733 734 key.Close()
734 735 return homedir
735 736 except:
736 737 return 'C:\\'
737 738 elif os.name == 'dos':
738 739 # Desperate, may do absurd things in classic MacOS. May work under DOS.
739 740 return 'C:\\'
740 741 else:
741 742 raise HomeDirError,'support for your operating system not implemented.'
742 743
743 744 #****************************************************************************
744 745 # strings and text
745 746
746 747 class LSString(str):
747 748 """String derivative with a special access attributes.
748 749
749 750 These are normal strings, but with the special attributes:
750 751
751 752 .l (or .list) : value as list (split on newlines).
752 753 .n (or .nlstr): original value (the string itself).
753 754 .s (or .spstr): value as whitespace-separated string.
754 755
755 756 Any values which require transformations are computed only once and
756 757 cached.
757 758
758 759 Such strings are very useful to efficiently interact with the shell, which
759 760 typically only understands whitespace-separated options for commands."""
760 761
761 762 def get_list(self):
762 763 try:
763 764 return self.__list
764 765 except AttributeError:
765 766 self.__list = self.split('\n')
766 767 return self.__list
767 768
768 769 l = list = property(get_list)
769 770
770 771 def get_spstr(self):
771 772 try:
772 773 return self.__spstr
773 774 except AttributeError:
774 775 self.__spstr = self.replace('\n',' ')
775 776 return self.__spstr
776 777
777 778 s = spstr = property(get_spstr)
778 779
779 780 def get_nlstr(self):
780 781 return self
781 782
782 783 n = nlstr = property(get_nlstr)
783 784
784 785 class SList(list):
785 786 """List derivative with a special access attributes.
786 787
787 788 These are normal lists, but with the special attributes:
788 789
789 790 .l (or .list) : value as list (the list itself).
790 791 .n (or .nlstr): value as a string, joined on newlines.
791 792 .s (or .spstr): value as a string, joined on spaces.
792 793
793 794 Any values which require transformations are computed only once and
794 795 cached."""
795 796
796 797 def get_list(self):
797 798 return self
798 799
799 800 l = list = property(get_list)
800 801
801 802 def get_spstr(self):
802 803 try:
803 804 return self.__spstr
804 805 except AttributeError:
805 806 self.__spstr = ' '.join(self)
806 807 return self.__spstr
807 808
808 809 s = spstr = property(get_spstr)
809 810
810 811 def get_nlstr(self):
811 812 try:
812 813 return self.__nlstr
813 814 except AttributeError:
814 815 self.__nlstr = '\n'.join(self)
815 816 return self.__nlstr
816 817
817 818 n = nlstr = property(get_nlstr)
818 819
819 820 def raw_input_multi(header='', ps1='==> ', ps2='..> ',terminate_str = '.'):
820 821 """Take multiple lines of input.
821 822
822 823 A list with each line of input as a separate element is returned when a
823 824 termination string is entered (defaults to a single '.'). Input can also
824 825 terminate via EOF (^D in Unix, ^Z-RET in Windows).
825 826
826 827 Lines of input which end in \\ are joined into single entries (and a
827 828 secondary continuation prompt is issued as long as the user terminates
828 829 lines with \\). This allows entering very long strings which are still
829 830 meant to be treated as single entities.
830 831 """
831 832
832 833 try:
833 834 if header:
834 835 header += '\n'
835 836 lines = [raw_input(header + ps1)]
836 837 except EOFError:
837 838 return []
838 839 terminate = [terminate_str]
839 840 try:
840 841 while lines[-1:] != terminate:
841 842 new_line = raw_input(ps1)
842 843 while new_line.endswith('\\'):
843 844 new_line = new_line[:-1] + raw_input(ps2)
844 845 lines.append(new_line)
845 846
846 847 return lines[:-1] # don't return the termination command
847 848 except EOFError:
848 849 print
849 850 return lines
850 851
851 852 #----------------------------------------------------------------------------
852 853 def raw_input_ext(prompt='', ps2='... '):
853 854 """Similar to raw_input(), but accepts extended lines if input ends with \\."""
854 855
855 856 line = raw_input(prompt)
856 857 while line.endswith('\\'):
857 858 line = line[:-1] + raw_input(ps2)
858 859 return line
859 860
860 861 #----------------------------------------------------------------------------
861 862 def ask_yes_no(prompt,default=None):
862 863 """Asks a question and returns an integer 1/0 (y/n) answer.
863 864
864 865 If default is given (one of 'y','n'), it is used if the user input is
865 866 empty. Otherwise the question is repeated until an answer is given.
866 867 If EOF occurs 20 times consecutively, the default answer is assumed,
867 868 or if there is no default, an exception is raised to prevent infinite
868 869 loops.
869 870
870 871 Valid answers are: y/yes/n/no (match is not case sensitive)."""
871 872
872 873 answers = {'y':1,'n':0,'yes':1,'no':0}
873 874 ans = None
874 875 eofs, max_eofs = 0, 20
875 876 while ans not in answers.keys():
876 877 try:
877 878 ans = raw_input(prompt+' ').lower()
878 879 if not ans: # response was an empty string
879 880 ans = default
880 881 eofs = 0
881 882 except (EOFError,KeyboardInterrupt):
882 883 eofs = eofs + 1
883 884 if eofs >= max_eofs:
884 885 if default in answers.keys():
885 886 ans = default
886 887 else:
887 888 raise
888 889
889 890 return answers[ans]
890 891
891 892 #----------------------------------------------------------------------------
892 893 class EvalDict:
893 894 """
894 895 Emulate a dict which evaluates its contents in the caller's frame.
895 896
896 897 Usage:
897 898 >>>number = 19
898 899 >>>text = "python"
899 900 >>>print "%(text.capitalize())s %(number/9.0).1f rules!" % EvalDict()
900 901 """
901 902
902 903 # This version is due to sismex01@hebmex.com on c.l.py, and is basically a
903 904 # modified (shorter) version of:
904 905 # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66018 by
905 906 # Skip Montanaro (skip@pobox.com).
906 907
907 908 def __getitem__(self, name):
908 909 frame = sys._getframe(1)
909 910 return eval(name, frame.f_globals, frame.f_locals)
910 911
911 912 EvalString = EvalDict # for backwards compatibility
912 913 #----------------------------------------------------------------------------
913 914 def qw(words,flat=0,sep=None,maxsplit=-1):
914 915 """Similar to Perl's qw() operator, but with some more options.
915 916
916 917 qw(words,flat=0,sep=' ',maxsplit=-1) -> words.split(sep,maxsplit)
917 918
918 919 words can also be a list itself, and with flat=1, the output will be
919 920 recursively flattened. Examples:
920 921
921 922 >>> qw('1 2')
922 923 ['1', '2']
923 924 >>> qw(['a b','1 2',['m n','p q']])
924 925 [['a', 'b'], ['1', '2'], [['m', 'n'], ['p', 'q']]]
925 926 >>> qw(['a b','1 2',['m n','p q']],flat=1)
926 927 ['a', 'b', '1', '2', 'm', 'n', 'p', 'q'] """
927 928
928 929 if type(words) in StringTypes:
929 930 return [word.strip() for word in words.split(sep,maxsplit)
930 931 if word and not word.isspace() ]
931 932 if flat:
932 933 return flatten(map(qw,words,[1]*len(words)))
933 934 return map(qw,words)
934 935
935 936 #----------------------------------------------------------------------------
936 937 def qwflat(words,sep=None,maxsplit=-1):
937 938 """Calls qw(words) in flat mode. It's just a convenient shorthand."""
938 939 return qw(words,1,sep,maxsplit)
939 940
940 941 #-----------------------------------------------------------------------------
941 942 def list_strings(arg):
942 943 """Always return a list of strings, given a string or list of strings
943 944 as input."""
944 945
945 946 if type(arg) in StringTypes: return [arg]
946 947 else: return arg
947 948
948 949 #----------------------------------------------------------------------------
949 950 def grep(pat,list,case=1):
950 951 """Simple minded grep-like function.
951 952 grep(pat,list) returns occurrences of pat in list, None on failure.
952 953
953 954 It only does simple string matching, with no support for regexps. Use the
954 955 option case=0 for case-insensitive matching."""
955 956
956 957 # This is pretty crude. At least it should implement copying only references
957 958 # to the original data in case it's big. Now it copies the data for output.
958 959 out=[]
959 960 if case:
960 961 for term in list:
961 962 if term.find(pat)>-1: out.append(term)
962 963 else:
963 964 lpat=pat.lower()
964 965 for term in list:
965 966 if term.lower().find(lpat)>-1: out.append(term)
966 967
967 968 if len(out): return out
968 969 else: return None
969 970
970 971 #----------------------------------------------------------------------------
971 972 def dgrep(pat,*opts):
972 973 """Return grep() on dir()+dir(__builtins__).
973 974
974 975 A very common use of grep() when working interactively."""
975 976
976 977 return grep(pat,dir(__main__)+dir(__main__.__builtins__),*opts)
977 978
978 979 #----------------------------------------------------------------------------
979 980 def idgrep(pat):
980 981 """Case-insensitive dgrep()"""
981 982
982 983 return dgrep(pat,0)
983 984
984 985 #----------------------------------------------------------------------------
985 986 def igrep(pat,list):
986 987 """Synonym for case-insensitive grep."""
987 988
988 989 return grep(pat,list,case=0)
989 990
990 991 #----------------------------------------------------------------------------
991 992 def indent(str,nspaces=4,ntabs=0):
992 993 """Indent a string a given number of spaces or tabstops.
993 994
994 995 indent(str,nspaces=4,ntabs=0) -> indent str by ntabs+nspaces.
995 996 """
996 997 if str is None:
997 998 return
998 999 ind = '\t'*ntabs+' '*nspaces
999 1000 outstr = '%s%s' % (ind,str.replace(os.linesep,os.linesep+ind))
1000 1001 if outstr.endswith(os.linesep+ind):
1001 1002 return outstr[:-len(ind)]
1002 1003 else:
1003 1004 return outstr
1004 1005
1005 1006 #-----------------------------------------------------------------------------
1006 1007 def native_line_ends(filename,backup=1):
1007 1008 """Convert (in-place) a file to line-ends native to the current OS.
1008 1009
1009 1010 If the optional backup argument is given as false, no backup of the
1010 1011 original file is left. """
1011 1012
1012 1013 backup_suffixes = {'posix':'~','dos':'.bak','nt':'.bak','mac':'.bak'}
1013 1014
1014 1015 bak_filename = filename + backup_suffixes[os.name]
1015 1016
1016 1017 original = open(filename).read()
1017 1018 shutil.copy2(filename,bak_filename)
1018 1019 try:
1019 1020 new = open(filename,'wb')
1020 1021 new.write(os.linesep.join(original.splitlines()))
1021 1022 new.write(os.linesep) # ALWAYS put an eol at the end of the file
1022 1023 new.close()
1023 1024 except:
1024 1025 os.rename(bak_filename,filename)
1025 1026 if not backup:
1026 1027 try:
1027 1028 os.remove(bak_filename)
1028 1029 except:
1029 1030 pass
1030 1031
1031 1032 #----------------------------------------------------------------------------
1032 1033 def get_pager_cmd(pager_cmd = None):
1033 1034 """Return a pager command.
1034 1035
1035 1036 Makes some attempts at finding an OS-correct one."""
1036 1037
1037 1038 if os.name == 'posix':
1038 1039 default_pager_cmd = 'less -r' # -r for color control sequences
1039 1040 elif os.name in ['nt','dos']:
1040 1041 default_pager_cmd = 'type'
1041 1042
1042 1043 if pager_cmd is None:
1043 1044 try:
1044 1045 pager_cmd = os.environ['PAGER']
1045 1046 except:
1046 1047 pager_cmd = default_pager_cmd
1047 1048 return pager_cmd
1048 1049
1049 1050 #-----------------------------------------------------------------------------
1050 1051 def get_pager_start(pager,start):
1051 1052 """Return the string for paging files with an offset.
1052 1053
1053 1054 This is the '+N' argument which less and more (under Unix) accept.
1054 1055 """
1055 1056
1056 1057 if pager in ['less','more']:
1057 1058 if start:
1058 1059 start_string = '+' + str(start)
1059 1060 else:
1060 1061 start_string = ''
1061 1062 else:
1062 1063 start_string = ''
1063 1064 return start_string
1064 1065
1065 1066 #----------------------------------------------------------------------------
1066 1067 def page_dumb(strng,start=0,screen_lines=25):
1067 1068 """Very dumb 'pager' in Python, for when nothing else works.
1068 1069
1069 1070 Only moves forward, same interface as page(), except for pager_cmd and
1070 1071 mode."""
1071 1072
1072 1073 out_ln = strng.splitlines()[start:]
1073 1074 screens = chop(out_ln,screen_lines-1)
1074 1075 if len(screens) == 1:
1075 1076 print >>Term.cout, os.linesep.join(screens[0])
1076 1077 else:
1077 1078 for scr in screens[0:-1]:
1078 1079 print >>Term.cout, os.linesep.join(scr)
1079 1080 ans = raw_input('---Return to continue, q to quit--- ')
1080 1081 if ans.lower().startswith('q'):
1081 1082 return
1082 1083 print >>Term.cout, os.linesep.join(screens[-1])
1083 1084
1084 1085 #----------------------------------------------------------------------------
1085 1086 def page(strng,start=0,screen_lines=0,pager_cmd = None):
1086 1087 """Print a string, piping through a pager after a certain length.
1087 1088
1088 1089 The screen_lines parameter specifies the number of *usable* lines of your
1089 1090 terminal screen (total lines minus lines you need to reserve to show other
1090 1091 information).
1091 1092
1092 1093 If you set screen_lines to a number <=0, page() will try to auto-determine
1093 1094 your screen size and will only use up to (screen_size+screen_lines) for
1094 1095 printing, paging after that. That is, if you want auto-detection but need
1095 1096 to reserve the bottom 3 lines of the screen, use screen_lines = -3, and for
1096 1097 auto-detection without any lines reserved simply use screen_lines = 0.
1097 1098
1098 1099 If a string won't fit in the allowed lines, it is sent through the
1099 1100 specified pager command. If none given, look for PAGER in the environment,
1100 1101 and ultimately default to less.
1101 1102
1102 1103 If no system pager works, the string is sent through a 'dumb pager'
1103 1104 written in python, very simplistic.
1104 1105 """
1105 1106
1106 1107 # Ugly kludge, but calling curses.initscr() flat out crashes in emacs
1107 1108 TERM = os.environ.get('TERM','dumb')
1108 1109 if TERM in ['dumb','emacs'] and os.name != 'nt':
1109 1110 print strng
1110 1111 return
1111 1112 # chop off the topmost part of the string we don't want to see
1112 1113 str_lines = strng.split(os.linesep)[start:]
1113 1114 str_toprint = os.linesep.join(str_lines)
1114 1115 num_newlines = len(str_lines)
1115 1116 len_str = len(str_toprint)
1116 1117
1117 1118 # Dumb heuristics to guesstimate number of on-screen lines the string
1118 1119 # takes. Very basic, but good enough for docstrings in reasonable
1119 1120 # terminals. If someone later feels like refining it, it's not hard.
1120 1121 numlines = max(num_newlines,int(len_str/80)+1)
1121 1122
1122 1123 screen_lines_def = 25 # default value if we can't auto-determine
1123 1124
1124 1125 # auto-determine screen size
1125 1126 if screen_lines <= 0:
1126 1127 if TERM=='xterm':
1127 1128 try:
1128 1129 import curses
1129 1130 if hasattr(curses,'initscr'):
1130 1131 use_curses = 1
1131 1132 else:
1132 1133 use_curses = 0
1133 1134 except ImportError:
1134 1135 use_curses = 0
1135 1136 else:
1136 1137 # curses causes problems on many terminals other than xterm.
1137 1138 use_curses = 0
1138 1139 if use_curses:
1139 1140 scr = curses.initscr()
1140 1141 screen_lines_real,screen_cols = scr.getmaxyx()
1141 1142 curses.endwin()
1142 1143 screen_lines += screen_lines_real
1143 1144 #print '***Screen size:',screen_lines_real,'lines x',\
1144 1145 #screen_cols,'columns.' # dbg
1145 1146 else:
1146 1147 screen_lines += screen_lines_def
1147 1148
1148 1149 #print 'numlines',numlines,'screenlines',screen_lines # dbg
1149 1150 if numlines <= screen_lines :
1150 1151 #print '*** normal print' # dbg
1151 1152 print >>Term.cout, str_toprint
1152 1153 else:
1153 1154 # Try to open pager and default to internal one if that fails.
1154 1155 # All failure modes are tagged as 'retval=1', to match the return
1155 1156 # value of a failed system command. If any intermediate attempt
1156 1157 # sets retval to 1, at the end we resort to our own page_dumb() pager.
1157 1158 pager_cmd = get_pager_cmd(pager_cmd)
1158 1159 pager_cmd += ' ' + get_pager_start(pager_cmd,start)
1159 1160 if os.name == 'nt':
1160 1161 if pager_cmd.startswith('type'):
1161 1162 # The default WinXP 'type' command is failing on complex strings.
1162 1163 retval = 1
1163 1164 else:
1164 1165 tmpname = tempfile.mktemp('.txt')
1165 1166 tmpfile = file(tmpname,'wt')
1166 1167 tmpfile.write(strng)
1167 1168 tmpfile.close()
1168 1169 cmd = "%s < %s" % (pager_cmd,tmpname)
1169 1170 if os.system(cmd):
1170 1171 retval = 1
1171 1172 else:
1172 1173 retval = None
1173 1174 os.remove(tmpname)
1174 1175 else:
1175 1176 try:
1176 1177 retval = None
1177 1178 # if I use popen4, things hang. No idea why.
1178 1179 #pager,shell_out = os.popen4(pager_cmd)
1179 1180 pager = os.popen(pager_cmd,'w')
1180 1181 pager.write(strng)
1181 1182 pager.close()
1182 1183 retval = pager.close() # success returns None
1183 1184 except IOError,msg: # broken pipe when user quits
1184 1185 if msg.args == (32,'Broken pipe'):
1185 1186 retval = None
1186 1187 else:
1187 1188 retval = 1
1188 1189 except OSError:
1189 1190 # Other strange problems, sometimes seen in Win2k/cygwin
1190 1191 retval = 1
1191 1192 if retval is not None:
1192 1193 page_dumb(strng,screen_lines=screen_lines)
1193 1194
1194 1195 #----------------------------------------------------------------------------
1195 1196 def page_file(fname,start = 0, pager_cmd = None):
1196 1197 """Page a file, using an optional pager command and starting line.
1197 1198 """
1198 1199
1199 1200 pager_cmd = get_pager_cmd(pager_cmd)
1200 1201 pager_cmd += ' ' + get_pager_start(pager_cmd,start)
1201 1202
1202 1203 try:
1203 1204 if os.environ['TERM'] in ['emacs','dumb']:
1204 1205 raise EnvironmentError
1205 1206 xsys(pager_cmd + ' ' + fname)
1206 1207 except:
1207 1208 try:
1208 1209 if start > 0:
1209 1210 start -= 1
1210 1211 page(open(fname).read(),start)
1211 1212 except:
1212 1213 print 'Unable to show file',`fname`
1213 1214
1214 1215 #----------------------------------------------------------------------------
1215 1216 def snip_print(str,width = 75,print_full = 0,header = ''):
1216 1217 """Print a string snipping the midsection to fit in width.
1217 1218
1218 1219 print_full: mode control:
1219 1220 - 0: only snip long strings
1220 1221 - 1: send to page() directly.
1221 1222 - 2: snip long strings and ask for full length viewing with page()
1222 1223 Return 1 if snipping was necessary, 0 otherwise."""
1223 1224
1224 1225 if print_full == 1:
1225 1226 page(header+str)
1226 1227 return 0
1227 1228
1228 1229 print header,
1229 1230 if len(str) < width:
1230 1231 print str
1231 1232 snip = 0
1232 1233 else:
1233 1234 whalf = int((width -5)/2)
1234 1235 print str[:whalf] + ' <...> ' + str[-whalf:]
1235 1236 snip = 1
1236 1237 if snip and print_full == 2:
1237 1238 if raw_input(header+' Snipped. View (y/n)? [N]').lower() == 'y':
1238 1239 page(str)
1239 1240 return snip
1240 1241
1241 1242 #****************************************************************************
1242 1243 # lists, dicts and structures
1243 1244
1244 1245 def belong(candidates,checklist):
1245 1246 """Check whether a list of items appear in a given list of options.
1246 1247
1247 1248 Returns a list of 1 and 0, one for each candidate given."""
1248 1249
1249 1250 return [x in checklist for x in candidates]
1250 1251
1251 1252 #----------------------------------------------------------------------------
1252 1253 def uniq_stable(elems):
1253 1254 """uniq_stable(elems) -> list
1254 1255
1255 1256 Return from an iterable, a list of all the unique elements in the input,
1256 1257 but maintaining the order in which they first appear.
1257 1258
1258 1259 A naive solution to this problem which just makes a dictionary with the
1259 1260 elements as keys fails to respect the stability condition, since
1260 1261 dictionaries are unsorted by nature.
1261 1262
1262 1263 Note: All elements in the input must be valid dictionary keys for this
1263 1264 routine to work, as it internally uses a dictionary for efficiency
1264 1265 reasons."""
1265 1266
1266 1267 unique = []
1267 1268 unique_dict = {}
1268 1269 for nn in elems:
1269 1270 if nn not in unique_dict:
1270 1271 unique.append(nn)
1271 1272 unique_dict[nn] = None
1272 1273 return unique
1273 1274
1274 1275 #----------------------------------------------------------------------------
1275 1276 class NLprinter:
1276 1277 """Print an arbitrarily nested list, indicating index numbers.
1277 1278
1278 1279 An instance of this class called nlprint is available and callable as a
1279 1280 function.
1280 1281
1281 1282 nlprint(list,indent=' ',sep=': ') -> prints indenting each level by 'indent'
1282 1283 and using 'sep' to separate the index from the value. """
1283 1284
1284 1285 def __init__(self):
1285 1286 self.depth = 0
1286 1287
1287 1288 def __call__(self,lst,pos='',**kw):
1288 1289 """Prints the nested list numbering levels."""
1289 1290 kw.setdefault('indent',' ')
1290 1291 kw.setdefault('sep',': ')
1291 1292 kw.setdefault('start',0)
1292 1293 kw.setdefault('stop',len(lst))
1293 1294 # we need to remove start and stop from kw so they don't propagate
1294 1295 # into a recursive call for a nested list.
1295 1296 start = kw['start']; del kw['start']
1296 1297 stop = kw['stop']; del kw['stop']
1297 1298 if self.depth == 0 and 'header' in kw.keys():
1298 1299 print kw['header']
1299 1300
1300 1301 for idx in range(start,stop):
1301 1302 elem = lst[idx]
1302 1303 if type(elem)==type([]):
1303 1304 self.depth += 1
1304 1305 self.__call__(elem,itpl('$pos$idx,'),**kw)
1305 1306 self.depth -= 1
1306 1307 else:
1307 1308 printpl(kw['indent']*self.depth+'$pos$idx$kw["sep"]$elem')
1308 1309
1309 1310 nlprint = NLprinter()
1310 1311 #----------------------------------------------------------------------------
1311 1312 def all_belong(candidates,checklist):
1312 1313 """Check whether a list of items ALL appear in a given list of options.
1313 1314
1314 1315 Returns a single 1 or 0 value."""
1315 1316
1316 1317 return 1-(0 in [x in checklist for x in candidates])
1317 1318
1318 1319 #----------------------------------------------------------------------------
1319 1320 def sort_compare(lst1,lst2,inplace = 1):
1320 1321 """Sort and compare two lists.
1321 1322
1322 1323 By default it does it in place, thus modifying the lists. Use inplace = 0
1323 1324 to avoid that (at the cost of temporary copy creation)."""
1324 1325 if not inplace:
1325 1326 lst1 = lst1[:]
1326 1327 lst2 = lst2[:]
1327 1328 lst1.sort(); lst2.sort()
1328 1329 return lst1 == lst2
1329 1330
1330 1331 #----------------------------------------------------------------------------
1331 1332 def mkdict(**kwargs):
1332 1333 """Return a dict from a keyword list.
1333 1334
1334 1335 It's just syntactic sugar for making ditcionary creation more convenient:
1335 1336 # the standard way
1336 1337 >>>data = { 'red' : 1, 'green' : 2, 'blue' : 3 }
1337 1338 # a cleaner way
1338 1339 >>>data = dict(red=1, green=2, blue=3)
1339 1340
1340 1341 If you need more than this, look at the Struct() class."""
1341 1342
1342 1343 return kwargs
1343 1344
1344 1345 #----------------------------------------------------------------------------
1345 1346 def list2dict(lst):
1346 1347 """Takes a list of (key,value) pairs and turns it into a dict."""
1347 1348
1348 1349 dic = {}
1349 1350 for k,v in lst: dic[k] = v
1350 1351 return dic
1351 1352
1352 1353 #----------------------------------------------------------------------------
1353 1354 def list2dict2(lst,default=''):
1354 1355 """Takes a list and turns it into a dict.
1355 1356 Much slower than list2dict, but more versatile. This version can take
1356 1357 lists with sublists of arbitrary length (including sclars)."""
1357 1358
1358 1359 dic = {}
1359 1360 for elem in lst:
1360 1361 if type(elem) in (types.ListType,types.TupleType):
1361 1362 size = len(elem)
1362 1363 if size == 0:
1363 1364 pass
1364 1365 elif size == 1:
1365 1366 dic[elem] = default
1366 1367 else:
1367 1368 k,v = elem[0], elem[1:]
1368 1369 if len(v) == 1: v = v[0]
1369 1370 dic[k] = v
1370 1371 else:
1371 1372 dic[elem] = default
1372 1373 return dic
1373 1374
1374 1375 #----------------------------------------------------------------------------
1375 1376 def flatten(seq):
1376 1377 """Flatten a list of lists (NOT recursive, only works for 2d lists)."""
1377 1378
1378 1379 # bug in python??? (YES. Fixed in 2.2, let's leave the kludgy fix in).
1379 1380
1380 1381 # if the x=0 isn't made, a *global* variable x is left over after calling
1381 1382 # this function, with the value of the last element in the return
1382 1383 # list. This does seem like a bug big time to me.
1383 1384
1384 1385 # the problem is fixed with the x=0, which seems to force the creation of
1385 1386 # a local name
1386 1387
1387 1388 x = 0
1388 1389 return [x for subseq in seq for x in subseq]
1389 1390
1390 1391 #----------------------------------------------------------------------------
1391 1392 def get_slice(seq,start=0,stop=None,step=1):
1392 1393 """Get a slice of a sequence with variable step. Specify start,stop,step."""
1393 1394 if stop == None:
1394 1395 stop = len(seq)
1395 1396 item = lambda i: seq[i]
1396 1397 return map(item,xrange(start,stop,step))
1397 1398
1398 1399 #----------------------------------------------------------------------------
1399 1400 def chop(seq,size):
1400 1401 """Chop a sequence into chunks of the given size."""
1401 1402 chunk = lambda i: seq[i:i+size]
1402 1403 return map(chunk,xrange(0,len(seq),size))
1403 1404
1404 1405 #----------------------------------------------------------------------------
1405 1406 def with(object, **args):
1406 1407 """Set multiple attributes for an object, similar to Pascal's with.
1407 1408
1408 1409 Example:
1409 1410 with(jim,
1410 1411 born = 1960,
1411 1412 haircolour = 'Brown',
1412 1413 eyecolour = 'Green')
1413 1414
1414 1415 Credit: Greg Ewing, in
1415 1416 http://mail.python.org/pipermail/python-list/2001-May/040703.html"""
1416 1417
1417 1418 object.__dict__.update(args)
1418 1419
1419 1420 #----------------------------------------------------------------------------
1420 1421 def setattr_list(obj,alist,nspace = None):
1421 1422 """Set a list of attributes for an object taken from a namespace.
1422 1423
1423 1424 setattr_list(obj,alist,nspace) -> sets in obj all the attributes listed in
1424 1425 alist with their values taken from nspace, which must be a dict (something
1425 1426 like locals() will often do) If nspace isn't given, locals() of the
1426 1427 *caller* is used, so in most cases you can omit it.
1427 1428
1428 1429 Note that alist can be given as a string, which will be automatically
1429 1430 split into a list on whitespace. If given as a list, it must be a list of
1430 1431 *strings* (the variable names themselves), not of variables."""
1431 1432
1432 1433 # this grabs the local variables from the *previous* call frame -- that is
1433 1434 # the locals from the function that called setattr_list().
1434 1435 # - snipped from weave.inline()
1435 1436 if nspace is None:
1436 1437 call_frame = sys._getframe().f_back
1437 1438 nspace = call_frame.f_locals
1438 1439
1439 1440 if type(alist) in StringTypes:
1440 1441 alist = alist.split()
1441 1442 for attr in alist:
1442 1443 val = eval(attr,nspace)
1443 1444 setattr(obj,attr,val)
1444 1445
1445 1446 #----------------------------------------------------------------------------
1446 1447 def getattr_list(obj,alist,*args):
1447 1448 """getattr_list(obj,alist[, default]) -> attribute list.
1448 1449
1449 1450 Get a list of named attributes for an object. When a default argument is
1450 1451 given, it is returned when the attribute doesn't exist; without it, an
1451 1452 exception is raised in that case.
1452 1453
1453 1454 Note that alist can be given as a string, which will be automatically
1454 1455 split into a list on whitespace. If given as a list, it must be a list of
1455 1456 *strings* (the variable names themselves), not of variables."""
1456 1457
1457 1458 if type(alist) in StringTypes:
1458 1459 alist = alist.split()
1459 1460 if args:
1460 1461 if len(args)==1:
1461 1462 default = args[0]
1462 1463 return map(lambda attr: getattr(obj,attr,default),alist)
1463 1464 else:
1464 1465 raise ValueError,'getattr_list() takes only one optional argument'
1465 1466 else:
1466 1467 return map(lambda attr: getattr(obj,attr),alist)
1467 1468
1468 1469 #----------------------------------------------------------------------------
1469 1470 def map_method(method,object_list,*argseq,**kw):
1470 1471 """map_method(method,object_list,*args,**kw) -> list
1471 1472
1472 1473 Return a list of the results of applying the methods to the items of the
1473 1474 argument sequence(s). If more than one sequence is given, the method is
1474 1475 called with an argument list consisting of the corresponding item of each
1475 1476 sequence. All sequences must be of the same length.
1476 1477
1477 1478 Keyword arguments are passed verbatim to all objects called.
1478 1479
1479 1480 This is Python code, so it's not nearly as fast as the builtin map()."""
1480 1481
1481 1482 out_list = []
1482 1483 idx = 0
1483 1484 for object in object_list:
1484 1485 try:
1485 1486 handler = getattr(object, method)
1486 1487 except AttributeError:
1487 1488 out_list.append(None)
1488 1489 else:
1489 1490 if argseq:
1490 1491 args = map(lambda lst:lst[idx],argseq)
1491 1492 #print 'ob',object,'hand',handler,'ar',args # dbg
1492 1493 out_list.append(handler(args,**kw))
1493 1494 else:
1494 1495 out_list.append(handler(**kw))
1495 1496 idx += 1
1496 1497 return out_list
1497 1498
1498 1499 #----------------------------------------------------------------------------
1499 1500 # Proposed popitem() extension, written as a method
1500 1501
1501 1502 class NotGiven: pass
1502 1503
1503 1504 def popkey(dct,key,default=NotGiven):
1504 1505 """Return dct[key] and delete dct[key].
1505 1506
1506 1507 If default is given, return it if dct[key] doesn't exist, otherwise raise
1507 1508 KeyError. """
1508 1509
1509 1510 try:
1510 1511 val = dct[key]
1511 1512 except KeyError:
1512 1513 if default is NotGiven:
1513 1514 raise
1514 1515 else:
1515 1516 return default
1516 1517 else:
1517 1518 del dct[key]
1518 1519 return val
1519 1520 #*************************** end of file <genutils.py> **********************
1520 1521
@@ -1,1999 +1,2004 b''
1 1 # -*- coding: utf-8 -*-
2 2 """
3 3 IPython -- An enhanced Interactive Python
4 4
5 5 Requires Python 2.1 or newer.
6 6
7 7 This file contains all the classes and helper functions specific to IPython.
8 8
9 $Id: iplib.py 638 2005-07-18 03:01:41Z fperez $
9 $Id: iplib.py 703 2005-08-16 17:34:44Z fperez $
10 10 """
11 11
12 12 #*****************************************************************************
13 13 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
14 14 # Copyright (C) 2001-2004 Fernando Perez. <fperez@colorado.edu>
15 15 #
16 16 # Distributed under the terms of the BSD License. The full license is in
17 17 # the file COPYING, distributed as part of this software.
18 18 #
19 19 # Note: this code originally subclassed code.InteractiveConsole from the
20 20 # Python standard library. Over time, much of that class has been copied
21 21 # verbatim here for modifications which could not be accomplished by
22 22 # subclassing. The Python License (sec. 2) allows for this, but it's always
23 23 # nice to acknowledge credit where credit is due.
24 24 #*****************************************************************************
25 25
26 26 #****************************************************************************
27 27 # Modules and globals
28 28
29 29 from __future__ import generators # for 2.2 backwards-compatibility
30 30
31 31 from IPython import Release
32 32 __author__ = '%s <%s>\n%s <%s>' % \
33 33 ( Release.authors['Janko'] + Release.authors['Fernando'] )
34 34 __license__ = Release.license
35 35 __version__ = Release.version
36 36
37 37 # Python standard modules
38 38 import __main__
39 39 import __builtin__
40 40 import exceptions
41 41 import keyword
42 42 import new
43 43 import os, sys, shutil
44 44 import code, glob, types, re
45 45 import string, StringIO
46 46 import inspect, pydoc
47 47 import bdb, pdb
48 48 import UserList # don't subclass list so this works with Python2.1
49 49 from pprint import pprint, pformat
50 50 import cPickle as pickle
51 51 import traceback
52 52
53 53 # IPython's own modules
54 54 import IPython
55 55 from IPython import OInspect,PyColorize,ultraTB
56 56 from IPython.ultraTB import ColorScheme,ColorSchemeTable # too long names
57 57 from IPython.Logger import Logger
58 58 from IPython.Magic import Magic,magic2python,shlex_split
59 59 from IPython.usage import cmd_line_usage,interactive_usage
60 60 from IPython.Struct import Struct
61 61 from IPython.Itpl import Itpl,itpl,printpl,ItplNS,itplns
62 62 from IPython.FakeModule import FakeModule
63 63 from IPython.background_jobs import BackgroundJobManager
64 64 from IPython.genutils import *
65 65
66 66 # Global pointer to the running
67 67
68 68 # store the builtin raw_input globally, and use this always, in case user code
69 69 # overwrites it (like wx.py.PyShell does)
70 70 raw_input_original = raw_input
71 71
72 72 #****************************************************************************
73 73 # Some utility function definitions
74 74
75 75 class Bunch: pass
76 76
77 77 def esc_quotes(strng):
78 78 """Return the input string with single and double quotes escaped out"""
79 79
80 80 return strng.replace('"','\\"').replace("'","\\'")
81 81
82 82 def import_fail_info(mod_name,fns=None):
83 83 """Inform load failure for a module."""
84 84
85 85 if fns == None:
86 86 warn("Loading of %s failed.\n" % (mod_name,))
87 87 else:
88 88 warn("Loading of %s from %s failed.\n" % (fns,mod_name))
89 89
90 90 def qw_lol(indata):
91 91 """qw_lol('a b') -> [['a','b']],
92 92 otherwise it's just a call to qw().
93 93
94 94 We need this to make sure the modules_some keys *always* end up as a
95 95 list of lists."""
96 96
97 97 if type(indata) in StringTypes:
98 98 return [qw(indata)]
99 99 else:
100 100 return qw(indata)
101 101
102 102 def ipmagic(arg_s):
103 103 """Call a magic function by name.
104 104
105 105 Input: a string containing the name of the magic function to call and any
106 106 additional arguments to be passed to the magic.
107 107
108 108 ipmagic('name -opt foo bar') is equivalent to typing at the ipython
109 109 prompt:
110 110
111 111 In[1]: %name -opt foo bar
112 112
113 113 To call a magic without arguments, simply use ipmagic('name').
114 114
115 115 This provides a proper Python function to call IPython's magics in any
116 116 valid Python code you can type at the interpreter, including loops and
117 117 compound statements. It is added by IPython to the Python builtin
118 118 namespace upon initialization."""
119 119
120 120 args = arg_s.split(' ',1)
121 121 magic_name = args[0]
122 122 if magic_name.startswith(__IPYTHON__.ESC_MAGIC):
123 123 magic_name = magic_name[1:]
124 124 try:
125 125 magic_args = args[1]
126 126 except IndexError:
127 127 magic_args = ''
128 128 fn = getattr(__IPYTHON__,'magic_'+magic_name,None)
129 129 if fn is None:
130 130 error("Magic function `%s` not found." % magic_name)
131 131 else:
132 132 magic_args = __IPYTHON__.var_expand(magic_args)
133 133 return fn(magic_args)
134 134
135 135 def ipalias(arg_s):
136 136 """Call an alias by name.
137 137
138 138 Input: a string containing the name of the alias to call and any
139 139 additional arguments to be passed to the magic.
140 140
141 141 ipalias('name -opt foo bar') is equivalent to typing at the ipython
142 142 prompt:
143 143
144 144 In[1]: name -opt foo bar
145 145
146 146 To call an alias without arguments, simply use ipalias('name').
147 147
148 148 This provides a proper Python function to call IPython's aliases in any
149 149 valid Python code you can type at the interpreter, including loops and
150 150 compound statements. It is added by IPython to the Python builtin
151 151 namespace upon initialization."""
152 152
153 153 args = arg_s.split(' ',1)
154 154 alias_name = args[0]
155 155 try:
156 156 alias_args = args[1]
157 157 except IndexError:
158 158 alias_args = ''
159 159 if alias_name in __IPYTHON__.alias_table:
160 160 __IPYTHON__.call_alias(alias_name,alias_args)
161 161 else:
162 162 error("Alias `%s` not found." % alias_name)
163 163
164 164 #-----------------------------------------------------------------------------
165 165 # Local use classes
166 166 try:
167 167 from IPython import FlexCompleter
168 168
169 169 class MagicCompleter(FlexCompleter.Completer):
170 170 """Extension of the completer class to work on %-prefixed lines."""
171 171
172 172 def __init__(self,shell,namespace=None,omit__names=0,alias_table=None):
173 173 """MagicCompleter() -> completer
174 174
175 175 Return a completer object suitable for use by the readline library
176 176 via readline.set_completer().
177 177
178 178 Inputs:
179 179
180 180 - shell: a pointer to the ipython shell itself. This is needed
181 181 because this completer knows about magic functions, and those can
182 182 only be accessed via the ipython instance.
183 183
184 184 - namespace: an optional dict where completions are performed.
185 185
186 186 - The optional omit__names parameter sets the completer to omit the
187 187 'magic' names (__magicname__) for python objects unless the text
188 188 to be completed explicitly starts with one or more underscores.
189 189
190 190 - If alias_table is supplied, it should be a dictionary of aliases
191 191 to complete. """
192 192
193 193 FlexCompleter.Completer.__init__(self,namespace)
194 194 self.magic_prefix = shell.name+'.magic_'
195 195 self.magic_escape = shell.ESC_MAGIC
196 196 self.readline = FlexCompleter.readline
197 197 delims = self.readline.get_completer_delims()
198 198 delims = delims.replace(self.magic_escape,'')
199 199 self.readline.set_completer_delims(delims)
200 200 self.get_line_buffer = self.readline.get_line_buffer
201 201 self.omit__names = omit__names
202 202 self.merge_completions = shell.rc.readline_merge_completions
203 203
204 204 if alias_table is None:
205 205 alias_table = {}
206 206 self.alias_table = alias_table
207 207 # Regexp to split filenames with spaces in them
208 208 self.space_name_re = re.compile(r'([^\\] )')
209 209 # Hold a local ref. to glob.glob for speed
210 210 self.glob = glob.glob
211 211 # Special handling of backslashes needed in win32 platforms
212 212 if sys.platform == "win32":
213 213 self.clean_glob = self._clean_glob_win32
214 214 else:
215 215 self.clean_glob = self._clean_glob
216 216 self.matchers = [self.python_matches,
217 217 self.file_matches,
218 218 self.alias_matches,
219 219 self.python_func_kw_matches]
220 220
221 221 # Code contributed by Alex Schmolck, for ipython/emacs integration
222 222 def all_completions(self, text):
223 223 """Return all possible completions for the benefit of emacs."""
224 224
225 225 completions = []
226 226 try:
227 227 for i in xrange(sys.maxint):
228 228 res = self.complete(text, i)
229 229
230 230 if not res: break
231 231
232 232 completions.append(res)
233 233 #XXX workaround for ``notDefined.<tab>``
234 234 except NameError:
235 235 pass
236 236 return completions
237 237 # /end Alex Schmolck code.
238 238
239 239 def _clean_glob(self,text):
240 240 return self.glob("%s*" % text)
241 241
242 242 def _clean_glob_win32(self,text):
243 243 return [f.replace("\\","/")
244 244 for f in self.glob("%s*" % text)]
245 245
246 246 def file_matches(self, text):
247 247 """Match filneames, expanding ~USER type strings.
248 248
249 249 Most of the seemingly convoluted logic in this completer is an
250 250 attempt to handle filenames with spaces in them. And yet it's not
251 251 quite perfect, because Python's readline doesn't expose all of the
252 252 GNU readline details needed for this to be done correctly.
253 253
254 254 For a filename with a space in it, the printed completions will be
255 255 only the parts after what's already been typed (instead of the
256 256 full completions, as is normally done). I don't think with the
257 257 current (as of Python 2.3) Python readline it's possible to do
258 258 better."""
259 259
260 260 #print 'Completer->file_matches: <%s>' % text # dbg
261 261
262 262 # chars that require escaping with backslash - i.e. chars
263 263 # that readline treats incorrectly as delimiters, but we
264 264 # don't want to treat as delimiters in filename matching
265 265 # when escaped with backslash
266 266
267 267 protectables = ' ()[]{}'
268 268
269 269 def protect_filename(s):
270 270 return "".join([(ch in protectables and '\\' + ch or ch)
271 271 for ch in s])
272 272
273 273 lbuf = self.get_line_buffer()[:self.readline.get_endidx()]
274 274 open_quotes = 0 # track strings with open quotes
275 275 try:
276 276 lsplit = shlex_split(lbuf)[-1]
277 277 except ValueError:
278 278 # typically an unmatched ", or backslash without escaped char.
279 279 if lbuf.count('"')==1:
280 280 open_quotes = 1
281 281 lsplit = lbuf.split('"')[-1]
282 282 elif lbuf.count("'")==1:
283 283 open_quotes = 1
284 284 lsplit = lbuf.split("'")[-1]
285 285 else:
286 286 return None
287 287 except IndexError:
288 288 # tab pressed on empty line
289 289 lsplit = ""
290 290
291 291 if lsplit != protect_filename(lsplit):
292 292 # if protectables are found, do matching on the whole escaped
293 293 # name
294 294 has_protectables = 1
295 295 text0,text = text,lsplit
296 296 else:
297 297 has_protectables = 0
298 298 text = os.path.expanduser(text)
299 299
300 300 if text == "":
301 301 return [protect_filename(f) for f in self.glob("*")]
302 302
303 303 m0 = self.clean_glob(text.replace('\\',''))
304 304 if has_protectables:
305 305 # If we had protectables, we need to revert our changes to the
306 306 # beginning of filename so that we don't double-write the part
307 307 # of the filename we have so far
308 308 len_lsplit = len(lsplit)
309 309 matches = [text0 + protect_filename(f[len_lsplit:]) for f in m0]
310 310 else:
311 311 if open_quotes:
312 312 # if we have a string with an open quote, we don't need to
313 313 # protect the names at all (and we _shouldn't_, as it
314 314 # would cause bugs when the filesystem call is made).
315 315 matches = m0
316 316 else:
317 317 matches = [protect_filename(f) for f in m0]
318 318 if len(matches) == 1 and os.path.isdir(matches[0]):
319 319 # Takes care of links to directories also. Use '/'
320 320 # explicitly, even under Windows, so that name completions
321 321 # don't end up escaped.
322 322 matches[0] += '/'
323 323 return matches
324 324
325 325 def alias_matches(self, text):
326 326 """Match internal system aliases"""
327 327 #print 'Completer->alias_matches:',text # dbg
328 328 text = os.path.expanduser(text)
329 329 aliases = self.alias_table.keys()
330 330 if text == "":
331 331 return aliases
332 332 else:
333 333 return [alias for alias in aliases if alias.startswith(text)]
334 334
335 335 def python_matches(self,text):
336 336 """Match attributes or global python names"""
337 337 #print 'Completer->python_matches' # dbg
338 338 if "." in text:
339 339 try:
340 340 matches = self.attr_matches(text)
341 341 if text.endswith('.') and self.omit__names:
342 342 if self.omit__names == 1:
343 343 # true if txt is _not_ a __ name, false otherwise:
344 344 no__name = (lambda txt:
345 345 re.match(r'.*\.__.*?__',txt) is None)
346 346 else:
347 347 # true if txt is _not_ a _ name, false otherwise:
348 348 no__name = (lambda txt:
349 349 re.match(r'.*\._.*?',txt) is None)
350 350 matches = filter(no__name, matches)
351 351 except NameError:
352 352 # catches <undefined attributes>.<tab>
353 353 matches = []
354 354 else:
355 355 matches = self.global_matches(text)
356 356 # this is so completion finds magics when automagic is on:
357 357 if matches == [] and not text.startswith(os.sep):
358 358 matches = self.attr_matches(self.magic_prefix+text)
359 359 return matches
360 360
361 361 def _default_arguments(self, obj):
362 362 """Return the list of default arguments of obj if it is callable,
363 363 or empty list otherwise."""
364 364
365 365 if not (inspect.isfunction(obj) or inspect.ismethod(obj)):
366 366 # for classes, check for __init__,__new__
367 367 if inspect.isclass(obj):
368 368 obj = (getattr(obj,'__init__',None) or
369 369 getattr(obj,'__new__',None))
370 370 # for all others, check if they are __call__able
371 371 elif hasattr(obj, '__call__'):
372 372 obj = obj.__call__
373 373 # XXX: is there a way to handle the builtins ?
374 374 try:
375 375 args,_,_1,defaults = inspect.getargspec(obj)
376 376 if defaults:
377 377 return args[-len(defaults):]
378 378 except TypeError: pass
379 379 return []
380 380
381 381 def python_func_kw_matches(self,text):
382 382 """Match named parameters (kwargs) of the last open function"""
383 383
384 384 if "." in text: # a parameter cannot be dotted
385 385 return []
386 386 try: regexp = self.__funcParamsRegex
387 387 except AttributeError:
388 388 regexp = self.__funcParamsRegex = re.compile(r'''
389 389 '.*?' | # single quoted strings or
390 390 ".*?" | # double quoted strings or
391 391 \w+ | # identifier
392 392 \S # other characters
393 393 ''', re.VERBOSE | re.DOTALL)
394 394 # 1. find the nearest identifier that comes before an unclosed
395 395 # parenthesis e.g. for "foo (1+bar(x), pa", the candidate is "foo"
396 396 tokens = regexp.findall(self.get_line_buffer())
397 397 tokens.reverse()
398 398 iterTokens = iter(tokens); openPar = 0
399 399 for token in iterTokens:
400 400 if token == ')':
401 401 openPar -= 1
402 402 elif token == '(':
403 403 openPar += 1
404 404 if openPar > 0:
405 405 # found the last unclosed parenthesis
406 406 break
407 407 else:
408 408 return []
409 409 # 2. Concatenate any dotted names (e.g. "foo.bar" for "foo.bar(x, pa" )
410 410 ids = []
411 411 isId = re.compile(r'\w+$').match
412 412 while True:
413 413 try:
414 414 ids.append(iterTokens.next())
415 415 if not isId(ids[-1]):
416 416 ids.pop(); break
417 417 if not iterTokens.next() == '.':
418 418 break
419 419 except StopIteration:
420 420 break
421 421 # lookup the candidate callable matches either using global_matches
422 422 # or attr_matches for dotted names
423 423 if len(ids) == 1:
424 424 callableMatches = self.global_matches(ids[0])
425 425 else:
426 426 callableMatches = self.attr_matches('.'.join(ids[::-1]))
427 427 argMatches = []
428 428 for callableMatch in callableMatches:
429 429 try: namedArgs = self._default_arguments(eval(callableMatch,
430 430 self.namespace))
431 431 except: continue
432 432 for namedArg in namedArgs:
433 433 if namedArg.startswith(text):
434 434 argMatches.append("%s=" %namedArg)
435 435 return argMatches
436 436
437 437 def complete(self, text, state):
438 438 """Return the next possible completion for 'text'.
439 439
440 440 This is called successively with state == 0, 1, 2, ... until it
441 441 returns None. The completion should begin with 'text'. """
442 442
443 443 #print '\n*** COMPLETE: <%s> (%s)' % (text,state) # dbg
444 444 magic_escape = self.magic_escape
445 445 magic_prefix = self.magic_prefix
446 446
447 447 try:
448 448 if text.startswith(magic_escape):
449 449 text = text.replace(magic_escape,magic_prefix)
450 450 elif text.startswith('~'):
451 451 text = os.path.expanduser(text)
452 452 if state == 0:
453 453 # Extend the list of completions with the results of each
454 454 # matcher, so we return results to the user from all
455 455 # namespaces.
456 456 if self.merge_completions:
457 457 self.matches = []
458 458 for matcher in self.matchers:
459 459 self.matches.extend(matcher(text))
460 460 else:
461 461 for matcher in self.matchers:
462 462 self.matches = matcher(text)
463 463 if self.matches:
464 464 break
465 465
466 466 try:
467 467 return self.matches[state].replace(magic_prefix,magic_escape)
468 468 except IndexError:
469 469 return None
470 470 except:
471 471 # If completion fails, don't annoy the user.
472 472 pass
473 473
474 474 except ImportError:
475 475 pass # no readline support
476 476
477 477 except KeyError:
478 478 pass # Windows doesn't set TERM, it doesn't matter
479 479
480 480
481 481 class InputList(UserList.UserList):
482 482 """Class to store user input.
483 483
484 484 It's basically a list, but slices return a string instead of a list, thus
485 485 allowing things like (assuming 'In' is an instance):
486 486
487 487 exec In[4:7]
488 488
489 489 or
490 490
491 491 exec In[5:9] + In[14] + In[21:25]"""
492 492
493 493 def __getslice__(self,i,j):
494 494 return ''.join(UserList.UserList.__getslice__(self,i,j))
495 495
496 496 #****************************************************************************
497 497 # Local use exceptions
498 498 class SpaceInInput(exceptions.Exception):
499 499 pass
500 500
501 501 #****************************************************************************
502 502 # Main IPython class
503 503
504 504 class InteractiveShell(code.InteractiveConsole, Logger, Magic):
505 505 """An enhanced console for Python."""
506 506
507 507 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
508 508 user_ns = None,banner2='',
509 509 custom_exceptions=((),None)):
510 510
511 511 # Put a reference to self in builtins so that any form of embedded or
512 512 # imported code can test for being inside IPython.
513 513 __builtin__.__IPYTHON__ = self
514 514
515 515 # And load into builtins ipmagic/ipalias as well
516 516 __builtin__.ipmagic = ipmagic
517 517 __builtin__.ipalias = ipalias
518 518
519 519 # Add to __builtin__ other parts of IPython's public API
520 520 __builtin__.ip_set_hook = self.set_hook
521 521
522 522 # Keep in the builtins a flag for when IPython is active. We set it
523 523 # with setdefault so that multiple nested IPythons don't clobber one
524 524 # another. Each will increase its value by one upon being activated,
525 525 # which also gives us a way to determine the nesting level.
526 526 __builtin__.__dict__.setdefault('__IPYTHON__active',0)
527 527
528 528 # Inform the user of ipython's fast exit magics.
529 529 _exit = ' Use %Exit or %Quit to exit without confirmation.'
530 530 __builtin__.exit += _exit
531 531 __builtin__.quit += _exit
532 532
533 533 # Create the namespace where the user will operate:
534 534
535 535 # FIXME. For some strange reason, __builtins__ is showing up at user
536 536 # level as a dict instead of a module. This is a manual fix, but I
537 537 # should really track down where the problem is coming from. Alex
538 538 # Schmolck reported this problem first.
539 539
540 540 # A useful post by Alex Martelli on this topic:
541 541 # Re: inconsistent value from __builtins__
542 542 # Von: Alex Martelli <aleaxit@yahoo.com>
543 543 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
544 544 # Gruppen: comp.lang.python
545 545 # Referenzen: 1
546 546
547 547 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
548 548 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
549 549 # > <type 'dict'>
550 550 # > >>> print type(__builtins__)
551 551 # > <type 'module'>
552 552 # > Is this difference in return value intentional?
553 553
554 554 # Well, it's documented that '__builtins__' can be either a dictionary
555 555 # or a module, and it's been that way for a long time. Whether it's
556 556 # intentional (or sensible), I don't know. In any case, the idea is that
557 557 # if you need to access the built-in namespace directly, you should start
558 558 # with "import __builtin__" (note, no 's') which will definitely give you
559 559 # a module. Yeah, it's somewhat confusing:-(.
560 560
561 561 if user_ns is None:
562 562 # Set __name__ to __main__ to better match the behavior of the
563 563 # normal interpreter.
564 564 self.user_ns = {'__name__' :'__main__',
565 565 '__builtins__' : __builtin__,
566 566 }
567 567 else:
568 568 self.user_ns = user_ns
569 569
570 570 # The user namespace MUST have a pointer to the shell itself.
571 571 self.user_ns[name] = self
572 572
573 573 # We need to insert into sys.modules something that looks like a
574 574 # module but which accesses the IPython namespace, for shelve and
575 575 # pickle to work interactively. Normally they rely on getting
576 576 # everything out of __main__, but for embedding purposes each IPython
577 577 # instance has its own private namespace, so we can't go shoving
578 578 # everything into __main__.
579 579
580 580 try:
581 581 main_name = self.user_ns['__name__']
582 582 except KeyError:
583 583 raise KeyError,'user_ns dictionary MUST have a "__name__" key'
584 584 else:
585 585 #print "pickle hack in place" # dbg
586 586 sys.modules[main_name] = FakeModule(self.user_ns)
587 587
588 588 # List of input with multi-line handling.
589 589 # Fill its zero entry, user counter starts at 1
590 590 self.input_hist = InputList(['\n'])
591 591
592 592 # list of visited directories
593 593 self.dir_hist = [os.getcwd()]
594 594
595 595 # dict of output history
596 596 self.output_hist = {}
597 597
598 598 # dict of names to be treated as system aliases. Each entry in the
599 599 # alias table must be a 2-tuple of the form (N,name), where N is the
600 600 # number of positional arguments of the alias.
601 601 self.alias_table = {}
602 602
603 603 # dict of things NOT to alias (keywords and builtins)
604 604 self.no_alias = {}
605 605 for key in keyword.kwlist:
606 606 self.no_alias[key] = 1
607 607 self.no_alias.update(__builtin__.__dict__)
608 608
609 609 # make global variables for user access to these
610 610 self.user_ns['_ih'] = self.input_hist
611 611 self.user_ns['_oh'] = self.output_hist
612 612 self.user_ns['_dh'] = self.dir_hist
613 613
614 614 # user aliases to input and output histories
615 615 self.user_ns['In'] = self.input_hist
616 616 self.user_ns['Out'] = self.output_hist
617 617
618 618 # Store the actual shell's name
619 619 self.name = name
620 620
621 621 # Object variable to store code object waiting execution. This is
622 622 # used mainly by the multithreaded shells, but it can come in handy in
623 623 # other situations. No need to use a Queue here, since it's a single
624 624 # item which gets cleared once run.
625 625 self.code_to_run = None
626 self.code_to_run_src = '' # corresponding source
627 626
628 627 # Job manager (for jobs run as background threads)
629 628 self.jobs = BackgroundJobManager()
630 629 # Put the job manager into builtins so it's always there.
631 630 __builtin__.jobs = self.jobs
632 631
633 632 # escapes for automatic behavior on the command line
634 633 self.ESC_SHELL = '!'
635 634 self.ESC_HELP = '?'
636 635 self.ESC_MAGIC = '%'
637 636 self.ESC_QUOTE = ','
638 637 self.ESC_QUOTE2 = ';'
639 638 self.ESC_PAREN = '/'
640 639
641 640 # And their associated handlers
642 641 self.esc_handlers = {self.ESC_PAREN:self.handle_auto,
643 642 self.ESC_QUOTE:self.handle_auto,
644 643 self.ESC_QUOTE2:self.handle_auto,
645 644 self.ESC_MAGIC:self.handle_magic,
646 645 self.ESC_HELP:self.handle_help,
647 646 self.ESC_SHELL:self.handle_shell_escape,
648 647 }
649 648
650 649 # class initializations
651 650 code.InteractiveConsole.__init__(self,locals = self.user_ns)
652 651 Logger.__init__(self,log_ns = self.user_ns)
653 652 Magic.__init__(self,self)
654 653
655 654 # an ugly hack to get a pointer to the shell, so I can start writing
656 655 # magic code via this pointer instead of the current mixin salad.
657 656 Magic.set_shell(self,self)
658 657
659 658 # hooks holds pointers used for user-side customizations
660 659 self.hooks = Struct()
661 660
662 661 # Set all default hooks, defined in the IPython.hooks module.
663 662 hooks = IPython.hooks
664 663 for hook_name in hooks.__all__:
665 664 self.set_hook(hook_name,getattr(hooks,hook_name))
666 665
667 666 # Flag to mark unconditional exit
668 667 self.exit_now = False
669 668
670 669 self.usage_min = """\
671 670 An enhanced console for Python.
672 671 Some of its features are:
673 672 - Readline support if the readline library is present.
674 673 - Tab completion in the local namespace.
675 674 - Logging of input, see command-line options.
676 675 - System shell escape via ! , eg !ls.
677 676 - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.)
678 677 - Keeps track of locally defined variables via %who, %whos.
679 678 - Show object information with a ? eg ?x or x? (use ?? for more info).
680 679 """
681 680 if usage: self.usage = usage
682 681 else: self.usage = self.usage_min
683 682
684 683 # Storage
685 684 self.rc = rc # This will hold all configuration information
686 685 self.inputcache = []
687 686 self._boundcache = []
688 687 self.pager = 'less'
689 688 # temporary files used for various purposes. Deleted at exit.
690 689 self.tempfiles = []
691 690
692 691 # for pushd/popd management
693 692 try:
694 693 self.home_dir = get_home_dir()
695 694 except HomeDirError,msg:
696 695 fatal(msg)
697 696
698 697 self.dir_stack = [os.getcwd().replace(self.home_dir,'~')]
699 698
700 699 # Functions to call the underlying shell.
701 700
702 701 # utility to expand user variables via Itpl
703 702 self.var_expand = lambda cmd: str(ItplNS(cmd.replace('#','\#'),
704 703 self.user_ns))
705 704 # The first is similar to os.system, but it doesn't return a value,
706 705 # and it allows interpolation of variables in the user's namespace.
707 706 self.system = lambda cmd: shell(self.var_expand(cmd),
708 707 header='IPython system call: ',
709 708 verbose=self.rc.system_verbose)
710 709 # These are for getoutput and getoutputerror:
711 710 self.getoutput = lambda cmd: \
712 711 getoutput(self.var_expand(cmd),
713 712 header='IPython system call: ',
714 713 verbose=self.rc.system_verbose)
715 714 self.getoutputerror = lambda cmd: \
716 715 getoutputerror(str(ItplNS(cmd.replace('#','\#'),
717 716 self.user_ns)),
718 717 header='IPython system call: ',
719 718 verbose=self.rc.system_verbose)
720 719
721 720 # RegExp for splitting line contents into pre-char//first
722 721 # word-method//rest. For clarity, each group in on one line.
723 722
724 723 # WARNING: update the regexp if the above escapes are changed, as they
725 724 # are hardwired in.
726 725
727 726 # Don't get carried away with trying to make the autocalling catch too
728 727 # much: it's better to be conservative rather than to trigger hidden
729 728 # evals() somewhere and end up causing side effects.
730 729
731 730 self.line_split = re.compile(r'^([\s*,;/])'
732 731 r'([\?\w\.]+\w*\s*)'
733 732 r'(\(?.*$)')
734 733
735 734 # Original re, keep around for a while in case changes break something
736 735 #self.line_split = re.compile(r'(^[\s*!\?%,/]?)'
737 736 # r'(\s*[\?\w\.]+\w*\s*)'
738 737 # r'(\(?.*$)')
739 738
740 739 # RegExp to identify potential function names
741 740 self.re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$')
742 741 # RegExp to exclude strings with this start from autocalling
743 742 self.re_exclude_auto = re.compile('^[!=()<>,\*/\+-]|^is ')
744 743 # try to catch also methods for stuff in lists/tuples/dicts: off
745 744 # (experimental). For this to work, the line_split regexp would need
746 745 # to be modified so it wouldn't break things at '['. That line is
747 746 # nasty enough that I shouldn't change it until I can test it _well_.
748 747 #self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$')
749 748
750 749 # keep track of where we started running (mainly for crash post-mortem)
751 750 self.starting_dir = os.getcwd()
752 751
753 752 # Attributes for Logger mixin class, make defaults here
754 753 self._dolog = 0
755 754 self.LOG = ''
756 755 self.LOGDEF = '.InteractiveShell.log'
757 756 self.LOGMODE = 'over'
758 757 self.LOGHEAD = Itpl(
759 758 """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE ***
760 759 #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW
761 760 #log# opts = $self.rc.opts
762 761 #log# args = $self.rc.args
763 762 #log# It is safe to make manual edits below here.
764 763 #log#-----------------------------------------------------------------------
765 764 """)
766 765 # Various switches which can be set
767 766 self.CACHELENGTH = 5000 # this is cheap, it's just text
768 767 self.BANNER = "Python %(version)s on %(platform)s\n" % sys.__dict__
769 768 self.banner2 = banner2
770 769
771 770 # TraceBack handlers:
772 771 # Need two, one for syntax errors and one for other exceptions.
773 772 self.SyntaxTB = ultraTB.ListTB(color_scheme='NoColor')
774 773 # This one is initialized with an offset, meaning we always want to
775 774 # remove the topmost item in the traceback, which is our own internal
776 775 # code. Valid modes: ['Plain','Context','Verbose']
777 776 self.InteractiveTB = ultraTB.AutoFormattedTB(mode = 'Plain',
778 777 color_scheme='NoColor',
779 778 tb_offset = 1)
780 779 # and add any custom exception handlers the user may have specified
781 780 self.set_custom_exc(*custom_exceptions)
782 781
783 782 # Object inspector
784 783 ins_colors = OInspect.InspectColors
785 784 code_colors = PyColorize.ANSICodeColors
786 785 self.inspector = OInspect.Inspector(ins_colors,code_colors,'NoColor')
787 786 self.autoindent = 0
788 787
789 788 # Make some aliases automatically
790 789 # Prepare list of shell aliases to auto-define
791 790 if os.name == 'posix':
792 791 auto_alias = ('mkdir mkdir', 'rmdir rmdir',
793 792 'mv mv -i','rm rm -i','cp cp -i',
794 793 'cat cat','less less','clear clear',
795 794 # a better ls
796 795 'ls ls -F',
797 796 # long ls
798 797 'll ls -lF',
799 798 # color ls
800 799 'lc ls -F -o --color',
801 800 # ls normal files only
802 801 'lf ls -F -o --color %l | grep ^-',
803 802 # ls symbolic links
804 803 'lk ls -F -o --color %l | grep ^l',
805 804 # directories or links to directories,
806 805 'ldir ls -F -o --color %l | grep /$',
807 806 # things which are executable
808 807 'lx ls -F -o --color %l | grep ^-..x',
809 808 )
810 809 elif os.name in ['nt','dos']:
811 810 auto_alias = ('dir dir /on', 'ls dir /on',
812 811 'ddir dir /ad /on', 'ldir dir /ad /on',
813 812 'mkdir mkdir','rmdir rmdir','echo echo',
814 813 'ren ren','cls cls','copy copy')
815 814 else:
816 815 auto_alias = ()
817 816 self.auto_alias = map(lambda s:s.split(None,1),auto_alias)
818 817 # Call the actual (public) initializer
819 818 self.init_auto_alias()
820 819 # end __init__
821 820
822 821 def set_hook(self,name,hook):
823 822 """set_hook(name,hook) -> sets an internal IPython hook.
824 823
825 824 IPython exposes some of its internal API as user-modifiable hooks. By
826 825 resetting one of these hooks, you can modify IPython's behavior to
827 826 call at runtime your own routines."""
828 827
829 828 # At some point in the future, this should validate the hook before it
830 829 # accepts it. Probably at least check that the hook takes the number
831 830 # of args it's supposed to.
832 831 setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__))
833 832
834 833 def set_custom_exc(self,exc_tuple,handler):
835 834 """set_custom_exc(exc_tuple,handler)
836 835
837 836 Set a custom exception handler, which will be called if any of the
838 837 exceptions in exc_tuple occur in the mainloop (specifically, in the
839 838 runcode() method.
840 839
841 840 Inputs:
842 841
843 842 - exc_tuple: a *tuple* of valid exceptions to call the defined
844 843 handler for. It is very important that you use a tuple, and NOT A
845 844 LIST here, because of the way Python's except statement works. If
846 845 you only want to trap a single exception, use a singleton tuple:
847 846
848 847 exc_tuple == (MyCustomException,)
849 848
850 849 - handler: this must be defined as a function with the following
851 850 basic interface: def my_handler(self,etype,value,tb).
852 851
853 852 This will be made into an instance method (via new.instancemethod)
854 853 of IPython itself, and it will be called if any of the exceptions
855 854 listed in the exc_tuple are caught. If the handler is None, an
856 855 internal basic one is used, which just prints basic info.
857 856
858 857 WARNING: by putting in your own exception handler into IPython's main
859 858 execution loop, you run a very good chance of nasty crashes. This
860 859 facility should only be used if you really know what you are doing."""
861 860
862 861 assert type(exc_tuple)==type(()) , \
863 862 "The custom exceptions must be given AS A TUPLE."
864 863
865 864 def dummy_handler(self,etype,value,tb):
866 865 print '*** Simple custom exception handler ***'
867 866 print 'Exception type :',etype
868 867 print 'Exception value:',value
869 868 print 'Traceback :',tb
870 print 'Source code :',self.code_to_run_src
869 print 'Source code :','\n'.join(self.buffer)
871 870
872 871 if handler is None: handler = dummy_handler
873 872
874 873 self.CustomTB = new.instancemethod(handler,self,self.__class__)
875 874 self.custom_exceptions = exc_tuple
876 875
877 876 def set_custom_completer(self,completer,pos=0):
878 877 """set_custom_completer(completer,pos=0)
879 878
880 879 Adds a new custom completer function.
881 880
882 881 The position argument (defaults to 0) is the index in the completers
883 882 list where you want the completer to be inserted."""
884 883
885 884 newcomp = new.instancemethod(completer,self.Completer,
886 885 self.Completer.__class__)
887 886 self.Completer.matchers.insert(pos,newcomp)
888 887
889 888 def post_config_initialization(self):
890 889 """Post configuration init method
891 890
892 891 This is called after the configuration files have been processed to
893 892 'finalize' the initialization."""
894 893
895 894 # dynamic data that survives through sessions
896 895 # XXX make the filename a config option?
897 896 persist_base = 'persist'
898 897 if self.rc.profile:
899 898 persist_base += '_%s' % self.rc.profile
900 899 self.persist_fname = os.path.join(self.rc.ipythondir,persist_base)
901 900
902 901 try:
903 902 self.persist = pickle.load(file(self.persist_fname))
904 903 except:
905 904 self.persist = {}
906 905
907 906 def init_auto_alias(self):
908 907 """Define some aliases automatically.
909 908
910 909 These are ALL parameter-less aliases"""
911 910 for alias,cmd in self.auto_alias:
912 911 self.alias_table[alias] = (0,cmd)
913 912
914 913 def alias_table_validate(self,verbose=0):
915 914 """Update information about the alias table.
916 915
917 916 In particular, make sure no Python keywords/builtins are in it."""
918 917
919 918 no_alias = self.no_alias
920 919 for k in self.alias_table.keys():
921 920 if k in no_alias:
922 921 del self.alias_table[k]
923 922 if verbose:
924 923 print ("Deleting alias <%s>, it's a Python "
925 924 "keyword or builtin." % k)
926 925
927 926 def set_autoindent(self,value=None):
928 927 """Set the autoindent flag, checking for readline support.
929 928
930 929 If called with no arguments, it acts as a toggle."""
931 930
932 931 if not self.has_readline:
933 932 if os.name == 'posix':
934 933 warn("The auto-indent feature requires the readline library")
935 934 self.autoindent = 0
936 935 return
937 936 if value is None:
938 937 self.autoindent = not self.autoindent
939 938 else:
940 939 self.autoindent = value
941 940
942 941 def rc_set_toggle(self,rc_field,value=None):
943 942 """Set or toggle a field in IPython's rc config. structure.
944 943
945 944 If called with no arguments, it acts as a toggle.
946 945
947 946 If called with a non-existent field, the resulting AttributeError
948 947 exception will propagate out."""
949 948
950 949 rc_val = getattr(self.rc,rc_field)
951 950 if value is None:
952 951 value = not rc_val
953 952 setattr(self.rc,rc_field,value)
954 953
955 954 def user_setup(self,ipythondir,rc_suffix,mode='install'):
956 955 """Install the user configuration directory.
957 956
958 957 Can be called when running for the first time or to upgrade the user's
959 958 .ipython/ directory with the mode parameter. Valid modes are 'install'
960 959 and 'upgrade'."""
961 960
962 961 def wait():
963 962 try:
964 963 raw_input("Please press <RETURN> to start IPython.")
965 964 except EOFError:
966 965 print >> Term.cout
967 966 print '*'*70
968 967
969 968 cwd = os.getcwd() # remember where we started
970 969 glb = glob.glob
971 970 print '*'*70
972 971 if mode == 'install':
973 972 print \
974 973 """Welcome to IPython. I will try to create a personal configuration directory
975 974 where you can customize many aspects of IPython's functionality in:\n"""
976 975 else:
977 976 print 'I am going to upgrade your configuration in:'
978 977
979 978 print ipythondir
980 979
981 980 rcdirend = os.path.join('IPython','UserConfig')
982 981 cfg = lambda d: os.path.join(d,rcdirend)
983 982 try:
984 983 rcdir = filter(os.path.isdir,map(cfg,sys.path))[0]
985 984 except IOError:
986 985 warning = """
987 986 Installation error. IPython's directory was not found.
988 987
989 988 Check the following:
990 989
991 990 The ipython/IPython directory should be in a directory belonging to your
992 991 PYTHONPATH environment variable (that is, it should be in a directory
993 992 belonging to sys.path). You can copy it explicitly there or just link to it.
994 993
995 994 IPython will proceed with builtin defaults.
996 995 """
997 996 warn(warning)
998 997 wait()
999 998 return
1000 999
1001 1000 if mode == 'install':
1002 1001 try:
1003 1002 shutil.copytree(rcdir,ipythondir)
1004 1003 os.chdir(ipythondir)
1005 1004 rc_files = glb("ipythonrc*")
1006 1005 for rc_file in rc_files:
1007 1006 os.rename(rc_file,rc_file+rc_suffix)
1008 1007 except:
1009 1008 warning = """
1010 1009
1011 1010 There was a problem with the installation:
1012 1011 %s
1013 1012 Try to correct it or contact the developers if you think it's a bug.
1014 1013 IPython will proceed with builtin defaults.""" % sys.exc_info()[1]
1015 1014 warn(warning)
1016 1015 wait()
1017 1016 return
1018 1017
1019 1018 elif mode == 'upgrade':
1020 1019 try:
1021 1020 os.chdir(ipythondir)
1022 1021 except:
1023 1022 print """
1024 1023 Can not upgrade: changing to directory %s failed. Details:
1025 1024 %s
1026 1025 """ % (ipythondir,sys.exc_info()[1])
1027 1026 wait()
1028 1027 return
1029 1028 else:
1030 1029 sources = glb(os.path.join(rcdir,'[A-Za-z]*'))
1031 1030 for new_full_path in sources:
1032 1031 new_filename = os.path.basename(new_full_path)
1033 1032 if new_filename.startswith('ipythonrc'):
1034 1033 new_filename = new_filename + rc_suffix
1035 1034 # The config directory should only contain files, skip any
1036 1035 # directories which may be there (like CVS)
1037 1036 if os.path.isdir(new_full_path):
1038 1037 continue
1039 1038 if os.path.exists(new_filename):
1040 1039 old_file = new_filename+'.old'
1041 1040 if os.path.exists(old_file):
1042 1041 os.remove(old_file)
1043 1042 os.rename(new_filename,old_file)
1044 1043 shutil.copy(new_full_path,new_filename)
1045 1044 else:
1046 1045 raise ValueError,'unrecognized mode for install:',`mode`
1047 1046
1048 1047 # Fix line-endings to those native to each platform in the config
1049 1048 # directory.
1050 1049 try:
1051 1050 os.chdir(ipythondir)
1052 1051 except:
1053 1052 print """
1054 1053 Problem: changing to directory %s failed.
1055 1054 Details:
1056 1055 %s
1057 1056
1058 1057 Some configuration files may have incorrect line endings. This should not
1059 1058 cause any problems during execution. """ % (ipythondir,sys.exc_info()[1])
1060 1059 wait()
1061 1060 else:
1062 1061 for fname in glb('ipythonrc*'):
1063 1062 try:
1064 1063 native_line_ends(fname,backup=0)
1065 1064 except IOError:
1066 1065 pass
1067 1066
1068 1067 if mode == 'install':
1069 1068 print """
1070 1069 Successful installation!
1071 1070
1072 1071 Please read the sections 'Initial Configuration' and 'Quick Tips' in the
1073 1072 IPython manual (there are both HTML and PDF versions supplied with the
1074 1073 distribution) to make sure that your system environment is properly configured
1075 1074 to take advantage of IPython's features."""
1076 1075 else:
1077 1076 print """
1078 1077 Successful upgrade!
1079 1078
1080 1079 All files in your directory:
1081 1080 %(ipythondir)s
1082 1081 which would have been overwritten by the upgrade were backed up with a .old
1083 1082 extension. If you had made particular customizations in those files you may
1084 1083 want to merge them back into the new files.""" % locals()
1085 1084 wait()
1086 1085 os.chdir(cwd)
1087 1086 # end user_setup()
1088 1087
1089 1088 def atexit_operations(self):
1090 1089 """This will be executed at the time of exit.
1091 1090
1092 1091 Saving of persistent data should be performed here. """
1093 1092
1094 1093 # input history
1095 1094 self.savehist()
1096 1095
1097 1096 # Cleanup all tempfiles left around
1098 1097 for tfile in self.tempfiles:
1099 1098 try:
1100 1099 os.unlink(tfile)
1101 1100 except OSError:
1102 1101 pass
1103 1102
1104 1103 # save the "persistent data" catch-all dictionary
1105 1104 try:
1106 1105 pickle.dump(self.persist, open(self.persist_fname,"w"))
1107 1106 except:
1108 1107 print "*** ERROR *** persistent data saving failed."
1109 1108
1110 1109 def savehist(self):
1111 1110 """Save input history to a file (via readline library)."""
1112 1111 try:
1113 1112 self.readline.write_history_file(self.histfile)
1114 1113 except:
1115 1114 print 'Unable to save IPython command history to file: ' + \
1116 1115 `self.histfile`
1117 1116
1118 1117 def pre_readline(self):
1119 1118 """readline hook to be used at the start of each line.
1120 1119
1121 1120 Currently it handles auto-indent only."""
1122 1121
1123 1122 self.readline.insert_text(' '* self.readline_indent)
1124 1123
1125 1124 def init_readline(self):
1126 1125 """Command history completion/saving/reloading."""
1127 1126 try:
1128 1127 import readline
1129 1128 self.Completer = MagicCompleter(self,
1130 1129 self.user_ns,
1131 1130 self.rc.readline_omit__names,
1132 1131 self.alias_table)
1133 1132 except ImportError,NameError:
1134 1133 # If FlexCompleter failed to import, MagicCompleter won't be
1135 1134 # defined. This can happen because of a problem with readline
1136 1135 self.has_readline = 0
1137 1136 # no point in bugging windows users with this every time:
1138 1137 if os.name == 'posix':
1139 1138 warn('Readline services not available on this platform.')
1140 1139 else:
1141 1140 import atexit
1142 1141
1143 1142 # Platform-specific configuration
1144 1143 if os.name == 'nt':
1145 1144 # readline under Windows modifies the default exit behavior
1146 1145 # from being Ctrl-Z/Return to the Unix Ctrl-D one.
1147 1146 __builtin__.exit = __builtin__.quit = \
1148 1147 ('Use Ctrl-D (i.e. EOF) to exit. '
1149 1148 'Use %Exit or %Quit to exit without confirmation.')
1150 1149 self.readline_startup_hook = readline.set_pre_input_hook
1151 1150 else:
1152 1151 self.readline_startup_hook = readline.set_startup_hook
1153 1152
1154 1153 # Load user's initrc file (readline config)
1155 1154 inputrc_name = os.environ.get('INPUTRC')
1156 1155 if inputrc_name is None:
1157 1156 home_dir = get_home_dir()
1158 1157 if home_dir is not None:
1159 1158 inputrc_name = os.path.join(home_dir,'.inputrc')
1160 1159 if os.path.isfile(inputrc_name):
1161 1160 try:
1162 1161 readline.read_init_file(inputrc_name)
1163 1162 except:
1164 1163 warn('Problems reading readline initialization file <%s>'
1165 1164 % inputrc_name)
1166 1165
1167 1166 self.has_readline = 1
1168 1167 self.readline = readline
1169 1168 self.readline_indent = 0 # for auto-indenting via readline
1170 1169 # save this in sys so embedded copies can restore it properly
1171 1170 sys.ipcompleter = self.Completer.complete
1172 1171 readline.set_completer(self.Completer.complete)
1173 1172
1174 1173 # Configure readline according to user's prefs
1175 1174 for rlcommand in self.rc.readline_parse_and_bind:
1176 1175 readline.parse_and_bind(rlcommand)
1177 1176
1178 1177 # remove some chars from the delimiters list
1179 1178 delims = readline.get_completer_delims()
1180 1179 delims = delims.translate(string._idmap,
1181 1180 self.rc.readline_remove_delims)
1182 1181 readline.set_completer_delims(delims)
1183 1182 # otherwise we end up with a monster history after a while:
1184 1183 readline.set_history_length(1000)
1185 1184 try:
1186 1185 #print '*** Reading readline history' # dbg
1187 1186 readline.read_history_file(self.histfile)
1188 1187 except IOError:
1189 1188 pass # It doesn't exist yet.
1190 1189
1191 1190 atexit.register(self.atexit_operations)
1192 1191 del atexit
1193 1192
1194 1193 # Configure auto-indent for all platforms
1195 1194 self.set_autoindent(self.rc.autoindent)
1196 1195
1197 1196 def showsyntaxerror(self, filename=None):
1198 1197 """Display the syntax error that just occurred.
1199 1198
1200 1199 This doesn't display a stack trace because there isn't one.
1201 1200
1202 1201 If a filename is given, it is stuffed in the exception instead
1203 1202 of what was there before (because Python's parser always uses
1204 1203 "<string>" when reading from a string).
1205 1204 """
1206 1205 type, value, sys.last_traceback = sys.exc_info()
1207 1206 sys.last_type = type
1208 1207 sys.last_value = value
1209 1208 if filename and type is SyntaxError:
1210 1209 # Work hard to stuff the correct filename in the exception
1211 1210 try:
1212 1211 msg, (dummy_filename, lineno, offset, line) = value
1213 1212 except:
1214 1213 # Not the format we expect; leave it alone
1215 1214 pass
1216 1215 else:
1217 1216 # Stuff in the right filename
1218 1217 try:
1219 1218 # Assume SyntaxError is a class exception
1220 1219 value = SyntaxError(msg, (filename, lineno, offset, line))
1221 1220 except:
1222 1221 # If that failed, assume SyntaxError is a string
1223 1222 value = msg, (filename, lineno, offset, line)
1224 1223 self.SyntaxTB(type,value,[])
1225 1224
1226 1225 def debugger(self):
1227 1226 """Call the pdb debugger."""
1228 1227
1229 1228 if not self.rc.pdb:
1230 1229 return
1231 1230 pdb.pm()
1232 1231
1233 1232 def showtraceback(self,exc_tuple = None):
1234 1233 """Display the exception that just occurred."""
1235 1234
1236 1235 # Though this won't be called by syntax errors in the input line,
1237 1236 # there may be SyntaxError cases whith imported code.
1238 1237 if exc_tuple is None:
1239 1238 type, value, tb = sys.exc_info()
1240 1239 else:
1241 1240 type, value, tb = exc_tuple
1242 1241 if type is SyntaxError:
1243 1242 self.showsyntaxerror()
1244 1243 else:
1245 1244 sys.last_type = type
1246 1245 sys.last_value = value
1247 1246 sys.last_traceback = tb
1248 1247 self.InteractiveTB()
1249 1248 if self.InteractiveTB.call_pdb and self.has_readline:
1250 1249 # pdb mucks up readline, fix it back
1251 1250 self.readline.set_completer(self.Completer.complete)
1252 1251
1253 1252 def update_cache(self, line):
1254 1253 """puts line into cache"""
1255 1254 self.inputcache.insert(0, line) # This copies the cache every time ... :-(
1256 1255 if len(self.inputcache) >= self.CACHELENGTH:
1257 1256 self.inputcache.pop() # This not :-)
1258 1257
1259 1258 def name_space_init(self):
1260 1259 """Create local namespace."""
1261 1260 # We want this to be a method to facilitate embedded initialization.
1262 1261 code.InteractiveConsole.__init__(self,self.user_ns)
1263 1262
1264 1263 def mainloop(self,banner=None):
1265 1264 """Creates the local namespace and starts the mainloop.
1266 1265
1267 1266 If an optional banner argument is given, it will override the
1268 1267 internally created default banner."""
1269 1268
1270 1269 self.name_space_init()
1271 1270 if self.rc.c: # Emulate Python's -c option
1272 1271 self.exec_init_cmd()
1273 1272 if banner is None:
1274 1273 if self.rc.banner:
1275 1274 banner = self.BANNER+self.banner2
1276 1275 else:
1277 1276 banner = ''
1278 1277 self.interact(banner)
1279 1278
1280 1279 def exec_init_cmd(self):
1281 1280 """Execute a command given at the command line.
1282 1281
1283 1282 This emulates Python's -c option."""
1284 1283
1285 1284 sys.argv = ['-c']
1286 1285 self.push(self.rc.c)
1287 1286
1288 1287 def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0):
1289 1288 """Embeds IPython into a running python program.
1290 1289
1291 1290 Input:
1292 1291
1293 1292 - header: An optional header message can be specified.
1294 1293
1295 1294 - local_ns, global_ns: working namespaces. If given as None, the
1296 1295 IPython-initialized one is updated with __main__.__dict__, so that
1297 1296 program variables become visible but user-specific configuration
1298 1297 remains possible.
1299 1298
1300 1299 - stack_depth: specifies how many levels in the stack to go to
1301 1300 looking for namespaces (when local_ns and global_ns are None). This
1302 1301 allows an intermediate caller to make sure that this function gets
1303 1302 the namespace from the intended level in the stack. By default (0)
1304 1303 it will get its locals and globals from the immediate caller.
1305 1304
1306 1305 Warning: it's possible to use this in a program which is being run by
1307 1306 IPython itself (via %run), but some funny things will happen (a few
1308 1307 globals get overwritten). In the future this will be cleaned up, as
1309 1308 there is no fundamental reason why it can't work perfectly."""
1310 1309
1311 1310 # Patch for global embedding to make sure that things don't overwrite
1312 1311 # user globals accidentally. Thanks to Richard <rxe@renre-europe.com>
1313 1312 # FIXME. Test this a bit more carefully (the if.. is new)
1314 1313 if local_ns is None and global_ns is None:
1315 1314 self.user_ns.update(__main__.__dict__)
1316 1315
1317 1316 # Get locals and globals from caller
1318 1317 if local_ns is None or global_ns is None:
1319 1318 call_frame = sys._getframe(stack_depth).f_back
1320 1319
1321 1320 if local_ns is None:
1322 1321 local_ns = call_frame.f_locals
1323 1322 if global_ns is None:
1324 1323 global_ns = call_frame.f_globals
1325 1324
1326 1325 # Update namespaces and fire up interpreter
1327 1326 self.user_ns.update(local_ns)
1328 1327 self.interact(header)
1329 1328
1330 1329 # Remove locals from namespace
1331 1330 for k in local_ns:
1332 1331 del self.user_ns[k]
1333 1332
1334 1333 def interact(self, banner=None):
1335 1334 """Closely emulate the interactive Python console.
1336 1335
1337 1336 The optional banner argument specify the banner to print
1338 1337 before the first interaction; by default it prints a banner
1339 1338 similar to the one printed by the real Python interpreter,
1340 1339 followed by the current class name in parentheses (so as not
1341 1340 to confuse this with the real interpreter -- since it's so
1342 1341 close!).
1343 1342
1344 1343 """
1345 1344 cprt = 'Type "copyright", "credits" or "license" for more information.'
1346 1345 if banner is None:
1347 1346 self.write("Python %s on %s\n%s\n(%s)\n" %
1348 1347 (sys.version, sys.platform, cprt,
1349 1348 self.__class__.__name__))
1350 1349 else:
1351 1350 self.write(banner)
1352 1351
1353 1352 more = 0
1354 1353
1355 1354 # Mark activity in the builtins
1356 1355 __builtin__.__dict__['__IPYTHON__active'] += 1
1357 1356
1358 1357 # exit_now is set by a call to %Exit or %Quit
1359 1358 while not self.exit_now:
1360 1359 try:
1361 1360 if more:
1362 1361 prompt = self.outputcache.prompt2
1363 1362 if self.autoindent:
1364 1363 self.readline_startup_hook(self.pre_readline)
1365 1364 else:
1366 1365 prompt = self.outputcache.prompt1
1367 1366 try:
1368 1367 line = self.raw_input(prompt)
1369 1368 if self.autoindent:
1370 1369 self.readline_startup_hook(None)
1371 1370 except EOFError:
1372 1371 if self.autoindent:
1373 1372 self.readline_startup_hook(None)
1374 1373 self.write("\n")
1375 1374 if self.rc.confirm_exit:
1376 1375 if ask_yes_no('Do you really want to exit ([y]/n)?','y'):
1377 1376 break
1378 1377 else:
1379 1378 break
1380 1379 else:
1381 1380 more = self.push(line)
1382 1381 # Auto-indent management
1383 1382 if self.autoindent:
1384 1383 if line:
1385 1384 ini_spaces = re.match('^(\s+)',line)
1386 1385 if ini_spaces:
1387 1386 nspaces = ini_spaces.end()
1388 1387 else:
1389 1388 nspaces = 0
1390 1389 self.readline_indent = nspaces
1391 1390
1392 1391 if line[-1] == ':':
1393 1392 self.readline_indent += 4
1394 1393 elif re.match(r'^\s+raise|^\s+return',line):
1395 1394 self.readline_indent -= 4
1396 1395 else:
1397 1396 self.readline_indent = 0
1398 1397
1399 1398 except KeyboardInterrupt:
1400 1399 self.write("\nKeyboardInterrupt\n")
1401 1400 self.resetbuffer()
1402 1401 more = 0
1403 1402 # keep cache in sync with the prompt counter:
1404 1403 self.outputcache.prompt_count -= 1
1405 1404
1406 1405 if self.autoindent:
1407 1406 self.readline_indent = 0
1408 1407
1409 1408 except bdb.BdbQuit:
1410 1409 warn("The Python debugger has exited with a BdbQuit exception.\n"
1411 1410 "Because of how pdb handles the stack, it is impossible\n"
1412 1411 "for IPython to properly format this particular exception.\n"
1413 1412 "IPython will resume normal operation.")
1414 1413
1415 1414 # We are off again...
1416 1415 __builtin__.__dict__['__IPYTHON__active'] -= 1
1417 1416
1418 1417 def excepthook(self, type, value, tb):
1419 1418 """One more defense for GUI apps that call sys.excepthook.
1420 1419
1421 1420 GUI frameworks like wxPython trap exceptions and call
1422 1421 sys.excepthook themselves. I guess this is a feature that
1423 1422 enables them to keep running after exceptions that would
1424 1423 otherwise kill their mainloop. This is a bother for IPython
1425 1424 which excepts to catch all of the program exceptions with a try:
1426 1425 except: statement.
1427 1426
1428 1427 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1429 1428 any app directly invokes sys.excepthook, it will look to the user like
1430 1429 IPython crashed. In order to work around this, we can disable the
1431 1430 CrashHandler and replace it with this excepthook instead, which prints a
1432 1431 regular traceback using our InteractiveTB. In this fashion, apps which
1433 1432 call sys.excepthook will generate a regular-looking exception from
1434 1433 IPython, and the CrashHandler will only be triggered by real IPython
1435 1434 crashes.
1436 1435
1437 1436 This hook should be used sparingly, only in places which are not likely
1438 1437 to be true IPython errors.
1439 1438 """
1440 1439
1441 1440 self.InteractiveTB(type, value, tb, tb_offset=0)
1442 1441 if self.InteractiveTB.call_pdb and self.has_readline:
1443 1442 self.readline.set_completer(self.Completer.complete)
1444 1443
1445 1444 def call_alias(self,alias,rest=''):
1446 1445 """Call an alias given its name and the rest of the line.
1447 1446
1448 1447 This function MUST be given a proper alias, because it doesn't make
1449 1448 any checks when looking up into the alias table. The caller is
1450 1449 responsible for invoking it only with a valid alias."""
1451 1450
1452 1451 #print 'ALIAS: <%s>+<%s>' % (alias,rest) # dbg
1453 1452 nargs,cmd = self.alias_table[alias]
1454 1453 # Expand the %l special to be the user's input line
1455 1454 if cmd.find('%l') >= 0:
1456 1455 cmd = cmd.replace('%l',rest)
1457 1456 rest = ''
1458 1457 if nargs==0:
1459 1458 # Simple, argument-less aliases
1460 1459 cmd = '%s %s' % (cmd,rest)
1461 1460 else:
1462 1461 # Handle aliases with positional arguments
1463 1462 args = rest.split(None,nargs)
1464 1463 if len(args)< nargs:
1465 1464 error('Alias <%s> requires %s arguments, %s given.' %
1466 1465 (alias,nargs,len(args)))
1467 1466 return
1468 1467 cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
1469 1468 # Now call the macro, evaluating in the user's namespace
1470 1469 try:
1471 1470 self.system(cmd)
1472 1471 except:
1473 1472 self.showtraceback()
1474 1473
1475 1474 def runlines(self,lines):
1476 1475 """Run a string of one or more lines of source.
1477 1476
1478 1477 This method is capable of running a string containing multiple source
1479 1478 lines, as if they had been entered at the IPython prompt. Since it
1480 1479 exposes IPython's processing machinery, the given strings can contain
1481 1480 magic calls (%magic), special shell access (!cmd), etc."""
1482 1481
1483 1482 # We must start with a clean buffer, in case this is run from an
1484 1483 # interactive IPython session (via a magic, for example).
1485 1484 self.resetbuffer()
1486 1485 lines = lines.split('\n')
1487 1486 more = 0
1488 1487 for line in lines:
1489 1488 # skip blank lines so we don't mess up the prompt counter, but do
1490 1489 # NOT skip even a blank line if we are in a code block (more is
1491 1490 # true)
1492 1491 if line or more:
1493 1492 more = self.push((self.prefilter(line,more)))
1494 1493 # IPython's runsource returns None if there was an error
1495 1494 # compiling the code. This allows us to stop processing right
1496 1495 # away, so the user gets the error message at the right place.
1497 1496 if more is None:
1498 1497 break
1499 1498 # final newline in case the input didn't have it, so that the code
1500 1499 # actually does get executed
1501 1500 if more:
1502 1501 self.push('\n')
1503 1502
1504 1503 def runsource(self, source, filename="<input>", symbol="single"):
1505 1504 """Compile and run some source in the interpreter.
1506 1505
1507 1506 Arguments are as for compile_command().
1508 1507
1509 1508 One several things can happen:
1510 1509
1511 1510 1) The input is incorrect; compile_command() raised an
1512 1511 exception (SyntaxError or OverflowError). A syntax traceback
1513 1512 will be printed by calling the showsyntaxerror() method.
1514 1513
1515 1514 2) The input is incomplete, and more input is required;
1516 1515 compile_command() returned None. Nothing happens.
1517 1516
1518 1517 3) The input is complete; compile_command() returned a code
1519 1518 object. The code is executed by calling self.runcode() (which
1520 1519 also handles run-time exceptions, except for SystemExit).
1521 1520
1522 1521 The return value is:
1523 1522
1524 1523 - True in case 2
1525 1524
1526 1525 - False in the other cases, unless an exception is raised, where
1527 1526 None is returned instead. This can be used by external callers to
1528 1527 know whether to continue feeding input or not.
1529 1528
1530 1529 The return value can be used to decide whether to use sys.ps1 or
1531 1530 sys.ps2 to prompt the next line."""
1531
1532 1532 try:
1533 1533 code = self.compile(source, filename, symbol)
1534 1534 except (OverflowError, SyntaxError, ValueError):
1535 1535 # Case 1
1536 1536 self.showsyntaxerror(filename)
1537 1537 return None
1538 1538
1539 1539 if code is None:
1540 1540 # Case 2
1541 1541 return True
1542 1542
1543 1543 # Case 3
1544 # We store the code source and object so that threaded shells and
1544 # We store the code object so that threaded shells and
1545 1545 # custom exception handlers can access all this info if needed.
1546 self.code_to_run_src = source
1546 # The source corresponding to this can be obtained from the
1547 # buffer attribute as '\n'.join(self.buffer).
1547 1548 self.code_to_run = code
1548 1549 # now actually execute the code object
1549 1550 if self.runcode(code) == 0:
1550 1551 return False
1551 1552 else:
1552 1553 return None
1553 1554
1554 1555 def runcode(self,code_obj):
1555 1556 """Execute a code object.
1556 1557
1557 1558 When an exception occurs, self.showtraceback() is called to display a
1558 1559 traceback.
1559 1560
1560 1561 Return value: a flag indicating whether the code to be run completed
1561 1562 successfully:
1562 1563
1563 1564 - 0: successful execution.
1564 1565 - 1: an error occurred.
1565 1566 """
1566 1567
1567 1568 # Set our own excepthook in case the user code tries to call it
1568 1569 # directly, so that the IPython crash handler doesn't get triggered
1569 1570 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
1570 1571 outflag = 1 # happens in more places, so it's easier as default
1571 1572 try:
1572 1573 try:
1573 1574 exec code_obj in self.locals
1574 1575 finally:
1575 1576 # Reset our crash handler in place
1576 1577 sys.excepthook = old_excepthook
1577 1578 except SystemExit:
1578 1579 self.resetbuffer()
1579 1580 self.showtraceback()
1580 1581 warn( __builtin__.exit,level=1)
1581 1582 except self.custom_exceptions:
1582 1583 etype,value,tb = sys.exc_info()
1583 1584 self.CustomTB(etype,value,tb)
1584 1585 except:
1585 1586 self.showtraceback()
1586 1587 else:
1587 1588 outflag = 0
1588 1589 if code.softspace(sys.stdout, 0):
1589 1590 print
1590 1591 # Flush out code object which has been run (and source)
1591 1592 self.code_to_run = None
1592 self.code_to_run_src = ''
1593 1593 return outflag
1594 1594
1595 1595 def raw_input(self, prompt=""):
1596 1596 """Write a prompt and read a line.
1597 1597
1598 1598 The returned line does not include the trailing newline.
1599 1599 When the user enters the EOF key sequence, EOFError is raised.
1600 1600
1601 1601 The base implementation uses the built-in function
1602 1602 raw_input(); a subclass may replace this with a different
1603 1603 implementation.
1604 1604 """
1605 1605 return self.prefilter(raw_input_original(prompt),
1606 1606 prompt==self.outputcache.prompt2)
1607 1607
1608 1608 def split_user_input(self,line):
1609 1609 """Split user input into pre-char, function part and rest."""
1610 1610
1611 1611 lsplit = self.line_split.match(line)
1612 1612 if lsplit is None: # no regexp match returns None
1613 1613 try:
1614 1614 iFun,theRest = line.split(None,1)
1615 1615 except ValueError:
1616 1616 iFun,theRest = line,''
1617 1617 pre = re.match('^(\s*)(.*)',line).groups()[0]
1618 1618 else:
1619 1619 pre,iFun,theRest = lsplit.groups()
1620 1620
1621 1621 #print 'line:<%s>' % line # dbg
1622 1622 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun.strip(),theRest) # dbg
1623 1623 return pre,iFun.strip(),theRest
1624 1624
1625 1625 def _prefilter(self, line, continue_prompt):
1626 1626 """Calls different preprocessors, depending on the form of line."""
1627 1627
1628 1628 # All handlers *must* return a value, even if it's blank ('').
1629 1629
1630 1630 # Lines are NOT logged here. Handlers should process the line as
1631 1631 # needed, update the cache AND log it (so that the input cache array
1632 1632 # stays synced).
1633 1633
1634 1634 # This function is _very_ delicate, and since it's also the one which
1635 1635 # determines IPython's response to user input, it must be as efficient
1636 1636 # as possible. For this reason it has _many_ returns in it, trying
1637 1637 # always to exit as quickly as it can figure out what it needs to do.
1638 1638
1639 1639 # This function is the main responsible for maintaining IPython's
1640 1640 # behavior respectful of Python's semantics. So be _very_ careful if
1641 1641 # making changes to anything here.
1642 1642
1643 1643 #.....................................................................
1644 1644 # Code begins
1645 1645
1646 1646 #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg
1647 1647
1648 1648 # save the line away in case we crash, so the post-mortem handler can
1649 1649 # record it
1650 1650 self._last_input_line = line
1651 1651
1652 1652 #print '***line: <%s>' % line # dbg
1653 1653
1654 1654 # the input history needs to track even empty lines
1655 1655 if not line.strip():
1656 1656 if not continue_prompt:
1657 1657 self.outputcache.prompt_count -= 1
1658 1658 return self.handle_normal('',continue_prompt)
1659 1659
1660 1660 # print '***cont',continue_prompt # dbg
1661 1661 # special handlers are only allowed for single line statements
1662 1662 if continue_prompt and not self.rc.multi_line_specials:
1663 1663 return self.handle_normal(line,continue_prompt)
1664 1664
1665 1665 # For the rest, we need the structure of the input
1666 1666 pre,iFun,theRest = self.split_user_input(line)
1667 1667 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
1668 1668
1669 1669 # First check for explicit escapes in the last/first character
1670 1670 handler = None
1671 1671 if line[-1] == self.ESC_HELP:
1672 1672 handler = self.esc_handlers.get(line[-1]) # the ? can be at the end
1673 1673 if handler is None:
1674 1674 # look at the first character of iFun, NOT of line, so we skip
1675 1675 # leading whitespace in multiline input
1676 1676 handler = self.esc_handlers.get(iFun[0:1])
1677 1677 if handler is not None:
1678 1678 return handler(line,continue_prompt,pre,iFun,theRest)
1679 1679 # Emacs ipython-mode tags certain input lines
1680 1680 if line.endswith('# PYTHON-MODE'):
1681 1681 return self.handle_emacs(line,continue_prompt)
1682 1682
1683 1683 # Next, check if we can automatically execute this thing
1684 1684
1685 1685 # Allow ! in multi-line statements if multi_line_specials is on:
1686 1686 if continue_prompt and self.rc.multi_line_specials and \
1687 1687 iFun.startswith(self.ESC_SHELL):
1688 1688 return self.handle_shell_escape(line,continue_prompt,
1689 1689 pre=pre,iFun=iFun,
1690 1690 theRest=theRest)
1691 1691
1692 1692 # Let's try to find if the input line is a magic fn
1693 1693 oinfo = None
1694 1694 if hasattr(self,'magic_'+iFun):
1695 1695 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
1696 1696 if oinfo['ismagic']:
1697 1697 # Be careful not to call magics when a variable assignment is
1698 1698 # being made (ls='hi', for example)
1699 1699 if self.rc.automagic and \
1700 1700 (len(theRest)==0 or theRest[0] not in '!=()<>,') and \
1701 1701 (self.rc.multi_line_specials or not continue_prompt):
1702 1702 return self.handle_magic(line,continue_prompt,
1703 1703 pre,iFun,theRest)
1704 1704 else:
1705 1705 return self.handle_normal(line,continue_prompt)
1706 1706
1707 1707 # If the rest of the line begins with an (in)equality, assginment or
1708 1708 # function call, we should not call _ofind but simply execute it.
1709 1709 # This avoids spurious geattr() accesses on objects upon assignment.
1710 1710 #
1711 1711 # It also allows users to assign to either alias or magic names true
1712 1712 # python variables (the magic/alias systems always take second seat to
1713 1713 # true python code).
1714 1714 if theRest and theRest[0] in '!=()':
1715 1715 return self.handle_normal(line,continue_prompt)
1716 1716
1717 1717 if oinfo is None:
1718 1718 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
1719 1719
1720 1720 if not oinfo['found']:
1721 1721 return self.handle_normal(line,continue_prompt)
1722 1722 else:
1723 1723 #print 'iFun <%s> rest <%s>' % (iFun,theRest) # dbg
1724 1724 if oinfo['isalias']:
1725 1725 return self.handle_alias(line,continue_prompt,
1726 1726 pre,iFun,theRest)
1727 1727
1728 1728 if self.rc.autocall and \
1729 1729 not self.re_exclude_auto.match(theRest) and \
1730 1730 self.re_fun_name.match(iFun) and \
1731 1731 callable(oinfo['obj']) :
1732 1732 #print 'going auto' # dbg
1733 1733 return self.handle_auto(line,continue_prompt,pre,iFun,theRest)
1734 1734 else:
1735 1735 #print 'was callable?', callable(oinfo['obj']) # dbg
1736 1736 return self.handle_normal(line,continue_prompt)
1737 1737
1738 1738 # If we get here, we have a normal Python line. Log and return.
1739 1739 return self.handle_normal(line,continue_prompt)
1740 1740
1741 1741 def _prefilter_dumb(self, line, continue_prompt):
1742 1742 """simple prefilter function, for debugging"""
1743 1743 return self.handle_normal(line,continue_prompt)
1744 1744
1745 1745 # Set the default prefilter() function (this can be user-overridden)
1746 1746 prefilter = _prefilter
1747 1747
1748 1748 def handle_normal(self,line,continue_prompt=None,
1749 1749 pre=None,iFun=None,theRest=None):
1750 1750 """Handle normal input lines. Use as a template for handlers."""
1751 1751
1752 1752 self.log(line,continue_prompt)
1753 1753 self.update_cache(line)
1754 1754 return line
1755 1755
1756 1756 def handle_alias(self,line,continue_prompt=None,
1757 1757 pre=None,iFun=None,theRest=None):
1758 1758 """Handle alias input lines. """
1759 1759
1760 1760 theRest = esc_quotes(theRest)
1761 1761 line_out = "%s%s.call_alias('%s','%s')" % (pre,self.name,iFun,theRest)
1762 1762 self.log(line_out,continue_prompt)
1763 1763 self.update_cache(line_out)
1764 1764 return line_out
1765 1765
1766 1766 def handle_shell_escape(self, line, continue_prompt=None,
1767 1767 pre=None,iFun=None,theRest=None):
1768 1768 """Execute the line in a shell, empty return value"""
1769 1769
1770 #print 'line in :', `line` # dbg
1770 1771 # Example of a special handler. Others follow a similar pattern.
1771 1772 if continue_prompt: # multi-line statements
1772 1773 if iFun.startswith('!!'):
1773 1774 print 'SyntaxError: !! is not allowed in multiline statements'
1774 1775 return pre
1775 1776 else:
1776 1777 cmd = ("%s %s" % (iFun[1:],theRest)).replace('"','\\"')
1777 1778 line_out = '%s%s.system("%s")' % (pre,self.name,cmd)
1779 #line_out = ('%s%s.system(' % (pre,self.name)) + repr(cmd) + ')'
1778 1780 else: # single-line input
1779 1781 if line.startswith('!!'):
1780 1782 # rewrite iFun/theRest to properly hold the call to %sx and
1781 1783 # the actual command to be executed, so handle_magic can work
1782 1784 # correctly
1783 1785 theRest = '%s %s' % (iFun[2:],theRest)
1784 1786 iFun = 'sx'
1785 1787 return self.handle_magic('%ssx %s' % (self.ESC_MAGIC,line[2:]),
1786 1788 continue_prompt,pre,iFun,theRest)
1787 1789 else:
1788 1790 cmd = esc_quotes(line[1:])
1789 1791 line_out = '%s.system("%s")' % (self.name,cmd)
1792 #line_out = ('%s.system(' % self.name) + repr(cmd)+ ')'
1790 1793 # update cache/log and return
1791 1794 self.log(line_out,continue_prompt)
1792 1795 self.update_cache(line_out) # readline cache gets normal line
1796 #print 'line out r:', `line_out` # dbg
1797 #print 'line out s:', line_out # dbg
1793 1798 return line_out
1794 1799
1795 1800 def handle_magic(self, line, continue_prompt=None,
1796 1801 pre=None,iFun=None,theRest=None):
1797 1802 """Execute magic functions.
1798 1803
1799 1804 Also log them with a prepended # so the log is clean Python."""
1800 1805
1801 1806 cmd = '%sipmagic("%s")' % (pre,esc_quotes('%s %s' % (iFun,theRest)))
1802 1807 self.log(cmd,continue_prompt)
1803 1808 self.update_cache(line)
1804 1809 #print 'in handle_magic, cmd=<%s>' % cmd # dbg
1805 1810 return cmd
1806 1811
1807 1812 def handle_auto(self, line, continue_prompt=None,
1808 1813 pre=None,iFun=None,theRest=None):
1809 1814 """Hande lines which can be auto-executed, quoting if requested."""
1810 1815
1811 1816 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
1812 1817
1813 1818 # This should only be active for single-line input!
1814 1819 if continue_prompt:
1815 1820 return line
1816 1821
1817 1822 if pre == self.ESC_QUOTE:
1818 1823 # Auto-quote splitting on whitespace
1819 1824 newcmd = '%s("%s")\n' % (iFun,'", "'.join(theRest.split()) )
1820 1825 elif pre == self.ESC_QUOTE2:
1821 1826 # Auto-quote whole string
1822 1827 newcmd = '%s("%s")\n' % (iFun,theRest)
1823 1828 else:
1824 1829 # Auto-paren
1825 1830 if theRest[0:1] in ('=','['):
1826 1831 # Don't autocall in these cases. They can be either
1827 1832 # rebindings of an existing callable's name, or item access
1828 1833 # for an object which is BOTH callable and implements
1829 1834 # __getitem__.
1830 1835 return '%s %s\n' % (iFun,theRest)
1831 1836 if theRest.endswith(';'):
1832 1837 newcmd = '%s(%s);\n' % (iFun.rstrip(),theRest[:-1])
1833 1838 else:
1834 1839 newcmd = '%s(%s)\n' % (iFun.rstrip(),theRest)
1835 1840
1836 1841 print >>Term.cout, self.outputcache.prompt1.auto_rewrite() + newcmd,
1837 1842 # log what is now valid Python, not the actual user input (without the
1838 1843 # final newline)
1839 1844 self.log(newcmd.strip(),continue_prompt)
1840 1845 return newcmd
1841 1846
1842 1847 def handle_help(self, line, continue_prompt=None,
1843 1848 pre=None,iFun=None,theRest=None):
1844 1849 """Try to get some help for the object.
1845 1850
1846 1851 obj? or ?obj -> basic information.
1847 1852 obj?? or ??obj -> more details.
1848 1853 """
1849 1854
1850 1855 # We need to make sure that we don't process lines which would be
1851 1856 # otherwise valid python, such as "x=1 # what?"
1852 1857 try:
1853 1858 code.compile_command(line)
1854 1859 except SyntaxError:
1855 1860 # We should only handle as help stuff which is NOT valid syntax
1856 1861 if line[0]==self.ESC_HELP:
1857 1862 line = line[1:]
1858 1863 elif line[-1]==self.ESC_HELP:
1859 1864 line = line[:-1]
1860 1865 self.log('#?'+line)
1861 1866 self.update_cache(line)
1862 1867 if line:
1863 1868 self.magic_pinfo(line)
1864 1869 else:
1865 1870 page(self.usage,screen_lines=self.rc.screen_length)
1866 1871 return '' # Empty string is needed here!
1867 1872 except:
1868 1873 # Pass any other exceptions through to the normal handler
1869 1874 return self.handle_normal(line,continue_prompt)
1870 1875 else:
1871 1876 # If the code compiles ok, we should handle it normally
1872 1877 return self.handle_normal(line,continue_prompt)
1873 1878
1874 1879 def handle_emacs(self,line,continue_prompt=None,
1875 1880 pre=None,iFun=None,theRest=None):
1876 1881 """Handle input lines marked by python-mode."""
1877 1882
1878 1883 # Currently, nothing is done. Later more functionality can be added
1879 1884 # here if needed.
1880 1885
1881 1886 # The input cache shouldn't be updated
1882 1887
1883 1888 return line
1884 1889
1885 1890 def write(self,data):
1886 1891 """Write a string to the default output"""
1887 1892 Term.cout.write(data)
1888 1893
1889 1894 def write_err(self,data):
1890 1895 """Write a string to the default error output"""
1891 1896 Term.cerr.write(data)
1892 1897
1893 1898 def safe_execfile(self,fname,*where,**kw):
1894 1899 fname = os.path.expanduser(fname)
1895 1900
1896 1901 # find things also in current directory
1897 1902 dname = os.path.dirname(fname)
1898 1903 if not sys.path.count(dname):
1899 1904 sys.path.append(dname)
1900 1905
1901 1906 try:
1902 1907 xfile = open(fname)
1903 1908 except:
1904 1909 print >> Term.cerr, \
1905 1910 'Could not open file <%s> for safe execution.' % fname
1906 1911 return None
1907 1912
1908 1913 kw.setdefault('islog',0)
1909 1914 kw.setdefault('quiet',1)
1910 1915 kw.setdefault('exit_ignore',0)
1911 1916 first = xfile.readline()
1912 1917 _LOGHEAD = str(self.LOGHEAD).split('\n',1)[0].strip()
1913 1918 xfile.close()
1914 1919 # line by line execution
1915 1920 if first.startswith(_LOGHEAD) or kw['islog']:
1916 1921 print 'Loading log file <%s> one line at a time...' % fname
1917 1922 if kw['quiet']:
1918 1923 stdout_save = sys.stdout
1919 1924 sys.stdout = StringIO.StringIO()
1920 1925 try:
1921 1926 globs,locs = where[0:2]
1922 1927 except:
1923 1928 try:
1924 1929 globs = locs = where[0]
1925 1930 except:
1926 1931 globs = locs = globals()
1927 1932 badblocks = []
1928 1933
1929 1934 # we also need to identify indented blocks of code when replaying
1930 1935 # logs and put them together before passing them to an exec
1931 1936 # statement. This takes a bit of regexp and look-ahead work in the
1932 1937 # file. It's easiest if we swallow the whole thing in memory
1933 1938 # first, and manually walk through the lines list moving the
1934 1939 # counter ourselves.
1935 1940 indent_re = re.compile('\s+\S')
1936 1941 xfile = open(fname)
1937 1942 filelines = xfile.readlines()
1938 1943 xfile.close()
1939 1944 nlines = len(filelines)
1940 1945 lnum = 0
1941 1946 while lnum < nlines:
1942 1947 line = filelines[lnum]
1943 1948 lnum += 1
1944 1949 # don't re-insert logger status info into cache
1945 1950 if line.startswith('#log#'):
1946 1951 continue
1947 1952 elif line.startswith('#%s'% self.ESC_MAGIC):
1948 1953 self.update_cache(line[1:])
1949 1954 line = magic2python(line)
1950 1955 elif line.startswith('#!'):
1951 1956 self.update_cache(line[1:])
1952 1957 else:
1953 1958 # build a block of code (maybe a single line) for execution
1954 1959 block = line
1955 1960 try:
1956 1961 next = filelines[lnum] # lnum has already incremented
1957 1962 except:
1958 1963 next = None
1959 1964 while next and indent_re.match(next):
1960 1965 block += next
1961 1966 lnum += 1
1962 1967 try:
1963 1968 next = filelines[lnum]
1964 1969 except:
1965 1970 next = None
1966 1971 # now execute the block of one or more lines
1967 1972 try:
1968 1973 exec block in globs,locs
1969 1974 self.update_cache(block.rstrip())
1970 1975 except SystemExit:
1971 1976 pass
1972 1977 except:
1973 1978 badblocks.append(block.rstrip())
1974 1979 if kw['quiet']: # restore stdout
1975 1980 sys.stdout.close()
1976 1981 sys.stdout = stdout_save
1977 1982 print 'Finished replaying log file <%s>' % fname
1978 1983 if badblocks:
1979 1984 print >> sys.stderr, \
1980 1985 '\nThe following lines/blocks in file <%s> reported errors:' \
1981 1986 % fname
1982 1987 for badline in badblocks:
1983 1988 print >> sys.stderr, badline
1984 1989 else: # regular file execution
1985 1990 try:
1986 1991 execfile(fname,*where)
1987 1992 except SyntaxError:
1988 1993 etype, evalue = sys.exc_info()[0:2]
1989 1994 self.SyntaxTB(etype,evalue,[])
1990 1995 warn('Failure executing file: <%s>' % fname)
1991 1996 except SystemExit,status:
1992 1997 if not kw['exit_ignore']:
1993 1998 self.InteractiveTB()
1994 1999 warn('Failure executing file: <%s>' % fname)
1995 2000 except:
1996 2001 self.InteractiveTB()
1997 2002 warn('Failure executing file: <%s>' % fname)
1998 2003
1999 2004 #************************* end of file <iplib.py> *****************************
@@ -1,859 +1,860 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 $Id: ultraTB.py 636 2005-07-17 03:11:11Z fperez $"""
63 $Id: ultraTB.py 703 2005-08-16 17:34:44Z fperez $"""
64 64
65 65 #*****************************************************************************
66 66 # Copyright (C) 2001 Nathaniel Gray <n8gray@caltech.edu>
67 67 # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
68 68 #
69 69 # Distributed under the terms of the BSD License. The full license is in
70 70 # the file COPYING, distributed as part of this software.
71 71 #*****************************************************************************
72 72
73 73 from IPython import Release
74 74 __author__ = '%s <%s>\n%s <%s>' % (Release.authors['Nathan']+
75 75 Release.authors['Fernando'])
76 76 __license__ = Release.license
77 77
78 78 # Required modules
79 79 import sys, os, traceback, types, string, time
80 80 import keyword, tokenize, linecache, inspect, pydoc
81 81 from UserDict import UserDict
82 82
83 83 # IPython's own modules
84 84 # Modified pdb which doesn't damage IPython's readline handling
85 85 from IPython import Debugger
86 86
87 87 from IPython.Struct import Struct
88 88 from IPython.ColorANSI import *
89 89 from IPython.genutils import Term,uniq_stable,error,info
90 90
91 91 #---------------------------------------------------------------------------
92 92 # Code begins
93 93
94 94 def inspect_error():
95 95 """Print a message about internal inspect errors.
96 96
97 97 These are unfortunately quite common."""
98 98
99 99 error('Internal Python error in the inspect module.\n'
100 100 'Below is the traceback from this internal error.\n')
101 101
102 102 # Make a global variable out of the color scheme table used for coloring
103 103 # exception tracebacks. This allows user code to add new schemes at runtime.
104 104 ExceptionColors = ColorSchemeTable()
105 105
106 106 # Populate it with color schemes
107 107 C = TermColors # shorthand and local lookup
108 108 ExceptionColors.add_scheme(ColorScheme(
109 109 'NoColor',
110 110 # The color to be used for the top line
111 111 topline = C.NoColor,
112 112
113 113 # The colors to be used in the traceback
114 114 filename = C.NoColor,
115 115 lineno = C.NoColor,
116 116 name = C.NoColor,
117 117 vName = C.NoColor,
118 118 val = C.NoColor,
119 119 em = C.NoColor,
120 120
121 121 # Emphasized colors for the last frame of the traceback
122 122 normalEm = C.NoColor,
123 123 filenameEm = C.NoColor,
124 124 linenoEm = C.NoColor,
125 125 nameEm = C.NoColor,
126 126 valEm = C.NoColor,
127 127
128 128 # Colors for printing the exception
129 129 excName = C.NoColor,
130 130 line = C.NoColor,
131 131 caret = C.NoColor,
132 132 Normal = C.NoColor
133 133 ))
134 134
135 135 # make some schemes as instances so we can copy them for modification easily
136 136 ExceptionColors.add_scheme(ColorScheme(
137 137 'Linux',
138 138 # The color to be used for the top line
139 139 topline = C.LightRed,
140 140
141 141 # The colors to be used in the traceback
142 142 filename = C.Green,
143 143 lineno = C.Green,
144 144 name = C.Purple,
145 145 vName = C.Cyan,
146 146 val = C.Green,
147 147 em = C.LightCyan,
148 148
149 149 # Emphasized colors for the last frame of the traceback
150 150 normalEm = C.LightCyan,
151 151 filenameEm = C.LightGreen,
152 152 linenoEm = C.LightGreen,
153 153 nameEm = C.LightPurple,
154 154 valEm = C.LightBlue,
155 155
156 156 # Colors for printing the exception
157 157 excName = C.LightRed,
158 158 line = C.Yellow,
159 159 caret = C.White,
160 160 Normal = C.Normal
161 161 ))
162 162
163 163 # For light backgrounds, swap dark/light colors
164 164 ExceptionColors.add_scheme(ColorScheme(
165 165 'LightBG',
166 166 # The color to be used for the top line
167 167 topline = C.Red,
168 168
169 169 # The colors to be used in the traceback
170 170 filename = C.LightGreen,
171 171 lineno = C.LightGreen,
172 172 name = C.LightPurple,
173 173 vName = C.Cyan,
174 174 val = C.LightGreen,
175 175 em = C.Cyan,
176 176
177 177 # Emphasized colors for the last frame of the traceback
178 178 normalEm = C.Cyan,
179 179 filenameEm = C.Green,
180 180 linenoEm = C.Green,
181 181 nameEm = C.Purple,
182 182 valEm = C.Blue,
183 183
184 184 # Colors for printing the exception
185 185 excName = C.Red,
186 186 #line = C.Brown, # brown often is displayed as yellow
187 187 line = C.Red,
188 188 caret = C.Normal,
189 189 Normal = C.Normal
190 190 ))
191 191
192 192 class TBTools:
193 193 """Basic tools used by all traceback printer classes."""
194 194
195 195 def __init__(self,color_scheme = 'NoColor',call_pdb=0):
196 196 # Whether to call the interactive pdb debugger after printing
197 197 # tracebacks or not
198 198 self.call_pdb = call_pdb
199 199 if call_pdb:
200 200 self.pdb = Debugger.Pdb()
201 201 else:
202 202 self.pdb = None
203 203
204 204 # Create color table
205 205 self.ColorSchemeTable = ExceptionColors
206 206
207 207 self.set_colors(color_scheme)
208 208 self.old_scheme = color_scheme # save initial value for toggles
209 209
210 210 def set_colors(self,*args,**kw):
211 211 """Shorthand access to the color table scheme selector method."""
212 212
213 213 self.ColorSchemeTable.set_active_scheme(*args,**kw)
214 214 # for convenience, set Colors to the active scheme
215 215 self.Colors = self.ColorSchemeTable.active_colors
216 216
217 217 def color_toggle(self):
218 218 """Toggle between the currently active color scheme and NoColor."""
219 219
220 220 if self.ColorSchemeTable.active_scheme_name == 'NoColor':
221 221 self.ColorSchemeTable.set_active_scheme(self.old_scheme)
222 222 self.Colors = self.ColorSchemeTable.active_colors
223 223 else:
224 224 self.old_scheme = self.ColorSchemeTable.active_scheme_name
225 225 self.ColorSchemeTable.set_active_scheme('NoColor')
226 226 self.Colors = self.ColorSchemeTable.active_colors
227 227
228 228 #---------------------------------------------------------------------------
229 229 class ListTB(TBTools):
230 230 """Print traceback information from a traceback list, with optional color.
231 231
232 232 Calling: requires 3 arguments:
233 233 (etype, evalue, elist)
234 234 as would be obtained by:
235 235 etype, evalue, tb = sys.exc_info()
236 236 if tb:
237 237 elist = traceback.extract_tb(tb)
238 238 else:
239 239 elist = None
240 240
241 241 It can thus be used by programs which need to process the traceback before
242 242 printing (such as console replacements based on the code module from the
243 243 standard library).
244 244
245 245 Because they are meant to be called without a full traceback (only a
246 246 list), instances of this class can't call the interactive pdb debugger."""
247 247
248 248 def __init__(self,color_scheme = 'NoColor'):
249 249 TBTools.__init__(self,color_scheme = color_scheme,call_pdb=0)
250 250
251 251 def __call__(self, etype, value, elist):
252 252 print >> Term.cerr, self.text(etype,value,elist)
253 253
254 254 def text(self,etype, value, elist,context=5):
255 255 """Return a color formatted string with the traceback info."""
256 256
257 257 Colors = self.Colors
258 258 out_string = ['%s%s%s\n' % (Colors.topline,'-'*60,Colors.Normal)]
259 259 if elist:
260 260 out_string.append('Traceback %s(most recent call last)%s:' % \
261 261 (Colors.normalEm, Colors.Normal) + '\n')
262 262 out_string.extend(self._format_list(elist))
263 263 lines = self._format_exception_only(etype, value)
264 264 for line in lines[:-1]:
265 265 out_string.append(" "+line)
266 266 out_string.append(lines[-1])
267 267 return ''.join(out_string)
268 268
269 269 def _format_list(self, extracted_list):
270 270 """Format a list of traceback entry tuples for printing.
271 271
272 272 Given a list of tuples as returned by extract_tb() or
273 273 extract_stack(), return a list of strings ready for printing.
274 274 Each string in the resulting list corresponds to the item with the
275 275 same index in the argument list. Each string ends in a newline;
276 276 the strings may contain internal newlines as well, for those items
277 277 whose source text line is not None.
278 278
279 279 Lifted almost verbatim from traceback.py
280 280 """
281 281
282 282 Colors = self.Colors
283 283 list = []
284 284 for filename, lineno, name, line in extracted_list[:-1]:
285 285 item = ' File %s"%s"%s, line %s%d%s, in %s%s%s\n' % \
286 286 (Colors.filename, filename, Colors.Normal,
287 287 Colors.lineno, lineno, Colors.Normal,
288 288 Colors.name, name, Colors.Normal)
289 289 if line:
290 290 item = item + ' %s\n' % line.strip()
291 291 list.append(item)
292 292 # Emphasize the last entry
293 293 filename, lineno, name, line = extracted_list[-1]
294 294 item = '%s File %s"%s"%s, line %s%d%s, in %s%s%s%s\n' % \
295 295 (Colors.normalEm,
296 296 Colors.filenameEm, filename, Colors.normalEm,
297 297 Colors.linenoEm, lineno, Colors.normalEm,
298 298 Colors.nameEm, name, Colors.normalEm,
299 299 Colors.Normal)
300 300 if line:
301 301 item = item + '%s %s%s\n' % (Colors.line, line.strip(),
302 302 Colors.Normal)
303 303 list.append(item)
304 304 return list
305 305
306 306 def _format_exception_only(self, etype, value):
307 307 """Format the exception part of a traceback.
308 308
309 309 The arguments are the exception type and value such as given by
310 310 sys.last_type and sys.last_value. The return value is a list of
311 311 strings, each ending in a newline. Normally, the list contains a
312 312 single string; however, for SyntaxError exceptions, it contains
313 313 several lines that (when printed) display detailed information
314 314 about where the syntax error occurred. The message indicating
315 315 which exception occurred is the always last string in the list.
316 316
317 317 Also lifted nearly verbatim from traceback.py
318 318 """
319 319
320 320 Colors = self.Colors
321 321 list = []
322 322 if type(etype) == types.ClassType:
323 323 stype = Colors.excName + etype.__name__ + Colors.Normal
324 324 else:
325 325 stype = etype # String exceptions don't get special coloring
326 326 if value is None:
327 327 list.append( str(stype) + '\n')
328 328 else:
329 329 if etype is SyntaxError:
330 330 try:
331 331 msg, (filename, lineno, offset, line) = value
332 332 except:
333 333 pass
334 334 else:
335 335 #print 'filename is',filename # dbg
336 336 if not filename: filename = "<string>"
337 337 list.append('%s File %s"%s"%s, line %s%d%s\n' % \
338 338 (Colors.normalEm,
339 339 Colors.filenameEm, filename, Colors.normalEm,
340 340 Colors.linenoEm, lineno, Colors.Normal ))
341 341 if line is not None:
342 342 i = 0
343 343 while i < len(line) and line[i].isspace():
344 344 i = i+1
345 345 list.append('%s %s%s\n' % (Colors.line,
346 346 line.strip(),
347 347 Colors.Normal))
348 348 if offset is not None:
349 349 s = ' '
350 350 for c in line[i:offset-1]:
351 351 if c.isspace():
352 352 s = s + c
353 353 else:
354 354 s = s + ' '
355 355 list.append('%s%s^%s\n' % (Colors.caret, s,
356 356 Colors.Normal) )
357 357 value = msg
358 358 s = self._some_str(value)
359 359 if s:
360 360 list.append('%s%s:%s %s\n' % (str(stype), Colors.excName,
361 361 Colors.Normal, s))
362 362 else:
363 363 list.append('%s\n' % str(stype))
364 364 return list
365 365
366 366 def _some_str(self, value):
367 367 # Lifted from traceback.py
368 368 try:
369 369 return str(value)
370 370 except:
371 371 return '<unprintable %s object>' % type(value).__name__
372 372
373 373 #----------------------------------------------------------------------------
374 374 class VerboseTB(TBTools):
375 375 """A port of Ka-Ping Yee's cgitb.py module that outputs color text instead
376 376 of HTML. Requires inspect and pydoc. Crazy, man.
377 377
378 378 Modified version which optionally strips the topmost entries from the
379 379 traceback, to be used with alternate interpreters (because their own code
380 380 would appear in the traceback)."""
381 381
382 382 def __init__(self,color_scheme = 'Linux',tb_offset=0,long_header=0,
383 383 call_pdb = 0, include_vars=1):
384 384 """Specify traceback offset, headers and color scheme.
385 385
386 386 Define how many frames to drop from the tracebacks. Calling it with
387 387 tb_offset=1 allows use of this handler in interpreters which will have
388 388 their own code at the top of the traceback (VerboseTB will first
389 389 remove that frame before printing the traceback info)."""
390 390 TBTools.__init__(self,color_scheme=color_scheme,call_pdb=call_pdb)
391 391 self.tb_offset = tb_offset
392 392 self.long_header = long_header
393 393 self.include_vars = include_vars
394 394
395 395 def text(self, etype, evalue, etb, context=5):
396 396 """Return a nice text document describing the traceback."""
397 397
398 398 # some locals
399 399 Colors = self.Colors # just a shorthand + quicker name lookup
400 400 ColorsNormal = Colors.Normal # used a lot
401 401 indent_size = 8 # we need some space to put line numbers before
402 402 indent = ' '*indent_size
403 403 numbers_width = indent_size - 1 # leave space between numbers & code
404 404 text_repr = pydoc.text.repr
405 405 exc = '%s%s%s' % (Colors.excName, str(etype), ColorsNormal)
406 406 em_normal = '%s\n%s%s' % (Colors.valEm, indent,ColorsNormal)
407 407 undefined = '%sundefined%s' % (Colors.em, ColorsNormal)
408 408
409 409 # some internal-use functions
410 410 def eqrepr(value, repr=text_repr): return '=%s' % repr(value)
411 411 def nullrepr(value, repr=text_repr): return ''
412 412
413 413 # meat of the code begins
414 414 if type(etype) is types.ClassType:
415 415 etype = etype.__name__
416 416
417 417 if self.long_header:
418 418 # Header with the exception type, python version, and date
419 419 pyver = 'Python ' + string.split(sys.version)[0] + ': ' + sys.executable
420 420 date = time.ctime(time.time())
421 421
422 422 head = '%s%s%s\n%s%s%s\n%s' % (Colors.topline, '-'*75, ColorsNormal,
423 423 exc, ' '*(75-len(str(etype))-len(pyver)),
424 424 pyver, string.rjust(date, 75) )
425 425 head += "\nA problem occured executing Python code. Here is the sequence of function"\
426 426 "\ncalls leading up to the error, with the most recent (innermost) call last."
427 427 else:
428 428 # Simplified header
429 429 head = '%s%s%s\n%s%s' % (Colors.topline, '-'*75, ColorsNormal,exc,
430 430 string.rjust('Traceback (most recent call last)',
431 431 75 - len(str(etype)) ) )
432 432 frames = []
433 433 # Flush cache before calling inspect. This helps alleviate some of the
434 434 # problems with python 2.3's inspect.py.
435 435 linecache.checkcache()
436 436 # Drop topmost frames if requested
437 437 try:
438 438 records = inspect.getinnerframes(etb, context)[self.tb_offset:]
439 439 except:
440 440
441 441 # FIXME: I've been getting many crash reports from python 2.3
442 442 # users, traceable to inspect.py. If I can find a small test-case
443 443 # to reproduce this, I should either write a better workaround or
444 444 # file a bug report against inspect (if that's the real problem).
445 445 # So far, I haven't been able to find an isolated example to
446 446 # reproduce the problem.
447 447 inspect_error()
448 448 traceback.print_exc(file=Term.cerr)
449 449 info('\nUnfortunately, your original traceback can not be constructed.\n')
450 450 return ''
451 451
452 452 # build some color string templates outside these nested loops
453 453 tpl_link = '%s%%s%s' % (Colors.filenameEm,ColorsNormal)
454 454 tpl_call = 'in %s%%s%s%%s%s' % (Colors.vName, Colors.valEm,
455 455 ColorsNormal)
456 456 tpl_call_fail = 'in %s%%s%s(***failed resolving arguments***)%s' % \
457 457 (Colors.vName, Colors.valEm, ColorsNormal)
458 458 tpl_local_var = '%s%%s%s' % (Colors.vName, ColorsNormal)
459 459 tpl_global_var = '%sglobal%s %s%%s%s' % (Colors.em, ColorsNormal,
460 460 Colors.vName, ColorsNormal)
461 461 tpl_name_val = '%%s %s= %%s%s' % (Colors.valEm, ColorsNormal)
462 462 tpl_line = '%s%%s%s %%s' % (Colors.lineno, ColorsNormal)
463 463 tpl_line_em = '%s%%s%s %%s%s' % (Colors.linenoEm,Colors.line,
464 464 ColorsNormal)
465 465
466 466 # now, loop over all records printing context and info
467 467 abspath = os.path.abspath
468 468 for frame, file, lnum, func, lines, index in records:
469 469 #print '*** record:',file,lnum,func,lines,index # dbg
470 470 try:
471 471 file = file and abspath(file) or '?'
472 472 except OSError:
473 473 # if file is '<console>' or something not in the filesystem,
474 474 # the abspath call will throw an OSError. Just ignore it and
475 475 # keep the original file string.
476 476 pass
477 477 link = tpl_link % file
478 478 try:
479 479 args, varargs, varkw, locals = inspect.getargvalues(frame)
480 480 except:
481 481 # This can happen due to a bug in python2.3. We should be
482 482 # able to remove this try/except when 2.4 becomes a
483 483 # requirement. Bug details at http://python.org/sf/1005466
484 484 inspect_error()
485 485 traceback.print_exc(file=Term.cerr)
486 486 info("\nIPython's exception reporting continues...\n")
487 487
488 488 if func == '?':
489 489 call = ''
490 490 else:
491 491 # Decide whether to include variable details or not
492 492 var_repr = self.include_vars and eqrepr or nullrepr
493 493 try:
494 494 call = tpl_call % (func,inspect.formatargvalues(args,
495 495 varargs, varkw,
496 496 locals,formatvalue=var_repr))
497 497 except KeyError:
498 498 # Very odd crash from inspect.formatargvalues(). The
499 499 # scenario under which it appeared was a call to
500 500 # view(array,scale) in NumTut.view.view(), where scale had
501 501 # been defined as a scalar (it should be a tuple). Somehow
502 502 # inspect messes up resolving the argument list of view()
503 503 # and barfs out. At some point I should dig into this one
504 504 # and file a bug report about it.
505 505 inspect_error()
506 506 traceback.print_exc(file=Term.cerr)
507 507 info("\nIPython's exception reporting continues...\n")
508 508 call = tpl_call_fail % func
509 509
510 510 # Initialize a list of names on the current line, which the
511 511 # tokenizer below will populate.
512 512 names = []
513 513
514 514 def tokeneater(token_type, token, start, end, line):
515 515 """Stateful tokeneater which builds dotted names.
516 516
517 517 The list of names it appends to (from the enclosing scope) can
518 518 contain repeated composite names. This is unavoidable, since
519 519 there is no way to disambguate partial dotted structures until
520 520 the full list is known. The caller is responsible for pruning
521 521 the final list of duplicates before using it."""
522 522
523 523 # build composite names
524 524 if token == '.':
525 525 try:
526 526 names[-1] += '.'
527 527 # store state so the next token is added for x.y.z names
528 528 tokeneater.name_cont = True
529 529 return
530 530 except IndexError:
531 531 pass
532 532 if token_type == tokenize.NAME and token not in keyword.kwlist:
533 533 if tokeneater.name_cont:
534 534 # Dotted names
535 535 names[-1] += token
536 536 tokeneater.name_cont = False
537 537 else:
538 538 # Regular new names. We append everything, the caller
539 539 # will be responsible for pruning the list later. It's
540 540 # very tricky to try to prune as we go, b/c composite
541 541 # names can fool us. The pruning at the end is easy
542 542 # to do (or the caller can print a list with repeated
543 543 # names if so desired.
544 544 names.append(token)
545 545 elif token_type == tokenize.NEWLINE:
546 546 raise IndexError
547 547 # we need to store a bit of state in the tokenizer to build
548 548 # dotted names
549 549 tokeneater.name_cont = False
550 550
551 551 def linereader(file=file, lnum=[lnum], getline=linecache.getline):
552 552 line = getline(file, lnum[0])
553 553 lnum[0] += 1
554 554 return line
555 555
556 556 # Build the list of names on this line of code where the exception
557 557 # occurred.
558 558 try:
559 559 # This builds the names list in-place by capturing it from the
560 560 # enclosing scope.
561 561 tokenize.tokenize(linereader, tokeneater)
562 562 except IndexError:
563 563 # signals exit of tokenizer
564 564 pass
565 565 except tokenize.TokenError,msg:
566 566 _m = ("An unexpected error occurred while tokenizing input\n"
567 567 "The following traceback may be corrupted or invalid\n"
568 568 "The error message is: %s\n" % msg)
569 569 error(_m)
570 570
571 571 # prune names list of duplicates, but keep the right order
572 572 unique_names = uniq_stable(names)
573 573
574 574 # Start loop over vars
575 575 lvals = []
576 576 if self.include_vars:
577 577 for name_full in unique_names:
578 578 name_base = name_full.split('.',1)[0]
579 579 if name_base in frame.f_code.co_varnames:
580 580 if locals.has_key(name_base):
581 581 try:
582 582 value = repr(eval(name_full,locals))
583 583 except:
584 584 value = undefined
585 585 else:
586 586 value = undefined
587 587 name = tpl_local_var % name_full
588 588 else:
589 589 if frame.f_globals.has_key(name_base):
590 590 try:
591 591 value = repr(eval(name_full,frame.f_globals))
592 592 except:
593 593 value = undefined
594 594 else:
595 595 value = undefined
596 596 name = tpl_global_var % name_full
597 597 lvals.append(tpl_name_val % (name,value))
598 598 if lvals:
599 599 lvals = '%s%s' % (indent,em_normal.join(lvals))
600 600 else:
601 601 lvals = ''
602 602
603 603 level = '%s %s\n' % (link,call)
604 604 excerpt = []
605 605 if index is not None:
606 606 i = lnum - index
607 607 for line in lines:
608 608 if i == lnum:
609 609 # This is the line with the error
610 610 pad = numbers_width - len(str(i))
611 611 if pad >= 3:
612 612 marker = '-'*(pad-3) + '-> '
613 613 elif pad == 2:
614 614 marker = '> '
615 615 elif pad == 1:
616 616 marker = '>'
617 617 else:
618 618 marker = ''
619 619 num = '%s%s' % (marker,i)
620 620 line = tpl_line_em % (num,line)
621 621 else:
622 622 num = '%*s' % (numbers_width,i)
623 623 line = tpl_line % (num,line)
624 624
625 625 excerpt.append(line)
626 626 if self.include_vars and i == lnum:
627 627 excerpt.append('%s\n' % lvals)
628 628 i += 1
629 629 frames.append('%s%s' % (level,''.join(excerpt)) )
630 630
631 631 # Get (safely) a string form of the exception info
632 632 try:
633 633 etype_str,evalue_str = map(str,(etype,evalue))
634 634 except:
635 635 # User exception is improperly defined.
636 636 etype,evalue = str,sys.exc_info()[:2]
637 637 etype_str,evalue_str = map(str,(etype,evalue))
638 638 # ... and format it
639 639 exception = ['%s%s%s: %s' % (Colors.excName, etype_str,
640 640 ColorsNormal, evalue_str)]
641 641 if type(evalue) is types.InstanceType:
642 for name in dir(evalue):
642 names = [w for w in dir(evalue) if isinstance(w, basestring)]
643 for name in names:
643 644 value = text_repr(getattr(evalue, name))
644 645 exception.append('\n%s%s = %s' % (indent, name, value))
645 646 # return all our info assembled as a single string
646 647 return '%s\n\n%s\n%s' % (head,'\n'.join(frames),''.join(exception[0]) )
647 648
648 649 def debugger(self):
649 650 """Call up the pdb debugger if desired, always clean up the tb reference.
650 651
651 652 If the call_pdb flag is set, the pdb interactive debugger is
652 653 invoked. In all cases, the self.tb reference to the current traceback
653 654 is deleted to prevent lingering references which hamper memory
654 655 management.
655 656
656 657 Note that each call to pdb() does an 'import readline', so if your app
657 658 requires a special setup for the readline completers, you'll have to
658 659 fix that by hand after invoking the exception handler."""
659 660
660 661 if self.call_pdb:
661 662 if self.pdb is None:
662 663 self.pdb = Debugger.Pdb()
663 664 # the system displayhook may have changed, restore the original for pdb
664 665 dhook = sys.displayhook
665 666 sys.displayhook = sys.__displayhook__
666 667 self.pdb.reset()
667 668 while self.tb.tb_next is not None:
668 669 self.tb = self.tb.tb_next
669 670 try:
670 671 self.pdb.interaction(self.tb.tb_frame, self.tb)
671 672 except:
672 673 print '*** ERROR ***'
673 674 print 'This version of pdb has a bug and crashed.'
674 675 print 'Returning to IPython...'
675 676 sys.displayhook = dhook
676 677 del self.tb
677 678
678 679 def handler(self, info=None):
679 680 (etype, evalue, etb) = info or sys.exc_info()
680 681 self.tb = etb
681 682 print >> Term.cerr, self.text(etype, evalue, etb)
682 683
683 684 # Changed so an instance can just be called as VerboseTB_inst() and print
684 685 # out the right info on its own.
685 686 def __call__(self, etype=None, evalue=None, etb=None):
686 687 """This hook can replace sys.excepthook (for Python 2.1 or higher)."""
687 688 if etb is not None:
688 689 self.handler((etype, evalue, etb))
689 690 else:
690 691 self.handler()
691 692 self.debugger()
692 693
693 694 #----------------------------------------------------------------------------
694 695 class FormattedTB(VerboseTB,ListTB):
695 696 """Subclass ListTB but allow calling with a traceback.
696 697
697 698 It can thus be used as a sys.excepthook for Python > 2.1.
698 699
699 700 Also adds 'Context' and 'Verbose' modes, not available in ListTB.
700 701
701 702 Allows a tb_offset to be specified. This is useful for situations where
702 703 one needs to remove a number of topmost frames from the traceback (such as
703 704 occurs with python programs that themselves execute other python code,
704 705 like Python shells). """
705 706
706 707 def __init__(self, mode = 'Plain', color_scheme='Linux',
707 708 tb_offset = 0,long_header=0,call_pdb=0,include_vars=0):
708 709
709 710 # NEVER change the order of this list. Put new modes at the end:
710 711 self.valid_modes = ['Plain','Context','Verbose']
711 712 self.verbose_modes = self.valid_modes[1:3]
712 713
713 714 VerboseTB.__init__(self,color_scheme,tb_offset,long_header,
714 715 call_pdb=call_pdb,include_vars=include_vars)
715 716 self.set_mode(mode)
716 717
717 718 def _extract_tb(self,tb):
718 719 if tb:
719 720 return traceback.extract_tb(tb)
720 721 else:
721 722 return None
722 723
723 724 def text(self, etype, value, tb,context=5,mode=None):
724 725 """Return formatted traceback.
725 726
726 727 If the optional mode parameter is given, it overrides the current
727 728 mode."""
728 729
729 730 if mode is None:
730 731 mode = self.mode
731 732 if mode in self.verbose_modes:
732 733 # verbose modes need a full traceback
733 734 return VerboseTB.text(self,etype, value, tb,context=5)
734 735 else:
735 736 # We must check the source cache because otherwise we can print
736 737 # out-of-date source code.
737 738 linecache.checkcache()
738 739 # Now we can extract and format the exception
739 740 elist = self._extract_tb(tb)
740 741 if len(elist) > self.tb_offset:
741 742 del elist[:self.tb_offset]
742 743 return ListTB.text(self,etype,value,elist)
743 744
744 745 def set_mode(self,mode=None):
745 746 """Switch to the desired mode.
746 747
747 748 If mode is not specified, cycles through the available modes."""
748 749
749 750 if not mode:
750 751 new_idx = ( self.valid_modes.index(self.mode) + 1 ) % \
751 752 len(self.valid_modes)
752 753 self.mode = self.valid_modes[new_idx]
753 754 elif mode not in self.valid_modes:
754 755 raise ValueError, 'Unrecognized mode in FormattedTB: <'+mode+'>\n'\
755 756 'Valid modes: '+str(self.valid_modes)
756 757 else:
757 758 self.mode = mode
758 759 # include variable details only in 'Verbose' mode
759 760 self.include_vars = (self.mode == self.valid_modes[2])
760 761
761 762 # some convenient shorcuts
762 763 def plain(self):
763 764 self.set_mode(self.valid_modes[0])
764 765
765 766 def context(self):
766 767 self.set_mode(self.valid_modes[1])
767 768
768 769 def verbose(self):
769 770 self.set_mode(self.valid_modes[2])
770 771
771 772 #----------------------------------------------------------------------------
772 773 class AutoFormattedTB(FormattedTB):
773 774 """A traceback printer which can be called on the fly.
774 775
775 776 It will find out about exceptions by itself.
776 777
777 778 A brief example:
778 779
779 780 AutoTB = AutoFormattedTB(mode = 'Verbose',color_scheme='Linux')
780 781 try:
781 782 ...
782 783 except:
783 784 AutoTB() # or AutoTB(out=logfile) where logfile is an open file object
784 785 """
785 786 def __call__(self,etype=None,evalue=None,etb=None,
786 787 out=None,tb_offset=None):
787 788 """Print out a formatted exception traceback.
788 789
789 790 Optional arguments:
790 791 - out: an open file-like object to direct output to.
791 792
792 793 - tb_offset: the number of frames to skip over in the stack, on a
793 794 per-call basis (this overrides temporarily the instance's tb_offset
794 795 given at initialization time. """
795 796
796 797 if out is None:
797 798 out = Term.cerr
798 799 if tb_offset is not None:
799 800 tb_offset, self.tb_offset = self.tb_offset, tb_offset
800 801 print >> out, self.text(etype, evalue, etb)
801 802 self.tb_offset = tb_offset
802 803 else:
803 804 print >> out, self.text()
804 805 self.debugger()
805 806
806 807 def text(self,etype=None,value=None,tb=None,context=5,mode=None):
807 808 if etype is None:
808 809 etype,value,tb = sys.exc_info()
809 810 self.tb = tb
810 811 return FormattedTB.text(self,etype,value,tb,context=5,mode=mode)
811 812
812 813 #---------------------------------------------------------------------------
813 814 # A simple class to preserve Nathan's original functionality.
814 815 class ColorTB(FormattedTB):
815 816 """Shorthand to initialize a FormattedTB in Linux colors mode."""
816 817 def __init__(self,color_scheme='Linux',call_pdb=0):
817 818 FormattedTB.__init__(self,color_scheme=color_scheme,
818 819 call_pdb=call_pdb)
819 820
820 821 #----------------------------------------------------------------------------
821 822 # module testing (minimal)
822 823 if __name__ == "__main__":
823 824 def spam(c, (d, e)):
824 825 x = c + d
825 826 y = c * d
826 827 foo(x, y)
827 828
828 829 def foo(a, b, bar=1):
829 830 eggs(a, b + bar)
830 831
831 832 def eggs(f, g, z=globals()):
832 833 h = f + g
833 834 i = f - g
834 835 return h / i
835 836
836 837 print ''
837 838 print '*** Before ***'
838 839 try:
839 840 print spam(1, (2, 3))
840 841 except:
841 842 traceback.print_exc()
842 843 print ''
843 844
844 845 handler = ColorTB()
845 846 print '*** ColorTB ***'
846 847 try:
847 848 print spam(1, (2, 3))
848 849 except:
849 850 apply(handler, sys.exc_info() )
850 851 print ''
851 852
852 853 handler = VerboseTB()
853 854 print '*** VerboseTB ***'
854 855 try:
855 856 print spam(1, (2, 3))
856 857 except:
857 858 apply(handler, sys.exc_info() )
858 859 print ''
859 860
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
General Comments 0
You need to be logged in to leave comments. Login now