##// END OF EJS Templates
%autocall fixes...
fperez -
Show More

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

@@ -1,1751 +1,1745 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 1007 2006-01-12 17:15:41Z vivainio $"""
8 $Id: genutils.py 1013 2006-01-13 08:33:32Z fperez $"""
9 9
10 10 #*****************************************************************************
11 11 # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu>
12 12 #
13 13 # Distributed under the terms of the BSD License. The full license is in
14 14 # the file COPYING, distributed as part of this software.
15 15 #*****************************************************************************
16 16
17 17 from __future__ import generators # 2.2 compatibility
18 18
19 19 from IPython import Release
20 20 __author__ = '%s <%s>' % Release.authors['Fernando']
21 21 __license__ = Release.license
22 22
23 23 #****************************************************************************
24 24 # required modules from the Python standard library
25 25 import __main__
26 26 import commands
27 27 import os
28 28 import re
29 29 import shlex
30 30 import shutil
31 31 import sys
32 32 import tempfile
33 33 import time
34 34 import types
35 35
36 36 # Other IPython utilities
37 37 from IPython.Itpl import Itpl,itpl,printpl
38 38 from IPython import DPyGetOpt
39 39
40 40 if os.name == "nt":
41 41 from IPython.winconsole import get_console_size
42 42
43 43 # Build objects which appeared in Python 2.3 for 2.2, to make ipython
44 44 # 2.2-friendly
45 45 try:
46 46 basestring
47 47 except NameError:
48 48 import types
49 49 basestring = (types.StringType, types.UnicodeType)
50 50 True = 1==1
51 51 False = 1==0
52 52
53 53 def enumerate(obj):
54 54 i = -1
55 55 for item in obj:
56 56 i += 1
57 57 yield i, item
58 58
59 59 # add these to the builtin namespace, so that all modules find them
60 60 import __builtin__
61 61 __builtin__.basestring = basestring
62 62 __builtin__.True = True
63 63 __builtin__.False = False
64 64 __builtin__.enumerate = enumerate
65 65
66 66 # Try to use shlex.split for converting an input string into a sys.argv-type
67 67 # list. This appeared in Python 2.3, so here's a quick backport for 2.2.
68 68 try:
69 69 shlex_split = shlex.split
70 70 except AttributeError:
71 71 _quotesre = re.compile(r'[\'"](.*)[\'"]')
72 72 _wordchars = ('abcdfeghijklmnopqrstuvwxyz'
73 73 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-.~*?'
74 74 'ßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþÿ'
75 75 'ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞ%s'
76 76 % os.sep)
77 77
78 78 def shlex_split(s):
79 79 """Simplified backport to Python 2.2 of shlex.split().
80 80
81 81 This is a quick and dirty hack, since the shlex module under 2.2 lacks
82 82 several of the features needed to really match the functionality of
83 83 shlex.split() in 2.3."""
84 84
85 85 lex = shlex.shlex(StringIO(s))
86 86 # Try to get options, extensions and path separators as characters
87 87 lex.wordchars = _wordchars
88 88 lex.commenters = ''
89 89 # Make a list out of the lexer by hand, since in 2.2 it's not an
90 90 # iterator.
91 91 lout = []
92 92 while 1:
93 93 token = lex.get_token()
94 94 if token == '':
95 95 break
96 96 # Try to handle quoted tokens correctly
97 97 quotes = _quotesre.match(token)
98 98 if quotes:
99 99 token = quotes.group(1)
100 100 lout.append(token)
101 101 return lout
102 102
103 103 #****************************************************************************
104 104 # Exceptions
105 105 class Error(Exception):
106 106 """Base class for exceptions in this module."""
107 107 pass
108 108
109 109 #----------------------------------------------------------------------------
110 110 class IOStream:
111 111 def __init__(self,stream,fallback):
112 112 if not hasattr(stream,'write') or not hasattr(stream,'flush'):
113 113 stream = fallback
114 114 self.stream = stream
115 115 self._swrite = stream.write
116 116 self.flush = stream.flush
117 117
118 118 def write(self,data):
119 119 try:
120 120 self._swrite(data)
121 121 except:
122 122 try:
123 123 # print handles some unicode issues which may trip a plain
124 124 # write() call. Attempt to emulate write() by using a
125 125 # trailing comma
126 126 print >> self.stream, data,
127 127 except:
128 128 # if we get here, something is seriously broken.
129 129 print >> sys.stderr, \
130 130 'ERROR - failed to write data to stream:', stream
131 131
132 132 class IOTerm:
133 133 """ Term holds the file or file-like objects for handling I/O operations.
134 134
135 135 These are normally just sys.stdin, sys.stdout and sys.stderr but for
136 136 Windows they can can replaced to allow editing the strings before they are
137 137 displayed."""
138 138
139 139 # In the future, having IPython channel all its I/O operations through
140 140 # this class will make it easier to embed it into other environments which
141 141 # are not a normal terminal (such as a GUI-based shell)
142 142 def __init__(self,cin=None,cout=None,cerr=None):
143 143 self.cin = IOStream(cin,sys.stdin)
144 144 self.cout = IOStream(cout,sys.stdout)
145 145 self.cerr = IOStream(cerr,sys.stderr)
146 146
147 147 # Global variable to be used for all I/O
148 148 Term = IOTerm()
149 149
150 150 # Windows-specific code to load Gary Bishop's readline and configure it
151 151 # automatically for the users
152 152 # Note: os.name on cygwin returns posix, so this should only pick up 'native'
153 153 # windows. Cygwin returns 'cygwin' for sys.platform.
154 154 if os.name == 'nt':
155 155 try:
156 156 import readline
157 157 except ImportError:
158 158 pass
159 159 else:
160 160 try:
161 161 _out = readline.GetOutputFile()
162 162 except AttributeError:
163 163 pass
164 164 else:
165 165 # Remake Term to use the readline i/o facilities
166 166 Term = IOTerm(cout=_out,cerr=_out)
167 167 del _out
168 168
169 169 #****************************************************************************
170 170 # Generic warning/error printer, used by everything else
171 171 def warn(msg,level=2,exit_val=1):
172 172 """Standard warning printer. Gives formatting consistency.
173 173
174 174 Output is sent to Term.cerr (sys.stderr by default).
175 175
176 176 Options:
177 177
178 178 -level(2): allows finer control:
179 179 0 -> Do nothing, dummy function.
180 180 1 -> Print message.
181 181 2 -> Print 'WARNING:' + message. (Default level).
182 182 3 -> Print 'ERROR:' + message.
183 183 4 -> Print 'FATAL ERROR:' + message and trigger a sys.exit(exit_val).
184 184
185 185 -exit_val (1): exit value returned by sys.exit() for a level 4
186 186 warning. Ignored for all other levels."""
187 187
188 188 if level>0:
189 189 header = ['','','WARNING: ','ERROR: ','FATAL ERROR: ']
190 190 print >> Term.cerr, '%s%s' % (header[level],msg)
191 191 if level == 4:
192 192 print >> Term.cerr,'Exiting.\n'
193 193 sys.exit(exit_val)
194 194
195 195 def info(msg):
196 196 """Equivalent to warn(msg,level=1)."""
197 197
198 198 warn(msg,level=1)
199 199
200 200 def error(msg):
201 201 """Equivalent to warn(msg,level=3)."""
202 202
203 203 warn(msg,level=3)
204 204
205 205 def fatal(msg,exit_val=1):
206 206 """Equivalent to warn(msg,exit_val=exit_val,level=4)."""
207 207
208 208 warn(msg,exit_val=exit_val,level=4)
209 209
210 210
211 211 # useful for debugging
212 212 def debugp(expr):
213 213 """Print the value of an expression from the caller's frame.
214 214
215 215 Takes an expression, evaluates it in the caller's frame and prints both
216 216 the given expression and the resulting value. The input must be of a form
217 217 suitable for eval()."""
218 218
219 219 cf = sys._getframe(1)
220 220 print '[DBG] %s -> %r' % (expr,eval(expr,cf.f_globals,cf.f_locals))
221 221
222 222 #----------------------------------------------------------------------------
223 223 StringTypes = types.StringTypes
224 224
225 225 # Basic timing functionality
226 226
227 227 # If possible (Unix), use the resource module instead of time.clock()
228 228 try:
229 229 import resource
230 230 def clock():
231 231 """clock() -> floating point number
232 232
233 233 Return the CPU time in seconds (user time only, system time is
234 234 ignored) since the start of the process. This is done via a call to
235 235 resource.getrusage, so it avoids the wraparound problems in
236 236 time.clock()."""
237 237
238 238 return resource.getrusage(resource.RUSAGE_SELF)[0]
239 239
240 240 def clock2():
241 241 """clock2() -> (t_user,t_system)
242 242
243 243 Similar to clock(), but return a tuple of user/system times."""
244 244 return resource.getrusage(resource.RUSAGE_SELF)[:2]
245 245
246 246 except ImportError:
247 247 clock = time.clock
248 248 def clock2():
249 249 """Under windows, system CPU time can't be measured.
250 250
251 251 This just returns clock() and zero."""
252 252 return time.clock(),0.0
253 253
254 254 def timings_out(reps,func,*args,**kw):
255 255 """timings_out(reps,func,*args,**kw) -> (t_total,t_per_call,output)
256 256
257 257 Execute a function reps times, return a tuple with the elapsed total
258 258 CPU time in seconds, the time per call and the function's output.
259 259
260 260 Under Unix, the return value is the sum of user+system time consumed by
261 261 the process, computed via the resource module. This prevents problems
262 262 related to the wraparound effect which the time.clock() function has.
263 263
264 264 Under Windows the return value is in wall clock seconds. See the
265 265 documentation for the time module for more details."""
266 266
267 267 reps = int(reps)
268 268 assert reps >=1, 'reps must be >= 1'
269 269 if reps==1:
270 270 start = clock()
271 271 out = func(*args,**kw)
272 272 tot_time = clock()-start
273 273 else:
274 274 rng = xrange(reps-1) # the last time is executed separately to store output
275 275 start = clock()
276 276 for dummy in rng: func(*args,**kw)
277 277 out = func(*args,**kw) # one last time
278 278 tot_time = clock()-start
279 279 av_time = tot_time / reps
280 280 return tot_time,av_time,out
281 281
282 282 def timings(reps,func,*args,**kw):
283 283 """timings(reps,func,*args,**kw) -> (t_total,t_per_call)
284 284
285 285 Execute a function reps times, return a tuple with the elapsed total CPU
286 286 time in seconds and the time per call. These are just the first two values
287 287 in timings_out()."""
288 288
289 289 return timings_out(reps,func,*args,**kw)[0:2]
290 290
291 291 def timing(func,*args,**kw):
292 292 """timing(func,*args,**kw) -> t_total
293 293
294 294 Execute a function once, return the elapsed total CPU time in
295 295 seconds. This is just the first value in timings_out()."""
296 296
297 297 return timings_out(1,func,*args,**kw)[0]
298 298
299 299 #****************************************************************************
300 300 # file and system
301 301
302 302 def system(cmd,verbose=0,debug=0,header=''):
303 303 """Execute a system command, return its exit status.
304 304
305 305 Options:
306 306
307 307 - verbose (0): print the command to be executed.
308 308
309 309 - debug (0): only print, do not actually execute.
310 310
311 311 - header (''): Header to print on screen prior to the executed command (it
312 312 is only prepended to the command, no newlines are added).
313 313
314 314 Note: a stateful version of this function is available through the
315 315 SystemExec class."""
316 316
317 317 stat = 0
318 318 if verbose or debug: print header+cmd
319 319 sys.stdout.flush()
320 320 if not debug: stat = os.system(cmd)
321 321 return stat
322 322
323 323 # This function is used by ipython in a lot of places to make system calls.
324 324 # We need it to be slightly different under win32, due to the vagaries of
325 325 # 'network shares'. A win32 override is below.
326 326
327 327 def shell(cmd,verbose=0,debug=0,header=''):
328 328 """Execute a command in the system shell, always return None.
329 329
330 330 Options:
331 331
332 332 - verbose (0): print the command to be executed.
333 333
334 334 - debug (0): only print, do not actually execute.
335 335
336 336 - header (''): Header to print on screen prior to the executed command (it
337 337 is only prepended to the command, no newlines are added).
338 338
339 339 Note: this is similar to genutils.system(), but it returns None so it can
340 340 be conveniently used in interactive loops without getting the return value
341 341 (typically 0) printed many times."""
342 342
343 343 stat = 0
344 344 if verbose or debug: print header+cmd
345 345 # flush stdout so we don't mangle python's buffering
346 346 sys.stdout.flush()
347 347 if not debug:
348 348 os.system(cmd)
349 349
350 350 # override shell() for win32 to deal with network shares
351 351 if os.name in ('nt','dos'):
352 352
353 353 shell_ori = shell
354 354
355 355 def shell(cmd,verbose=0,debug=0,header=''):
356 356 if os.getcwd().startswith(r"\\"):
357 357 path = os.getcwd()
358 358 # change to c drive (cannot be on UNC-share when issuing os.system,
359 359 # as cmd.exe cannot handle UNC addresses)
360 360 os.chdir("c:")
361 361 # issue pushd to the UNC-share and then run the command
362 362 try:
363 363 shell_ori('"pushd %s&&"'%path+cmd,verbose,debug,header)
364 364 finally:
365 365 os.chdir(path)
366 366 else:
367 367 shell_ori(cmd,verbose,debug,header)
368 368
369 369 shell.__doc__ = shell_ori.__doc__
370 370
371 371 def getoutput(cmd,verbose=0,debug=0,header='',split=0):
372 372 """Dummy substitute for perl's backquotes.
373 373
374 374 Executes a command and returns the output.
375 375
376 376 Accepts the same arguments as system(), plus:
377 377
378 378 - split(0): if true, the output is returned as a list split on newlines.
379 379
380 380 Note: a stateful version of this function is available through the
381 381 SystemExec class."""
382 382
383 383 if verbose or debug: print header+cmd
384 384 if not debug:
385 385 output = commands.getoutput(cmd)
386 386 if split:
387 387 return output.split('\n')
388 388 else:
389 389 return output
390 390
391 391 def getoutputerror(cmd,verbose=0,debug=0,header='',split=0):
392 392 """Return (standard output,standard error) of executing cmd in a shell.
393 393
394 394 Accepts the same arguments as system(), plus:
395 395
396 396 - split(0): if true, each of stdout/err is returned as a list split on
397 397 newlines.
398 398
399 399 Note: a stateful version of this function is available through the
400 400 SystemExec class."""
401 401
402 402 if verbose or debug: print header+cmd
403 403 if not cmd:
404 404 if split:
405 405 return [],[]
406 406 else:
407 407 return '',''
408 408 if not debug:
409 409 pin,pout,perr = os.popen3(cmd)
410 410 tout = pout.read().rstrip()
411 411 terr = perr.read().rstrip()
412 412 pin.close()
413 413 pout.close()
414 414 perr.close()
415 415 if split:
416 416 return tout.split('\n'),terr.split('\n')
417 417 else:
418 418 return tout,terr
419 419
420 420 # for compatibility with older naming conventions
421 421 xsys = system
422 422 bq = getoutput
423 423
424 424 class SystemExec:
425 425 """Access the system and getoutput functions through a stateful interface.
426 426
427 427 Note: here we refer to the system and getoutput functions from this
428 428 library, not the ones from the standard python library.
429 429
430 430 This class offers the system and getoutput functions as methods, but the
431 431 verbose, debug and header parameters can be set for the instance (at
432 432 creation time or later) so that they don't need to be specified on each
433 433 call.
434 434
435 435 For efficiency reasons, there's no way to override the parameters on a
436 436 per-call basis other than by setting instance attributes. If you need
437 437 local overrides, it's best to directly call system() or getoutput().
438 438
439 439 The following names are provided as alternate options:
440 440 - xsys: alias to system
441 441 - bq: alias to getoutput
442 442
443 443 An instance can then be created as:
444 444 >>> sysexec = SystemExec(verbose=1,debug=0,header='Calling: ')
445 445
446 446 And used as:
447 447 >>> sysexec.xsys('pwd')
448 448 >>> dirlist = sysexec.bq('ls -l')
449 449 """
450 450
451 451 def __init__(self,verbose=0,debug=0,header='',split=0):
452 452 """Specify the instance's values for verbose, debug and header."""
453 453 setattr_list(self,'verbose debug header split')
454 454
455 455 def system(self,cmd):
456 456 """Stateful interface to system(), with the same keyword parameters."""
457 457
458 458 system(cmd,self.verbose,self.debug,self.header)
459 459
460 460 def shell(self,cmd):
461 461 """Stateful interface to shell(), with the same keyword parameters."""
462 462
463 463 shell(cmd,self.verbose,self.debug,self.header)
464 464
465 465 xsys = system # alias
466 466
467 467 def getoutput(self,cmd):
468 468 """Stateful interface to getoutput()."""
469 469
470 470 return getoutput(cmd,self.verbose,self.debug,self.header,self.split)
471 471
472 472 def getoutputerror(self,cmd):
473 473 """Stateful interface to getoutputerror()."""
474 474
475 475 return getoutputerror(cmd,self.verbose,self.debug,self.header,self.split)
476 476
477 477 bq = getoutput # alias
478 478
479 479 #-----------------------------------------------------------------------------
480 480 def mutex_opts(dict,ex_op):
481 481 """Check for presence of mutually exclusive keys in a dict.
482 482
483 483 Call: mutex_opts(dict,[[op1a,op1b],[op2a,op2b]...]"""
484 484 for op1,op2 in ex_op:
485 485 if op1 in dict and op2 in dict:
486 486 raise ValueError,'\n*** ERROR in Arguments *** '\
487 487 'Options '+op1+' and '+op2+' are mutually exclusive.'
488 488
489 489 #-----------------------------------------------------------------------------
490 490 def get_py_filename(name):
491 491 """Return a valid python filename in the current directory.
492 492
493 493 If the given name is not a file, it adds '.py' and searches again.
494 494 Raises IOError with an informative message if the file isn't found."""
495 495
496 496 name = os.path.expanduser(name)
497 497 if not os.path.isfile(name) and not name.endswith('.py'):
498 498 name += '.py'
499 499 if os.path.isfile(name):
500 500 return name
501 501 else:
502 502 raise IOError,'File `%s` not found.' % name
503 503
504 504 #-----------------------------------------------------------------------------
505 505 def filefind(fname,alt_dirs = None):
506 506 """Return the given filename either in the current directory, if it
507 507 exists, or in a specified list of directories.
508 508
509 509 ~ expansion is done on all file and directory names.
510 510
511 511 Upon an unsuccessful search, raise an IOError exception."""
512 512
513 513 if alt_dirs is None:
514 514 try:
515 515 alt_dirs = get_home_dir()
516 516 except HomeDirError:
517 517 alt_dirs = os.getcwd()
518 518 search = [fname] + list_strings(alt_dirs)
519 519 search = map(os.path.expanduser,search)
520 520 #print 'search list for',fname,'list:',search # dbg
521 521 fname = search[0]
522 522 if os.path.isfile(fname):
523 523 return fname
524 524 for direc in search[1:]:
525 525 testname = os.path.join(direc,fname)
526 526 #print 'testname',testname # dbg
527 527 if os.path.isfile(testname):
528 528 return testname
529 529 raise IOError,'File' + `fname` + \
530 530 ' not found in current or supplied directories:' + `alt_dirs`
531 531
532 532 #----------------------------------------------------------------------------
533 533 def file_read(filename):
534 534 """Read a file and close it. Returns the file source."""
535 535 fobj=open(filename,'r');
536 536 source = fobj.read();
537 537 fobj.close()
538 538 return source
539 539
540 540 #----------------------------------------------------------------------------
541 541 def target_outdated(target,deps):
542 542 """Determine whether a target is out of date.
543 543
544 544 target_outdated(target,deps) -> 1/0
545 545
546 546 deps: list of filenames which MUST exist.
547 547 target: single filename which may or may not exist.
548 548
549 549 If target doesn't exist or is older than any file listed in deps, return
550 550 true, otherwise return false.
551 551 """
552 552 try:
553 553 target_time = os.path.getmtime(target)
554 554 except os.error:
555 555 return 1
556 556 for dep in deps:
557 557 dep_time = os.path.getmtime(dep)
558 558 if dep_time > target_time:
559 559 #print "For target",target,"Dep failed:",dep # dbg
560 560 #print "times (dep,tar):",dep_time,target_time # dbg
561 561 return 1
562 562 return 0
563 563
564 564 #-----------------------------------------------------------------------------
565 565 def target_update(target,deps,cmd):
566 566 """Update a target with a given command given a list of dependencies.
567 567
568 568 target_update(target,deps,cmd) -> runs cmd if target is outdated.
569 569
570 570 This is just a wrapper around target_outdated() which calls the given
571 571 command if target is outdated."""
572 572
573 573 if target_outdated(target,deps):
574 574 xsys(cmd)
575 575
576 576 #----------------------------------------------------------------------------
577 577 def unquote_ends(istr):
578 578 """Remove a single pair of quotes from the endpoints of a string."""
579 579
580 580 if not istr:
581 581 return istr
582 582 if (istr[0]=="'" and istr[-1]=="'") or \
583 583 (istr[0]=='"' and istr[-1]=='"'):
584 584 return istr[1:-1]
585 585 else:
586 586 return istr
587 587
588 588 #----------------------------------------------------------------------------
589 589 def process_cmdline(argv,names=[],defaults={},usage=''):
590 590 """ Process command-line options and arguments.
591 591
592 592 Arguments:
593 593
594 594 - argv: list of arguments, typically sys.argv.
595 595
596 596 - names: list of option names. See DPyGetOpt docs for details on options
597 597 syntax.
598 598
599 599 - defaults: dict of default values.
600 600
601 601 - usage: optional usage notice to print if a wrong argument is passed.
602 602
603 603 Return a dict of options and a list of free arguments."""
604 604
605 605 getopt = DPyGetOpt.DPyGetOpt()
606 606 getopt.setIgnoreCase(0)
607 607 getopt.parseConfiguration(names)
608 608
609 609 try:
610 610 getopt.processArguments(argv)
611 611 except:
612 612 print usage
613 613 warn(`sys.exc_value`,level=4)
614 614
615 615 defaults.update(getopt.optionValues)
616 616 args = getopt.freeValues
617 617
618 618 return defaults,args
619 619
620 620 #----------------------------------------------------------------------------
621 621 def optstr2types(ostr):
622 622 """Convert a string of option names to a dict of type mappings.
623 623
624 624 optstr2types(str) -> {None:'string_opts',int:'int_opts',float:'float_opts'}
625 625
626 626 This is used to get the types of all the options in a string formatted
627 627 with the conventions of DPyGetOpt. The 'type' None is used for options
628 628 which are strings (they need no further conversion). This function's main
629 629 use is to get a typemap for use with read_dict().
630 630 """
631 631
632 632 typeconv = {None:'',int:'',float:''}
633 633 typemap = {'s':None,'i':int,'f':float}
634 634 opt_re = re.compile(r'([\w]*)([^:=]*:?=?)([sif]?)')
635 635
636 636 for w in ostr.split():
637 637 oname,alias,otype = opt_re.match(w).groups()
638 638 if otype == '' or alias == '!': # simple switches are integers too
639 639 otype = 'i'
640 640 typeconv[typemap[otype]] += oname + ' '
641 641 return typeconv
642 642
643 643 #----------------------------------------------------------------------------
644 644 def read_dict(filename,type_conv=None,**opt):
645 645
646 646 """Read a dictionary of key=value pairs from an input file, optionally
647 647 performing conversions on the resulting values.
648 648
649 649 read_dict(filename,type_conv,**opt) -> dict
650 650
651 651 Only one value per line is accepted, the format should be
652 652 # optional comments are ignored
653 653 key value\n
654 654
655 655 Args:
656 656
657 657 - type_conv: A dictionary specifying which keys need to be converted to
658 658 which types. By default all keys are read as strings. This dictionary
659 659 should have as its keys valid conversion functions for strings
660 660 (int,long,float,complex, or your own). The value for each key
661 661 (converter) should be a whitespace separated string containing the names
662 662 of all the entries in the file to be converted using that function. For
663 663 keys to be left alone, use None as the conversion function (only needed
664 664 with purge=1, see below).
665 665
666 666 - opt: dictionary with extra options as below (default in parens)
667 667
668 668 purge(0): if set to 1, all keys *not* listed in type_conv are purged out
669 669 of the dictionary to be returned. If purge is going to be used, the
670 670 set of keys to be left as strings also has to be explicitly specified
671 671 using the (non-existent) conversion function None.
672 672
673 673 fs(None): field separator. This is the key/value separator to be used
674 674 when parsing the file. The None default means any whitespace [behavior
675 675 of string.split()].
676 676
677 677 strip(0): if 1, strip string values of leading/trailinig whitespace.
678 678
679 679 warn(1): warning level if requested keys are not found in file.
680 680 - 0: silently ignore.
681 681 - 1: inform but proceed.
682 682 - 2: raise KeyError exception.
683 683
684 684 no_empty(0): if 1, remove keys with whitespace strings as a value.
685 685
686 686 unique([]): list of keys (or space separated string) which can't be
687 687 repeated. If one such key is found in the file, each new instance
688 688 overwrites the previous one. For keys not listed here, the behavior is
689 689 to make a list of all appearances.
690 690
691 691 Example:
692 692 If the input file test.ini has:
693 693 i 3
694 694 x 4.5
695 695 y 5.5
696 696 s hi ho
697 697 Then:
698 698
699 699 >>> type_conv={int:'i',float:'x',None:'s'}
700 700 >>> read_dict('test.ini')
701 701 {'i': '3', 's': 'hi ho', 'x': '4.5', 'y': '5.5'}
702 702 >>> read_dict('test.ini',type_conv)
703 703 {'i': 3, 's': 'hi ho', 'x': 4.5, 'y': '5.5'}
704 704 >>> read_dict('test.ini',type_conv,purge=1)
705 705 {'i': 3, 's': 'hi ho', 'x': 4.5}
706 706 """
707 707
708 708 # starting config
709 709 opt.setdefault('purge',0)
710 710 opt.setdefault('fs',None) # field sep defaults to any whitespace
711 711 opt.setdefault('strip',0)
712 712 opt.setdefault('warn',1)
713 713 opt.setdefault('no_empty',0)
714 714 opt.setdefault('unique','')
715 715 if type(opt['unique']) in StringTypes:
716 716 unique_keys = qw(opt['unique'])
717 717 elif type(opt['unique']) in (types.TupleType,types.ListType):
718 718 unique_keys = opt['unique']
719 719 else:
720 720 raise ValueError, 'Unique keys must be given as a string, List or Tuple'
721 721
722 722 dict = {}
723 723 # first read in table of values as strings
724 724 file = open(filename,'r')
725 725 for line in file.readlines():
726 726 line = line.strip()
727 727 if len(line) and line[0]=='#': continue
728 728 if len(line)>0:
729 729 lsplit = line.split(opt['fs'],1)
730 730 try:
731 731 key,val = lsplit
732 732 except ValueError:
733 733 key,val = lsplit[0],''
734 734 key = key.strip()
735 735 if opt['strip']: val = val.strip()
736 736 if val == "''" or val == '""': val = ''
737 737 if opt['no_empty'] and (val=='' or val.isspace()):
738 738 continue
739 739 # if a key is found more than once in the file, build a list
740 740 # unless it's in the 'unique' list. In that case, last found in file
741 741 # takes precedence. User beware.
742 742 try:
743 743 if dict[key] and key in unique_keys:
744 744 dict[key] = val
745 745 elif type(dict[key]) is types.ListType:
746 746 dict[key].append(val)
747 747 else:
748 748 dict[key] = [dict[key],val]
749 749 except KeyError:
750 750 dict[key] = val
751 751 # purge if requested
752 752 if opt['purge']:
753 753 accepted_keys = qwflat(type_conv.values())
754 754 for key in dict.keys():
755 755 if key in accepted_keys: continue
756 756 del(dict[key])
757 757 # now convert if requested
758 758 if type_conv==None: return dict
759 759 conversions = type_conv.keys()
760 760 try: conversions.remove(None)
761 761 except: pass
762 762 for convert in conversions:
763 763 for val in qw(type_conv[convert]):
764 764 try:
765 765 dict[val] = convert(dict[val])
766 766 except KeyError,e:
767 767 if opt['warn'] == 0:
768 768 pass
769 769 elif opt['warn'] == 1:
770 770 print >>sys.stderr, 'Warning: key',val,\
771 771 'not found in file',filename
772 772 elif opt['warn'] == 2:
773 773 raise KeyError,e
774 774 else:
775 775 raise ValueError,'Warning level must be 0,1 or 2'
776 776
777 777 return dict
778 778
779 779 #----------------------------------------------------------------------------
780 780 def flag_calls(func):
781 781 """Wrap a function to detect and flag when it gets called.
782 782
783 783 This is a decorator which takes a function and wraps it in a function with
784 784 a 'called' attribute. wrapper.called is initialized to False.
785 785
786 786 The wrapper.called attribute is set to False right before each call to the
787 787 wrapped function, so if the call fails it remains False. After the call
788 788 completes, wrapper.called is set to True and the output is returned.
789 789
790 790 Testing for truth in wrapper.called allows you to determine if a call to
791 791 func() was attempted and succeeded."""
792 792
793 793 def wrapper(*args,**kw):
794 794 wrapper.called = False
795 795 out = func(*args,**kw)
796 796 wrapper.called = True
797 797 return out
798 798
799 799 wrapper.called = False
800 800 wrapper.__doc__ = func.__doc__
801 801 return wrapper
802 802
803 803 #----------------------------------------------------------------------------
804 804 class HomeDirError(Error):
805 805 pass
806 806
807 807 def get_home_dir():
808 808 """Return the closest possible equivalent to a 'home' directory.
809 809
810 810 We first try $HOME. Absent that, on NT it's $HOMEDRIVE\$HOMEPATH.
811 811
812 812 Currently only Posix and NT are implemented, a HomeDirError exception is
813 813 raised for all other OSes. """
814 814
815 815 isdir = os.path.isdir
816 816 env = os.environ
817 817 try:
818 818 homedir = env['HOME']
819 819 if not isdir(homedir):
820 820 # in case a user stuck some string which does NOT resolve to a
821 821 # valid path, it's as good as if we hadn't foud it
822 822 raise KeyError
823 823 return homedir
824 824 except KeyError:
825 825 if os.name == 'posix':
826 826 raise HomeDirError,'undefined $HOME, IPython can not proceed.'
827 827 elif os.name == 'nt':
828 828 # For some strange reason, win9x returns 'nt' for os.name.
829 829 try:
830 830 homedir = os.path.join(env['HOMEDRIVE'],env['HOMEPATH'])
831 831 if not isdir(homedir):
832 832 homedir = os.path.join(env['USERPROFILE'])
833 833 if not isdir(homedir):
834 834 raise HomeDirError
835 835 return homedir
836 836 except:
837 837 try:
838 838 # Use the registry to get the 'My Documents' folder.
839 839 import _winreg as wreg
840 840 key = wreg.OpenKey(wreg.HKEY_CURRENT_USER,
841 841 "Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders")
842 842 homedir = wreg.QueryValueEx(key,'Personal')[0]
843 843 key.Close()
844 844 if not isdir(homedir):
845 845 e = ('Invalid "Personal" folder registry key '
846 846 'typically "My Documents".\n'
847 847 'Value: %s\n'
848 848 'This is not a valid directory on your system.' %
849 849 homedir)
850 850 raise HomeDirError(e)
851 851 return homedir
852 852 except HomeDirError:
853 853 raise
854 854 except:
855 855 return 'C:\\'
856 856 elif os.name == 'dos':
857 857 # Desperate, may do absurd things in classic MacOS. May work under DOS.
858 858 return 'C:\\'
859 859 else:
860 860 raise HomeDirError,'support for your operating system not implemented.'
861 861
862 862 #****************************************************************************
863 863 # strings and text
864 864
865 865 class LSString(str):
866 866 """String derivative with a special access attributes.
867 867
868 868 These are normal strings, but with the special attributes:
869 869
870 870 .l (or .list) : value as list (split on newlines).
871 871 .n (or .nlstr): original value (the string itself).
872 872 .s (or .spstr): value as whitespace-separated string.
873 873
874 874 Any values which require transformations are computed only once and
875 875 cached.
876 876
877 877 Such strings are very useful to efficiently interact with the shell, which
878 878 typically only understands whitespace-separated options for commands."""
879 879
880 880 def get_list(self):
881 881 try:
882 882 return self.__list
883 883 except AttributeError:
884 884 self.__list = self.split('\n')
885 885 return self.__list
886 886
887 887 l = list = property(get_list)
888 888
889 889 def get_spstr(self):
890 890 try:
891 891 return self.__spstr
892 892 except AttributeError:
893 893 self.__spstr = self.replace('\n',' ')
894 894 return self.__spstr
895 895
896 896 s = spstr = property(get_spstr)
897 897
898 898 def get_nlstr(self):
899 899 return self
900 900
901 901 n = nlstr = property(get_nlstr)
902 902
903 903 #----------------------------------------------------------------------------
904 904 class SList(list):
905 905 """List derivative with a special access attributes.
906 906
907 907 These are normal lists, but with the special attributes:
908 908
909 909 .l (or .list) : value as list (the list itself).
910 910 .n (or .nlstr): value as a string, joined on newlines.
911 911 .s (or .spstr): value as a string, joined on spaces.
912 912
913 913 Any values which require transformations are computed only once and
914 914 cached."""
915 915
916 916 def get_list(self):
917 917 return self
918 918
919 919 l = list = property(get_list)
920 920
921 921 def get_spstr(self):
922 922 try:
923 923 return self.__spstr
924 924 except AttributeError:
925 925 self.__spstr = ' '.join(self)
926 926 return self.__spstr
927 927
928 928 s = spstr = property(get_spstr)
929 929
930 930 def get_nlstr(self):
931 931 try:
932 932 return self.__nlstr
933 933 except AttributeError:
934 934 self.__nlstr = '\n'.join(self)
935 935 return self.__nlstr
936 936
937 937 n = nlstr = property(get_nlstr)
938 938
939 939 #----------------------------------------------------------------------------
940 # This can be replaced with an isspace() call once we drop 2.2 compatibility
941 _isspace_match = re.compile(r'^\s+$').match
942 def isspace(s):
943 return bool(_isspace_match(s))
944
945 #----------------------------------------------------------------------------
946 940 def esc_quotes(strng):
947 941 """Return the input string with single and double quotes escaped out"""
948 942
949 943 return strng.replace('"','\\"').replace("'","\\'")
950 944
951 945 #----------------------------------------------------------------------------
952 946 def make_quoted_expr(s):
953 947 """Return string s in appropriate quotes, using raw string if possible.
954 948
955 949 Effectively this turns string: cd \ao\ao\
956 950 to: r"cd \ao\ao\_"[:-1]
957 951
958 952 Note the use of raw string and padding at the end to allow trailing backslash.
959 953
960 954 """
961 955
962 956 tail = ''
963 957 tailpadding = ''
964 958 raw = ''
965 959 if "\\" in s:
966 960 raw = 'r'
967 961 if s.endswith('\\'):
968 962 tail = '[:-1]'
969 963 tailpadding = '_'
970 964 if '"' not in s:
971 965 quote = '"'
972 966 elif "'" not in s:
973 967 quote = "'"
974 968 elif '"""' not in s and not s.endswith('"'):
975 969 quote = '"""'
976 970 elif "'''" not in s and not s.endswith("'"):
977 971 quote = "'''"
978 972 else:
979 973 # give up, backslash-escaped string will do
980 974 return '"%s"' % esc_quotes(s)
981 975 res = itpl("$raw$quote$s$tailpadding$quote$tail")
982 976 return res
983 977
984 978
985 979 #----------------------------------------------------------------------------
986 980 def raw_input_multi(header='', ps1='==> ', ps2='..> ',terminate_str = '.'):
987 981 """Take multiple lines of input.
988 982
989 983 A list with each line of input as a separate element is returned when a
990 984 termination string is entered (defaults to a single '.'). Input can also
991 985 terminate via EOF (^D in Unix, ^Z-RET in Windows).
992 986
993 987 Lines of input which end in \\ are joined into single entries (and a
994 988 secondary continuation prompt is issued as long as the user terminates
995 989 lines with \\). This allows entering very long strings which are still
996 990 meant to be treated as single entities.
997 991 """
998 992
999 993 try:
1000 994 if header:
1001 995 header += '\n'
1002 996 lines = [raw_input(header + ps1)]
1003 997 except EOFError:
1004 998 return []
1005 999 terminate = [terminate_str]
1006 1000 try:
1007 1001 while lines[-1:] != terminate:
1008 1002 new_line = raw_input(ps1)
1009 1003 while new_line.endswith('\\'):
1010 1004 new_line = new_line[:-1] + raw_input(ps2)
1011 1005 lines.append(new_line)
1012 1006
1013 1007 return lines[:-1] # don't return the termination command
1014 1008 except EOFError:
1015 1009 print
1016 1010 return lines
1017 1011
1018 1012 #----------------------------------------------------------------------------
1019 1013 def raw_input_ext(prompt='', ps2='... '):
1020 1014 """Similar to raw_input(), but accepts extended lines if input ends with \\."""
1021 1015
1022 1016 line = raw_input(prompt)
1023 1017 while line.endswith('\\'):
1024 1018 line = line[:-1] + raw_input(ps2)
1025 1019 return line
1026 1020
1027 1021 #----------------------------------------------------------------------------
1028 1022 def ask_yes_no(prompt,default=None):
1029 1023 """Asks a question and returns an integer 1/0 (y/n) answer.
1030 1024
1031 1025 If default is given (one of 'y','n'), it is used if the user input is
1032 1026 empty. Otherwise the question is repeated until an answer is given.
1033 1027 If EOF occurs 20 times consecutively, the default answer is assumed,
1034 1028 or if there is no default, an exception is raised to prevent infinite
1035 1029 loops.
1036 1030
1037 1031 Valid answers are: y/yes/n/no (match is not case sensitive)."""
1038 1032
1039 1033 answers = {'y':True,'n':False,'yes':True,'no':False}
1040 1034 ans = None
1041 1035 eofs, max_eofs = 0, 20
1042 1036 while ans not in answers.keys():
1043 1037 try:
1044 1038 ans = raw_input(prompt+' ').lower()
1045 1039 if not ans: # response was an empty string
1046 1040 ans = default
1047 1041 eofs = 0
1048 1042 except (EOFError,KeyboardInterrupt):
1049 1043 eofs = eofs + 1
1050 1044 if eofs >= max_eofs:
1051 1045 if default in answers.keys():
1052 1046 ans = default
1053 1047 else:
1054 1048 raise
1055 1049
1056 1050 return answers[ans]
1057 1051
1058 1052 #----------------------------------------------------------------------------
1059 1053 def marquee(txt='',width=78,mark='*'):
1060 1054 """Return the input string centered in a 'marquee'."""
1061 1055 if not txt:
1062 1056 return (mark*width)[:width]
1063 1057 nmark = (width-len(txt)-2)/len(mark)/2
1064 1058 if nmark < 0: nmark =0
1065 1059 marks = mark*nmark
1066 1060 return '%s %s %s' % (marks,txt,marks)
1067 1061
1068 1062 #----------------------------------------------------------------------------
1069 1063 class EvalDict:
1070 1064 """
1071 1065 Emulate a dict which evaluates its contents in the caller's frame.
1072 1066
1073 1067 Usage:
1074 1068 >>>number = 19
1075 1069 >>>text = "python"
1076 1070 >>>print "%(text.capitalize())s %(number/9.0).1f rules!" % EvalDict()
1077 1071 """
1078 1072
1079 1073 # This version is due to sismex01@hebmex.com on c.l.py, and is basically a
1080 1074 # modified (shorter) version of:
1081 1075 # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66018 by
1082 1076 # Skip Montanaro (skip@pobox.com).
1083 1077
1084 1078 def __getitem__(self, name):
1085 1079 frame = sys._getframe(1)
1086 1080 return eval(name, frame.f_globals, frame.f_locals)
1087 1081
1088 1082 EvalString = EvalDict # for backwards compatibility
1089 1083 #----------------------------------------------------------------------------
1090 1084 def qw(words,flat=0,sep=None,maxsplit=-1):
1091 1085 """Similar to Perl's qw() operator, but with some more options.
1092 1086
1093 1087 qw(words,flat=0,sep=' ',maxsplit=-1) -> words.split(sep,maxsplit)
1094 1088
1095 1089 words can also be a list itself, and with flat=1, the output will be
1096 1090 recursively flattened. Examples:
1097 1091
1098 1092 >>> qw('1 2')
1099 1093 ['1', '2']
1100 1094 >>> qw(['a b','1 2',['m n','p q']])
1101 1095 [['a', 'b'], ['1', '2'], [['m', 'n'], ['p', 'q']]]
1102 1096 >>> qw(['a b','1 2',['m n','p q']],flat=1)
1103 1097 ['a', 'b', '1', '2', 'm', 'n', 'p', 'q'] """
1104 1098
1105 1099 if type(words) in StringTypes:
1106 1100 return [word.strip() for word in words.split(sep,maxsplit)
1107 1101 if word and not word.isspace() ]
1108 1102 if flat:
1109 1103 return flatten(map(qw,words,[1]*len(words)))
1110 1104 return map(qw,words)
1111 1105
1112 1106 #----------------------------------------------------------------------------
1113 1107 def qwflat(words,sep=None,maxsplit=-1):
1114 1108 """Calls qw(words) in flat mode. It's just a convenient shorthand."""
1115 1109 return qw(words,1,sep,maxsplit)
1116 1110
1117 1111 #----------------------------------------------------------------------------
1118 1112 def qw_lol(indata):
1119 1113 """qw_lol('a b') -> [['a','b']],
1120 1114 otherwise it's just a call to qw().
1121 1115
1122 1116 We need this to make sure the modules_some keys *always* end up as a
1123 1117 list of lists."""
1124 1118
1125 1119 if type(indata) in StringTypes:
1126 1120 return [qw(indata)]
1127 1121 else:
1128 1122 return qw(indata)
1129 1123
1130 1124 #-----------------------------------------------------------------------------
1131 1125 def list_strings(arg):
1132 1126 """Always return a list of strings, given a string or list of strings
1133 1127 as input."""
1134 1128
1135 1129 if type(arg) in StringTypes: return [arg]
1136 1130 else: return arg
1137 1131
1138 1132 #----------------------------------------------------------------------------
1139 1133 def grep(pat,list,case=1):
1140 1134 """Simple minded grep-like function.
1141 1135 grep(pat,list) returns occurrences of pat in list, None on failure.
1142 1136
1143 1137 It only does simple string matching, with no support for regexps. Use the
1144 1138 option case=0 for case-insensitive matching."""
1145 1139
1146 1140 # This is pretty crude. At least it should implement copying only references
1147 1141 # to the original data in case it's big. Now it copies the data for output.
1148 1142 out=[]
1149 1143 if case:
1150 1144 for term in list:
1151 1145 if term.find(pat)>-1: out.append(term)
1152 1146 else:
1153 1147 lpat=pat.lower()
1154 1148 for term in list:
1155 1149 if term.lower().find(lpat)>-1: out.append(term)
1156 1150
1157 1151 if len(out): return out
1158 1152 else: return None
1159 1153
1160 1154 #----------------------------------------------------------------------------
1161 1155 def dgrep(pat,*opts):
1162 1156 """Return grep() on dir()+dir(__builtins__).
1163 1157
1164 1158 A very common use of grep() when working interactively."""
1165 1159
1166 1160 return grep(pat,dir(__main__)+dir(__main__.__builtins__),*opts)
1167 1161
1168 1162 #----------------------------------------------------------------------------
1169 1163 def idgrep(pat):
1170 1164 """Case-insensitive dgrep()"""
1171 1165
1172 1166 return dgrep(pat,0)
1173 1167
1174 1168 #----------------------------------------------------------------------------
1175 1169 def igrep(pat,list):
1176 1170 """Synonym for case-insensitive grep."""
1177 1171
1178 1172 return grep(pat,list,case=0)
1179 1173
1180 1174 #----------------------------------------------------------------------------
1181 1175 def indent(str,nspaces=4,ntabs=0):
1182 1176 """Indent a string a given number of spaces or tabstops.
1183 1177
1184 1178 indent(str,nspaces=4,ntabs=0) -> indent str by ntabs+nspaces.
1185 1179 """
1186 1180 if str is None:
1187 1181 return
1188 1182 ind = '\t'*ntabs+' '*nspaces
1189 1183 outstr = '%s%s' % (ind,str.replace(os.linesep,os.linesep+ind))
1190 1184 if outstr.endswith(os.linesep+ind):
1191 1185 return outstr[:-len(ind)]
1192 1186 else:
1193 1187 return outstr
1194 1188
1195 1189 #-----------------------------------------------------------------------------
1196 1190 def native_line_ends(filename,backup=1):
1197 1191 """Convert (in-place) a file to line-ends native to the current OS.
1198 1192
1199 1193 If the optional backup argument is given as false, no backup of the
1200 1194 original file is left. """
1201 1195
1202 1196 backup_suffixes = {'posix':'~','dos':'.bak','nt':'.bak','mac':'.bak'}
1203 1197
1204 1198 bak_filename = filename + backup_suffixes[os.name]
1205 1199
1206 1200 original = open(filename).read()
1207 1201 shutil.copy2(filename,bak_filename)
1208 1202 try:
1209 1203 new = open(filename,'wb')
1210 1204 new.write(os.linesep.join(original.splitlines()))
1211 1205 new.write(os.linesep) # ALWAYS put an eol at the end of the file
1212 1206 new.close()
1213 1207 except:
1214 1208 os.rename(bak_filename,filename)
1215 1209 if not backup:
1216 1210 try:
1217 1211 os.remove(bak_filename)
1218 1212 except:
1219 1213 pass
1220 1214
1221 1215 #----------------------------------------------------------------------------
1222 1216 def get_pager_cmd(pager_cmd = None):
1223 1217 """Return a pager command.
1224 1218
1225 1219 Makes some attempts at finding an OS-correct one."""
1226 1220
1227 1221 if os.name == 'posix':
1228 1222 default_pager_cmd = 'less -r' # -r for color control sequences
1229 1223 elif os.name in ['nt','dos']:
1230 1224 default_pager_cmd = 'type'
1231 1225
1232 1226 if pager_cmd is None:
1233 1227 try:
1234 1228 pager_cmd = os.environ['PAGER']
1235 1229 except:
1236 1230 pager_cmd = default_pager_cmd
1237 1231 return pager_cmd
1238 1232
1239 1233 #-----------------------------------------------------------------------------
1240 1234 def get_pager_start(pager,start):
1241 1235 """Return the string for paging files with an offset.
1242 1236
1243 1237 This is the '+N' argument which less and more (under Unix) accept.
1244 1238 """
1245 1239
1246 1240 if pager in ['less','more']:
1247 1241 if start:
1248 1242 start_string = '+' + str(start)
1249 1243 else:
1250 1244 start_string = ''
1251 1245 else:
1252 1246 start_string = ''
1253 1247 return start_string
1254 1248
1255 1249 #----------------------------------------------------------------------------
1256 1250 if os.name == "nt":
1257 1251 import msvcrt
1258 1252 def page_more():
1259 1253 """ Smart pausing between pages
1260 1254
1261 1255 @return: True if need print more lines, False if quit
1262 1256 """
1263 1257 Term.cout.write('---Return to continue, q to quit--- ')
1264 1258 ans = msvcrt.getch()
1265 1259 if ans in ("q", "Q"):
1266 1260 result = False
1267 1261 else:
1268 1262 result = True
1269 1263 Term.cout.write("\b"*37 + " "*37 + "\b"*37)
1270 1264 return result
1271 1265 else:
1272 1266 def page_more():
1273 1267 ans = raw_input('---Return to continue, q to quit--- ')
1274 1268 if ans.lower().startswith('q'):
1275 1269 return False
1276 1270 else:
1277 1271 return True
1278 1272
1279 1273 esc_re = re.compile(r"(\x1b[^m]+m)")
1280 1274
1281 1275 def page_dumb(strng,start=0,screen_lines=25):
1282 1276 """Very dumb 'pager' in Python, for when nothing else works.
1283 1277
1284 1278 Only moves forward, same interface as page(), except for pager_cmd and
1285 1279 mode."""
1286 1280
1287 1281 out_ln = strng.splitlines()[start:]
1288 1282 screens = chop(out_ln,screen_lines-1)
1289 1283 if len(screens) == 1:
1290 1284 print >>Term.cout, os.linesep.join(screens[0])
1291 1285 else:
1292 1286 last_escape = ""
1293 1287 for scr in screens[0:-1]:
1294 1288 hunk = os.linesep.join(scr)
1295 1289 print >>Term.cout, last_escape + hunk
1296 1290 if not page_more():
1297 1291 return
1298 1292 esc_list = esc_re.findall(hunk)
1299 1293 if len(esc_list) > 0:
1300 1294 last_escape = esc_list[-1]
1301 1295 print >>Term.cout, last_escape + os.linesep.join(screens[-1])
1302 1296
1303 1297 #----------------------------------------------------------------------------
1304 1298 def page(strng,start=0,screen_lines=0,pager_cmd = None):
1305 1299 """Print a string, piping through a pager after a certain length.
1306 1300
1307 1301 The screen_lines parameter specifies the number of *usable* lines of your
1308 1302 terminal screen (total lines minus lines you need to reserve to show other
1309 1303 information).
1310 1304
1311 1305 If you set screen_lines to a number <=0, page() will try to auto-determine
1312 1306 your screen size and will only use up to (screen_size+screen_lines) for
1313 1307 printing, paging after that. That is, if you want auto-detection but need
1314 1308 to reserve the bottom 3 lines of the screen, use screen_lines = -3, and for
1315 1309 auto-detection without any lines reserved simply use screen_lines = 0.
1316 1310
1317 1311 If a string won't fit in the allowed lines, it is sent through the
1318 1312 specified pager command. If none given, look for PAGER in the environment,
1319 1313 and ultimately default to less.
1320 1314
1321 1315 If no system pager works, the string is sent through a 'dumb pager'
1322 1316 written in python, very simplistic.
1323 1317 """
1324 1318
1325 1319 # Ugly kludge, but calling curses.initscr() flat out crashes in emacs
1326 1320 TERM = os.environ.get('TERM','dumb')
1327 1321 if TERM in ['dumb','emacs'] and os.name != 'nt':
1328 1322 print strng
1329 1323 return
1330 1324 # chop off the topmost part of the string we don't want to see
1331 1325 str_lines = strng.split(os.linesep)[start:]
1332 1326 str_toprint = os.linesep.join(str_lines)
1333 1327 num_newlines = len(str_lines)
1334 1328 len_str = len(str_toprint)
1335 1329
1336 1330 # Dumb heuristics to guesstimate number of on-screen lines the string
1337 1331 # takes. Very basic, but good enough for docstrings in reasonable
1338 1332 # terminals. If someone later feels like refining it, it's not hard.
1339 1333 numlines = max(num_newlines,int(len_str/80)+1)
1340 1334
1341 1335 if os.name == "nt":
1342 1336 screen_lines_def = get_console_size(defaulty=25)[1]
1343 1337 else:
1344 1338 screen_lines_def = 25 # default value if we can't auto-determine
1345 1339
1346 1340 # auto-determine screen size
1347 1341 if screen_lines <= 0:
1348 1342 if TERM=='xterm':
1349 1343 try:
1350 1344 import curses
1351 1345 if hasattr(curses,'initscr'):
1352 1346 use_curses = 1
1353 1347 else:
1354 1348 use_curses = 0
1355 1349 except ImportError:
1356 1350 use_curses = 0
1357 1351 else:
1358 1352 # curses causes problems on many terminals other than xterm.
1359 1353 use_curses = 0
1360 1354 if use_curses:
1361 1355 scr = curses.initscr()
1362 1356 screen_lines_real,screen_cols = scr.getmaxyx()
1363 1357 curses.endwin()
1364 1358 screen_lines += screen_lines_real
1365 1359 #print '***Screen size:',screen_lines_real,'lines x',\
1366 1360 #screen_cols,'columns.' # dbg
1367 1361 else:
1368 1362 screen_lines += screen_lines_def
1369 1363
1370 1364 #print 'numlines',numlines,'screenlines',screen_lines # dbg
1371 1365 if numlines <= screen_lines :
1372 1366 #print '*** normal print' # dbg
1373 1367 print >>Term.cout, str_toprint
1374 1368 else:
1375 1369 # Try to open pager and default to internal one if that fails.
1376 1370 # All failure modes are tagged as 'retval=1', to match the return
1377 1371 # value of a failed system command. If any intermediate attempt
1378 1372 # sets retval to 1, at the end we resort to our own page_dumb() pager.
1379 1373 pager_cmd = get_pager_cmd(pager_cmd)
1380 1374 pager_cmd += ' ' + get_pager_start(pager_cmd,start)
1381 1375 if os.name == 'nt':
1382 1376 if pager_cmd.startswith('type'):
1383 1377 # The default WinXP 'type' command is failing on complex strings.
1384 1378 retval = 1
1385 1379 else:
1386 1380 tmpname = tempfile.mktemp('.txt')
1387 1381 tmpfile = file(tmpname,'wt')
1388 1382 tmpfile.write(strng)
1389 1383 tmpfile.close()
1390 1384 cmd = "%s < %s" % (pager_cmd,tmpname)
1391 1385 if os.system(cmd):
1392 1386 retval = 1
1393 1387 else:
1394 1388 retval = None
1395 1389 os.remove(tmpname)
1396 1390 else:
1397 1391 try:
1398 1392 retval = None
1399 1393 # if I use popen4, things hang. No idea why.
1400 1394 #pager,shell_out = os.popen4(pager_cmd)
1401 1395 pager = os.popen(pager_cmd,'w')
1402 1396 pager.write(strng)
1403 1397 pager.close()
1404 1398 retval = pager.close() # success returns None
1405 1399 except IOError,msg: # broken pipe when user quits
1406 1400 if msg.args == (32,'Broken pipe'):
1407 1401 retval = None
1408 1402 else:
1409 1403 retval = 1
1410 1404 except OSError:
1411 1405 # Other strange problems, sometimes seen in Win2k/cygwin
1412 1406 retval = 1
1413 1407 if retval is not None:
1414 1408 page_dumb(strng,screen_lines=screen_lines)
1415 1409
1416 1410 #----------------------------------------------------------------------------
1417 1411 def page_file(fname,start = 0, pager_cmd = None):
1418 1412 """Page a file, using an optional pager command and starting line.
1419 1413 """
1420 1414
1421 1415 pager_cmd = get_pager_cmd(pager_cmd)
1422 1416 pager_cmd += ' ' + get_pager_start(pager_cmd,start)
1423 1417
1424 1418 try:
1425 1419 if os.environ['TERM'] in ['emacs','dumb']:
1426 1420 raise EnvironmentError
1427 1421 xsys(pager_cmd + ' ' + fname)
1428 1422 except:
1429 1423 try:
1430 1424 if start > 0:
1431 1425 start -= 1
1432 1426 page(open(fname).read(),start)
1433 1427 except:
1434 1428 print 'Unable to show file',`fname`
1435 1429
1436 1430 #----------------------------------------------------------------------------
1437 1431 def snip_print(str,width = 75,print_full = 0,header = ''):
1438 1432 """Print a string snipping the midsection to fit in width.
1439 1433
1440 1434 print_full: mode control:
1441 1435 - 0: only snip long strings
1442 1436 - 1: send to page() directly.
1443 1437 - 2: snip long strings and ask for full length viewing with page()
1444 1438 Return 1 if snipping was necessary, 0 otherwise."""
1445 1439
1446 1440 if print_full == 1:
1447 1441 page(header+str)
1448 1442 return 0
1449 1443
1450 1444 print header,
1451 1445 if len(str) < width:
1452 1446 print str
1453 1447 snip = 0
1454 1448 else:
1455 1449 whalf = int((width -5)/2)
1456 1450 print str[:whalf] + ' <...> ' + str[-whalf:]
1457 1451 snip = 1
1458 1452 if snip and print_full == 2:
1459 1453 if raw_input(header+' Snipped. View (y/n)? [N]').lower() == 'y':
1460 1454 page(str)
1461 1455 return snip
1462 1456
1463 1457 #****************************************************************************
1464 1458 # lists, dicts and structures
1465 1459
1466 1460 def belong(candidates,checklist):
1467 1461 """Check whether a list of items appear in a given list of options.
1468 1462
1469 1463 Returns a list of 1 and 0, one for each candidate given."""
1470 1464
1471 1465 return [x in checklist for x in candidates]
1472 1466
1473 1467 #----------------------------------------------------------------------------
1474 1468 def uniq_stable(elems):
1475 1469 """uniq_stable(elems) -> list
1476 1470
1477 1471 Return from an iterable, a list of all the unique elements in the input,
1478 1472 but maintaining the order in which they first appear.
1479 1473
1480 1474 A naive solution to this problem which just makes a dictionary with the
1481 1475 elements as keys fails to respect the stability condition, since
1482 1476 dictionaries are unsorted by nature.
1483 1477
1484 1478 Note: All elements in the input must be valid dictionary keys for this
1485 1479 routine to work, as it internally uses a dictionary for efficiency
1486 1480 reasons."""
1487 1481
1488 1482 unique = []
1489 1483 unique_dict = {}
1490 1484 for nn in elems:
1491 1485 if nn not in unique_dict:
1492 1486 unique.append(nn)
1493 1487 unique_dict[nn] = None
1494 1488 return unique
1495 1489
1496 1490 #----------------------------------------------------------------------------
1497 1491 class NLprinter:
1498 1492 """Print an arbitrarily nested list, indicating index numbers.
1499 1493
1500 1494 An instance of this class called nlprint is available and callable as a
1501 1495 function.
1502 1496
1503 1497 nlprint(list,indent=' ',sep=': ') -> prints indenting each level by 'indent'
1504 1498 and using 'sep' to separate the index from the value. """
1505 1499
1506 1500 def __init__(self):
1507 1501 self.depth = 0
1508 1502
1509 1503 def __call__(self,lst,pos='',**kw):
1510 1504 """Prints the nested list numbering levels."""
1511 1505 kw.setdefault('indent',' ')
1512 1506 kw.setdefault('sep',': ')
1513 1507 kw.setdefault('start',0)
1514 1508 kw.setdefault('stop',len(lst))
1515 1509 # we need to remove start and stop from kw so they don't propagate
1516 1510 # into a recursive call for a nested list.
1517 1511 start = kw['start']; del kw['start']
1518 1512 stop = kw['stop']; del kw['stop']
1519 1513 if self.depth == 0 and 'header' in kw.keys():
1520 1514 print kw['header']
1521 1515
1522 1516 for idx in range(start,stop):
1523 1517 elem = lst[idx]
1524 1518 if type(elem)==type([]):
1525 1519 self.depth += 1
1526 1520 self.__call__(elem,itpl('$pos$idx,'),**kw)
1527 1521 self.depth -= 1
1528 1522 else:
1529 1523 printpl(kw['indent']*self.depth+'$pos$idx$kw["sep"]$elem')
1530 1524
1531 1525 nlprint = NLprinter()
1532 1526 #----------------------------------------------------------------------------
1533 1527 def all_belong(candidates,checklist):
1534 1528 """Check whether a list of items ALL appear in a given list of options.
1535 1529
1536 1530 Returns a single 1 or 0 value."""
1537 1531
1538 1532 return 1-(0 in [x in checklist for x in candidates])
1539 1533
1540 1534 #----------------------------------------------------------------------------
1541 1535 def sort_compare(lst1,lst2,inplace = 1):
1542 1536 """Sort and compare two lists.
1543 1537
1544 1538 By default it does it in place, thus modifying the lists. Use inplace = 0
1545 1539 to avoid that (at the cost of temporary copy creation)."""
1546 1540 if not inplace:
1547 1541 lst1 = lst1[:]
1548 1542 lst2 = lst2[:]
1549 1543 lst1.sort(); lst2.sort()
1550 1544 return lst1 == lst2
1551 1545
1552 1546 #----------------------------------------------------------------------------
1553 1547 def mkdict(**kwargs):
1554 1548 """Return a dict from a keyword list.
1555 1549
1556 1550 It's just syntactic sugar for making ditcionary creation more convenient:
1557 1551 # the standard way
1558 1552 >>>data = { 'red' : 1, 'green' : 2, 'blue' : 3 }
1559 1553 # a cleaner way
1560 1554 >>>data = dict(red=1, green=2, blue=3)
1561 1555
1562 1556 If you need more than this, look at the Struct() class."""
1563 1557
1564 1558 return kwargs
1565 1559
1566 1560 #----------------------------------------------------------------------------
1567 1561 def list2dict(lst):
1568 1562 """Takes a list of (key,value) pairs and turns it into a dict."""
1569 1563
1570 1564 dic = {}
1571 1565 for k,v in lst: dic[k] = v
1572 1566 return dic
1573 1567
1574 1568 #----------------------------------------------------------------------------
1575 1569 def list2dict2(lst,default=''):
1576 1570 """Takes a list and turns it into a dict.
1577 1571 Much slower than list2dict, but more versatile. This version can take
1578 1572 lists with sublists of arbitrary length (including sclars)."""
1579 1573
1580 1574 dic = {}
1581 1575 for elem in lst:
1582 1576 if type(elem) in (types.ListType,types.TupleType):
1583 1577 size = len(elem)
1584 1578 if size == 0:
1585 1579 pass
1586 1580 elif size == 1:
1587 1581 dic[elem] = default
1588 1582 else:
1589 1583 k,v = elem[0], elem[1:]
1590 1584 if len(v) == 1: v = v[0]
1591 1585 dic[k] = v
1592 1586 else:
1593 1587 dic[elem] = default
1594 1588 return dic
1595 1589
1596 1590 #----------------------------------------------------------------------------
1597 1591 def flatten(seq):
1598 1592 """Flatten a list of lists (NOT recursive, only works for 2d lists)."""
1599 1593
1600 1594 # bug in python??? (YES. Fixed in 2.2, let's leave the kludgy fix in).
1601 1595
1602 1596 # if the x=0 isn't made, a *global* variable x is left over after calling
1603 1597 # this function, with the value of the last element in the return
1604 1598 # list. This does seem like a bug big time to me.
1605 1599
1606 1600 # the problem is fixed with the x=0, which seems to force the creation of
1607 1601 # a local name
1608 1602
1609 1603 x = 0
1610 1604 return [x for subseq in seq for x in subseq]
1611 1605
1612 1606 #----------------------------------------------------------------------------
1613 1607 def get_slice(seq,start=0,stop=None,step=1):
1614 1608 """Get a slice of a sequence with variable step. Specify start,stop,step."""
1615 1609 if stop == None:
1616 1610 stop = len(seq)
1617 1611 item = lambda i: seq[i]
1618 1612 return map(item,xrange(start,stop,step))
1619 1613
1620 1614 #----------------------------------------------------------------------------
1621 1615 def chop(seq,size):
1622 1616 """Chop a sequence into chunks of the given size."""
1623 1617 chunk = lambda i: seq[i:i+size]
1624 1618 return map(chunk,xrange(0,len(seq),size))
1625 1619
1626 1620 #----------------------------------------------------------------------------
1627 1621 def with(object, **args):
1628 1622 """Set multiple attributes for an object, similar to Pascal's with.
1629 1623
1630 1624 Example:
1631 1625 with(jim,
1632 1626 born = 1960,
1633 1627 haircolour = 'Brown',
1634 1628 eyecolour = 'Green')
1635 1629
1636 1630 Credit: Greg Ewing, in
1637 1631 http://mail.python.org/pipermail/python-list/2001-May/040703.html"""
1638 1632
1639 1633 object.__dict__.update(args)
1640 1634
1641 1635 #----------------------------------------------------------------------------
1642 1636 def setattr_list(obj,alist,nspace = None):
1643 1637 """Set a list of attributes for an object taken from a namespace.
1644 1638
1645 1639 setattr_list(obj,alist,nspace) -> sets in obj all the attributes listed in
1646 1640 alist with their values taken from nspace, which must be a dict (something
1647 1641 like locals() will often do) If nspace isn't given, locals() of the
1648 1642 *caller* is used, so in most cases you can omit it.
1649 1643
1650 1644 Note that alist can be given as a string, which will be automatically
1651 1645 split into a list on whitespace. If given as a list, it must be a list of
1652 1646 *strings* (the variable names themselves), not of variables."""
1653 1647
1654 1648 # this grabs the local variables from the *previous* call frame -- that is
1655 1649 # the locals from the function that called setattr_list().
1656 1650 # - snipped from weave.inline()
1657 1651 if nspace is None:
1658 1652 call_frame = sys._getframe().f_back
1659 1653 nspace = call_frame.f_locals
1660 1654
1661 1655 if type(alist) in StringTypes:
1662 1656 alist = alist.split()
1663 1657 for attr in alist:
1664 1658 val = eval(attr,nspace)
1665 1659 setattr(obj,attr,val)
1666 1660
1667 1661 #----------------------------------------------------------------------------
1668 1662 def getattr_list(obj,alist,*args):
1669 1663 """getattr_list(obj,alist[, default]) -> attribute list.
1670 1664
1671 1665 Get a list of named attributes for an object. When a default argument is
1672 1666 given, it is returned when the attribute doesn't exist; without it, an
1673 1667 exception is raised in that case.
1674 1668
1675 1669 Note that alist can be given as a string, which will be automatically
1676 1670 split into a list on whitespace. If given as a list, it must be a list of
1677 1671 *strings* (the variable names themselves), not of variables."""
1678 1672
1679 1673 if type(alist) in StringTypes:
1680 1674 alist = alist.split()
1681 1675 if args:
1682 1676 if len(args)==1:
1683 1677 default = args[0]
1684 1678 return map(lambda attr: getattr(obj,attr,default),alist)
1685 1679 else:
1686 1680 raise ValueError,'getattr_list() takes only one optional argument'
1687 1681 else:
1688 1682 return map(lambda attr: getattr(obj,attr),alist)
1689 1683
1690 1684 #----------------------------------------------------------------------------
1691 1685 def map_method(method,object_list,*argseq,**kw):
1692 1686 """map_method(method,object_list,*args,**kw) -> list
1693 1687
1694 1688 Return a list of the results of applying the methods to the items of the
1695 1689 argument sequence(s). If more than one sequence is given, the method is
1696 1690 called with an argument list consisting of the corresponding item of each
1697 1691 sequence. All sequences must be of the same length.
1698 1692
1699 1693 Keyword arguments are passed verbatim to all objects called.
1700 1694
1701 1695 This is Python code, so it's not nearly as fast as the builtin map()."""
1702 1696
1703 1697 out_list = []
1704 1698 idx = 0
1705 1699 for object in object_list:
1706 1700 try:
1707 1701 handler = getattr(object, method)
1708 1702 except AttributeError:
1709 1703 out_list.append(None)
1710 1704 else:
1711 1705 if argseq:
1712 1706 args = map(lambda lst:lst[idx],argseq)
1713 1707 #print 'ob',object,'hand',handler,'ar',args # dbg
1714 1708 out_list.append(handler(args,**kw))
1715 1709 else:
1716 1710 out_list.append(handler(**kw))
1717 1711 idx += 1
1718 1712 return out_list
1719 1713
1720 1714 #----------------------------------------------------------------------------
1721 1715 def import_fail_info(mod_name,fns=None):
1722 1716 """Inform load failure for a module."""
1723 1717
1724 1718 if fns == None:
1725 1719 warn("Loading of %s failed.\n" % (mod_name,))
1726 1720 else:
1727 1721 warn("Loading of %s from %s failed.\n" % (fns,mod_name))
1728 1722
1729 1723 #----------------------------------------------------------------------------
1730 1724 # Proposed popitem() extension, written as a method
1731 1725
1732 1726 class NotGiven: pass
1733 1727
1734 1728 def popkey(dct,key,default=NotGiven):
1735 1729 """Return dct[key] and delete dct[key].
1736 1730
1737 1731 If default is given, return it if dct[key] doesn't exist, otherwise raise
1738 1732 KeyError. """
1739 1733
1740 1734 try:
1741 1735 val = dct[key]
1742 1736 except KeyError:
1743 1737 if default is NotGiven:
1744 1738 raise
1745 1739 else:
1746 1740 return default
1747 1741 else:
1748 1742 del dct[key]
1749 1743 return val
1750 1744 #*************************** end of file <genutils.py> **********************
1751 1745
@@ -1,2157 +1,2191 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 1012 2006-01-12 21:29:37Z vivainio $
9 $Id: iplib.py 1013 2006-01-13 08:33:32Z fperez $
10 10 """
11 11
12 12 #*****************************************************************************
13 13 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
14 14 # Copyright (C) 2001-2006 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, all of that class has been copied
21 21 # verbatim here for modifications which could not be accomplished by
22 22 # subclassing. At this point, there are no dependencies at all on the code
23 23 # module anymore (it is not even imported). The Python License (sec. 2)
24 24 # allows for this, but it's always nice to acknowledge credit where credit is
25 25 # due.
26 26 #*****************************************************************************
27 27
28 28 #****************************************************************************
29 29 # Modules and globals
30 30
31 31 from __future__ import generators # for 2.2 backwards-compatibility
32 32
33 33 from IPython import Release
34 34 __author__ = '%s <%s>\n%s <%s>' % \
35 35 ( Release.authors['Janko'] + Release.authors['Fernando'] )
36 36 __license__ = Release.license
37 37 __version__ = Release.version
38 38
39 39 # Python standard modules
40 40 import __main__
41 41 import __builtin__
42 42 import StringIO
43 43 import bdb
44 44 import cPickle as pickle
45 45 import codeop
46 46 import exceptions
47 47 import glob
48 48 import inspect
49 49 import keyword
50 50 import new
51 51 import os
52 52 import pdb
53 53 import pydoc
54 54 import re
55 55 import shutil
56 56 import string
57 57 import sys
58 58 import tempfile
59 59 import traceback
60 60 import types
61 61
62 62 from pprint import pprint, pformat
63 63
64 64 # IPython's own modules
65 65 import IPython
66 66 from IPython import OInspect,PyColorize,ultraTB
67 67 from IPython.ColorANSI import ColorScheme,ColorSchemeTable # too long names
68 68 from IPython.FakeModule import FakeModule
69 69 from IPython.Itpl import Itpl,itpl,printpl,ItplNS,itplns
70 70 from IPython.Logger import Logger
71 71 from IPython.Magic import Magic
72 72 from IPython.Prompts import CachedOutput
73 73 from IPython.ipstruct import Struct
74 74 from IPython.background_jobs import BackgroundJobManager
75 75 from IPython.usage import cmd_line_usage,interactive_usage
76 76 from IPython.genutils import *
77 77
78 78 # Globals
79 79
80 80 # store the builtin raw_input globally, and use this always, in case user code
81 81 # overwrites it (like wx.py.PyShell does)
82 82 raw_input_original = raw_input
83 83
84 84 # compiled regexps for autoindent management
85 ini_spaces_re = re.compile(r'^(\s+)')
86 85 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
87 86
88 87
89 88 #****************************************************************************
90 89 # Some utility function definitions
91 90
91 ini_spaces_re = re.compile(r'^(\s+)')
92
93 def num_ini_spaces(strng):
94 """Return the number of initial spaces in a string"""
95
96 ini_spaces = ini_spaces_re.match(strng)
97 if ini_spaces:
98 return ini_spaces.end()
99 else:
100 return 0
101
92 102 def softspace(file, newvalue):
93 103 """Copied from code.py, to remove the dependency"""
104
94 105 oldvalue = 0
95 106 try:
96 107 oldvalue = file.softspace
97 108 except AttributeError:
98 109 pass
99 110 try:
100 111 file.softspace = newvalue
101 112 except (AttributeError, TypeError):
102 113 # "attribute-less object" or "read-only attributes"
103 114 pass
104 115 return oldvalue
105 116
106 117
107 118 #****************************************************************************
108 119 # Local use exceptions
109 120 class SpaceInInput(exceptions.Exception): pass
110 121
111 122
112 123 #****************************************************************************
113 124 # Local use classes
114 125 class Bunch: pass
115 126
116 127 class Undefined: pass
117 128
118 129 class InputList(list):
119 130 """Class to store user input.
120 131
121 132 It's basically a list, but slices return a string instead of a list, thus
122 133 allowing things like (assuming 'In' is an instance):
123 134
124 135 exec In[4:7]
125 136
126 137 or
127 138
128 139 exec In[5:9] + In[14] + In[21:25]"""
129 140
130 141 def __getslice__(self,i,j):
131 142 return ''.join(list.__getslice__(self,i,j))
132 143
133 144 class SyntaxTB(ultraTB.ListTB):
134 145 """Extension which holds some state: the last exception value"""
135 146
136 147 def __init__(self,color_scheme = 'NoColor'):
137 148 ultraTB.ListTB.__init__(self,color_scheme)
138 149 self.last_syntax_error = None
139 150
140 151 def __call__(self, etype, value, elist):
141 152 self.last_syntax_error = value
142 153 ultraTB.ListTB.__call__(self,etype,value,elist)
143 154
144 155 def clear_err_state(self):
145 156 """Return the current error state and clear it"""
146 157 e = self.last_syntax_error
147 158 self.last_syntax_error = None
148 159 return e
149 160
150 161 #****************************************************************************
151 162 # Main IPython class
152 163
153 164 # FIXME: the Magic class is a mixin for now, and will unfortunately remain so
154 165 # until a full rewrite is made. I've cleaned all cross-class uses of
155 166 # attributes and methods, but too much user code out there relies on the
156 167 # equlity %foo == __IP.magic_foo, so I can't actually remove the mixin usage.
157 168 #
158 169 # But at least now, all the pieces have been separated and we could, in
159 170 # principle, stop using the mixin. This will ease the transition to the
160 171 # chainsaw branch.
161 172
162 173 # For reference, the following is the list of 'self.foo' uses in the Magic
163 174 # class as of 2005-12-28. These are names we CAN'T use in the main ipython
164 175 # class, to prevent clashes.
165 176
166 177 # ['self.__class__', 'self.__dict__', 'self._inspect', 'self._ofind',
167 178 # 'self.arg_err', 'self.extract_input', 'self.format_', 'self.lsmagic',
168 179 # 'self.magic_', 'self.options_table', 'self.parse', 'self.shell',
169 180 # 'self.value']
170 181
171 182 class InteractiveShell(object,Magic):
172 183 """An enhanced console for Python."""
173 184
174 185 # class attribute to indicate whether the class supports threads or not.
175 186 # Subclasses with thread support should override this as needed.
176 187 isthreaded = False
177 188
178 189 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
179 190 user_ns = None,user_global_ns=None,banner2='',
180 191 custom_exceptions=((),None),embedded=False):
181 192
182 193 # some minimal strict typechecks. For some core data structures, I
183 194 # want actual basic python types, not just anything that looks like
184 195 # one. This is especially true for namespaces.
185 196 for ns in (user_ns,user_global_ns):
186 197 if ns is not None and type(ns) != types.DictType:
187 198 raise TypeError,'namespace must be a dictionary'
188 199
189 200 # Job manager (for jobs run as background threads)
190 201 self.jobs = BackgroundJobManager()
191 202
192 203 # track which builtins we add, so we can clean up later
193 204 self.builtins_added = {}
194 205 # This method will add the necessary builtins for operation, but
195 206 # tracking what it did via the builtins_added dict.
196 207 self.add_builtins()
197 208
198 209 # Do the intuitively correct thing for quit/exit: we remove the
199 210 # builtins if they exist, and our own magics will deal with this
200 211 try:
201 212 del __builtin__.exit, __builtin__.quit
202 213 except AttributeError:
203 214 pass
204 215
205 216 # Store the actual shell's name
206 217 self.name = name
207 218
208 219 # We need to know whether the instance is meant for embedding, since
209 220 # global/local namespaces need to be handled differently in that case
210 221 self.embedded = embedded
211 222
212 223 # command compiler
213 224 self.compile = codeop.CommandCompiler()
214 225
215 226 # User input buffer
216 227 self.buffer = []
217 228
218 229 # Default name given in compilation of code
219 230 self.filename = '<ipython console>'
220 231
221 232 # Make an empty namespace, which extension writers can rely on both
222 233 # existing and NEVER being used by ipython itself. This gives them a
223 234 # convenient location for storing additional information and state
224 235 # their extensions may require, without fear of collisions with other
225 236 # ipython names that may develop later.
226 237 self.meta = Bunch()
227 238
228 239 # Create the namespace where the user will operate. user_ns is
229 240 # normally the only one used, and it is passed to the exec calls as
230 241 # the locals argument. But we do carry a user_global_ns namespace
231 242 # given as the exec 'globals' argument, This is useful in embedding
232 243 # situations where the ipython shell opens in a context where the
233 244 # distinction between locals and globals is meaningful.
234 245
235 246 # FIXME. For some strange reason, __builtins__ is showing up at user
236 247 # level as a dict instead of a module. This is a manual fix, but I
237 248 # should really track down where the problem is coming from. Alex
238 249 # Schmolck reported this problem first.
239 250
240 251 # A useful post by Alex Martelli on this topic:
241 252 # Re: inconsistent value from __builtins__
242 253 # Von: Alex Martelli <aleaxit@yahoo.com>
243 254 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
244 255 # Gruppen: comp.lang.python
245 256
246 257 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
247 258 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
248 259 # > <type 'dict'>
249 260 # > >>> print type(__builtins__)
250 261 # > <type 'module'>
251 262 # > Is this difference in return value intentional?
252 263
253 264 # Well, it's documented that '__builtins__' can be either a dictionary
254 265 # or a module, and it's been that way for a long time. Whether it's
255 266 # intentional (or sensible), I don't know. In any case, the idea is
256 267 # that if you need to access the built-in namespace directly, you
257 268 # should start with "import __builtin__" (note, no 's') which will
258 269 # definitely give you a module. Yeah, it's somewhat confusing:-(.
259 270
260 271 if user_ns is None:
261 272 # Set __name__ to __main__ to better match the behavior of the
262 273 # normal interpreter.
263 274 user_ns = {'__name__' :'__main__',
264 275 '__builtins__' : __builtin__,
265 276 }
266 277
267 278 if user_global_ns is None:
268 279 user_global_ns = {}
269 280
270 281 # Assign namespaces
271 282 # This is the namespace where all normal user variables live
272 283 self.user_ns = user_ns
273 284 # Embedded instances require a separate namespace for globals.
274 285 # Normally this one is unused by non-embedded instances.
275 286 self.user_global_ns = user_global_ns
276 287 # A namespace to keep track of internal data structures to prevent
277 288 # them from cluttering user-visible stuff. Will be updated later
278 289 self.internal_ns = {}
279 290
280 291 # Namespace of system aliases. Each entry in the alias
281 292 # table must be a 2-tuple of the form (N,name), where N is the number
282 293 # of positional arguments of the alias.
283 294 self.alias_table = {}
284 295
285 296 # A table holding all the namespaces IPython deals with, so that
286 297 # introspection facilities can search easily.
287 298 self.ns_table = {'user':user_ns,
288 299 'user_global':user_global_ns,
289 300 'alias':self.alias_table,
290 301 'internal':self.internal_ns,
291 302 'builtin':__builtin__.__dict__
292 303 }
293 304
294 305 # The user namespace MUST have a pointer to the shell itself.
295 306 self.user_ns[name] = self
296 307
297 308 # We need to insert into sys.modules something that looks like a
298 309 # module but which accesses the IPython namespace, for shelve and
299 310 # pickle to work interactively. Normally they rely on getting
300 311 # everything out of __main__, but for embedding purposes each IPython
301 312 # instance has its own private namespace, so we can't go shoving
302 313 # everything into __main__.
303 314
304 315 # note, however, that we should only do this for non-embedded
305 316 # ipythons, which really mimic the __main__.__dict__ with their own
306 317 # namespace. Embedded instances, on the other hand, should not do
307 318 # this because they need to manage the user local/global namespaces
308 319 # only, but they live within a 'normal' __main__ (meaning, they
309 320 # shouldn't overtake the execution environment of the script they're
310 321 # embedded in).
311 322
312 323 if not embedded:
313 324 try:
314 325 main_name = self.user_ns['__name__']
315 326 except KeyError:
316 327 raise KeyError,'user_ns dictionary MUST have a "__name__" key'
317 328 else:
318 329 #print "pickle hack in place" # dbg
319 330 #print 'main_name:',main_name # dbg
320 331 sys.modules[main_name] = FakeModule(self.user_ns)
321 332
322 333 # List of input with multi-line handling.
323 334 # Fill its zero entry, user counter starts at 1
324 335 self.input_hist = InputList(['\n'])
325 336
326 337 # list of visited directories
327 338 try:
328 339 self.dir_hist = [os.getcwd()]
329 340 except IOError, e:
330 341 self.dir_hist = []
331 342
332 343 # dict of output history
333 344 self.output_hist = {}
334 345
335 346 # dict of things NOT to alias (keywords, builtins and some magics)
336 347 no_alias = {}
337 348 no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias']
338 349 for key in keyword.kwlist + no_alias_magics:
339 350 no_alias[key] = 1
340 351 no_alias.update(__builtin__.__dict__)
341 352 self.no_alias = no_alias
342 353
343 354 # make global variables for user access to these
344 355 self.user_ns['_ih'] = self.input_hist
345 356 self.user_ns['_oh'] = self.output_hist
346 357 self.user_ns['_dh'] = self.dir_hist
347 358
348 359 # user aliases to input and output histories
349 360 self.user_ns['In'] = self.input_hist
350 361 self.user_ns['Out'] = self.output_hist
351 362
352 363 # Object variable to store code object waiting execution. This is
353 364 # used mainly by the multithreaded shells, but it can come in handy in
354 365 # other situations. No need to use a Queue here, since it's a single
355 366 # item which gets cleared once run.
356 367 self.code_to_run = None
357 368
358 369 # escapes for automatic behavior on the command line
359 370 self.ESC_SHELL = '!'
360 371 self.ESC_HELP = '?'
361 372 self.ESC_MAGIC = '%'
362 373 self.ESC_QUOTE = ','
363 374 self.ESC_QUOTE2 = ';'
364 375 self.ESC_PAREN = '/'
365 376
366 377 # And their associated handlers
367 378 self.esc_handlers = {self.ESC_PAREN : self.handle_auto,
368 379 self.ESC_QUOTE : self.handle_auto,
369 380 self.ESC_QUOTE2 : self.handle_auto,
370 381 self.ESC_MAGIC : self.handle_magic,
371 382 self.ESC_HELP : self.handle_help,
372 383 self.ESC_SHELL : self.handle_shell_escape,
373 384 }
374 385
375 386 # class initializations
376 387 Magic.__init__(self,self)
377 388
378 389 # Python source parser/formatter for syntax highlighting
379 390 pyformat = PyColorize.Parser().format
380 391 self.pycolorize = lambda src: pyformat(src,'str',self.rc['colors'])
381 392
382 393 # hooks holds pointers used for user-side customizations
383 394 self.hooks = Struct()
384 395
385 396 # Set all default hooks, defined in the IPython.hooks module.
386 397 hooks = IPython.hooks
387 398 for hook_name in hooks.__all__:
388 399 self.set_hook(hook_name,getattr(hooks,hook_name))
389 400
390 401 # Flag to mark unconditional exit
391 402 self.exit_now = False
392 403
393 404 self.usage_min = """\
394 405 An enhanced console for Python.
395 406 Some of its features are:
396 407 - Readline support if the readline library is present.
397 408 - Tab completion in the local namespace.
398 409 - Logging of input, see command-line options.
399 410 - System shell escape via ! , eg !ls.
400 411 - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.)
401 412 - Keeps track of locally defined variables via %who, %whos.
402 413 - Show object information with a ? eg ?x or x? (use ?? for more info).
403 414 """
404 415 if usage: self.usage = usage
405 416 else: self.usage = self.usage_min
406 417
407 418 # Storage
408 419 self.rc = rc # This will hold all configuration information
409 420 self.pager = 'less'
410 421 # temporary files used for various purposes. Deleted at exit.
411 422 self.tempfiles = []
412 423
413 424 # Keep track of readline usage (later set by init_readline)
414 425 self.has_readline = False
415 426
416 427 # template for logfile headers. It gets resolved at runtime by the
417 428 # logstart method.
418 429 self.loghead_tpl = \
419 430 """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE ***
420 431 #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW
421 432 #log# opts = %s
422 433 #log# args = %s
423 434 #log# It is safe to make manual edits below here.
424 435 #log#-----------------------------------------------------------------------
425 436 """
426 437 # for pushd/popd management
427 438 try:
428 439 self.home_dir = get_home_dir()
429 440 except HomeDirError,msg:
430 441 fatal(msg)
431 442
432 443 self.dir_stack = [os.getcwd().replace(self.home_dir,'~')]
433 444
434 445 # Functions to call the underlying shell.
435 446
436 447 # utility to expand user variables via Itpl
437 448 self.var_expand = lambda cmd: str(ItplNS(cmd.replace('#','\#'),
438 449 self.user_ns))
439 450 # The first is similar to os.system, but it doesn't return a value,
440 451 # and it allows interpolation of variables in the user's namespace.
441 452 self.system = lambda cmd: shell(self.var_expand(cmd),
442 453 header='IPython system call: ',
443 454 verbose=self.rc.system_verbose)
444 455 # These are for getoutput and getoutputerror:
445 456 self.getoutput = lambda cmd: \
446 457 getoutput(self.var_expand(cmd),
447 458 header='IPython system call: ',
448 459 verbose=self.rc.system_verbose)
449 460 self.getoutputerror = lambda cmd: \
450 461 getoutputerror(str(ItplNS(cmd.replace('#','\#'),
451 462 self.user_ns)),
452 463 header='IPython system call: ',
453 464 verbose=self.rc.system_verbose)
454 465
455 466 # RegExp for splitting line contents into pre-char//first
456 467 # word-method//rest. For clarity, each group in on one line.
457 468
458 469 # WARNING: update the regexp if the above escapes are changed, as they
459 470 # are hardwired in.
460 471
461 472 # Don't get carried away with trying to make the autocalling catch too
462 473 # much: it's better to be conservative rather than to trigger hidden
463 474 # evals() somewhere and end up causing side effects.
464 475
465 476 self.line_split = re.compile(r'^([\s*,;/])'
466 477 r'([\?\w\.]+\w*\s*)'
467 478 r'(\(?.*$)')
468 479
469 480 # Original re, keep around for a while in case changes break something
470 481 #self.line_split = re.compile(r'(^[\s*!\?%,/]?)'
471 482 # r'(\s*[\?\w\.]+\w*\s*)'
472 483 # r'(\(?.*$)')
473 484
474 485 # RegExp to identify potential function names
475 486 self.re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$')
476 # RegExp to exclude strings with this start from autocalling
477 self.re_exclude_auto = re.compile('^[!=()<>,\*/\+-]|^is ')
487
488 # RegExp to exclude strings with this start from autocalling. In
489 # particular, all binary operators should be excluded, so that if foo
490 # is callable, foo OP bar doesn't become foo(OP bar), which is
491 # invalid. The characters '!=()' don't need to be checked for, as the
492 # _prefilter routine explicitely does so, to catch direct calls and
493 # rebindings of existing names.
494
495 # Warning: the '-' HAS TO BE AT THE END of the first group, otherwise
496 # it affects the rest of the group in square brackets.
497 self.re_exclude_auto = re.compile(r'^[<>,&^\|\*/\+-]'
498 '|^is |^not |^in |^and |^or ')
478 499
479 500 # try to catch also methods for stuff in lists/tuples/dicts: off
480 501 # (experimental). For this to work, the line_split regexp would need
481 502 # to be modified so it wouldn't break things at '['. That line is
482 503 # nasty enough that I shouldn't change it until I can test it _well_.
483 504 #self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$')
484 505
485 506 # keep track of where we started running (mainly for crash post-mortem)
486 507 self.starting_dir = os.getcwd()
487 508
488 509 # Various switches which can be set
489 510 self.CACHELENGTH = 5000 # this is cheap, it's just text
490 511 self.BANNER = "Python %(version)s on %(platform)s\n" % sys.__dict__
491 512 self.banner2 = banner2
492 513
493 514 # TraceBack handlers:
494 515
495 516 # Syntax error handler.
496 517 self.SyntaxTB = SyntaxTB(color_scheme='NoColor')
497 518
498 519 # The interactive one is initialized with an offset, meaning we always
499 520 # want to remove the topmost item in the traceback, which is our own
500 521 # internal code. Valid modes: ['Plain','Context','Verbose']
501 522 self.InteractiveTB = ultraTB.AutoFormattedTB(mode = 'Plain',
502 523 color_scheme='NoColor',
503 524 tb_offset = 1)
504 525
505 526 # IPython itself shouldn't crash. This will produce a detailed
506 527 # post-mortem if it does. But we only install the crash handler for
507 528 # non-threaded shells, the threaded ones use a normal verbose reporter
508 529 # and lose the crash handler. This is because exceptions in the main
509 530 # thread (such as in GUI code) propagate directly to sys.excepthook,
510 531 # and there's no point in printing crash dumps for every user exception.
511 532 if self.isthreaded:
512 533 sys.excepthook = ultraTB.FormattedTB()
513 534 else:
514 535 from IPython import CrashHandler
515 536 sys.excepthook = CrashHandler.CrashHandler(self)
516 537
517 538 # The instance will store a pointer to this, so that runtime code
518 539 # (such as magics) can access it. This is because during the
519 540 # read-eval loop, it gets temporarily overwritten (to deal with GUI
520 541 # frameworks).
521 542 self.sys_excepthook = sys.excepthook
522 543
523 544 # and add any custom exception handlers the user may have specified
524 545 self.set_custom_exc(*custom_exceptions)
525 546
526 547 # Object inspector
527 548 self.inspector = OInspect.Inspector(OInspect.InspectColors,
528 549 PyColorize.ANSICodeColors,
529 550 'NoColor')
530 551 # indentation management
531 552 self.autoindent = False
532 553 self.indent_current_nsp = 0
533 554 self.indent_current = '' # actual indent string
534 555
535 556 # Make some aliases automatically
536 557 # Prepare list of shell aliases to auto-define
537 558 if os.name == 'posix':
538 559 auto_alias = ('mkdir mkdir', 'rmdir rmdir',
539 560 'mv mv -i','rm rm -i','cp cp -i',
540 561 'cat cat','less less','clear clear',
541 562 # a better ls
542 563 'ls ls -F',
543 564 # long ls
544 565 'll ls -lF',
545 566 # color ls
546 567 'lc ls -F -o --color',
547 568 # ls normal files only
548 569 'lf ls -F -o --color %l | grep ^-',
549 570 # ls symbolic links
550 571 'lk ls -F -o --color %l | grep ^l',
551 572 # directories or links to directories,
552 573 'ldir ls -F -o --color %l | grep /$',
553 574 # things which are executable
554 575 'lx ls -F -o --color %l | grep ^-..x',
555 576 )
556 577 elif os.name in ['nt','dos']:
557 578 auto_alias = ('dir dir /on', 'ls dir /on',
558 579 'ddir dir /ad /on', 'ldir dir /ad /on',
559 580 'mkdir mkdir','rmdir rmdir','echo echo',
560 581 'ren ren','cls cls','copy copy')
561 582 else:
562 583 auto_alias = ()
563 584 self.auto_alias = map(lambda s:s.split(None,1),auto_alias)
564 585 # Call the actual (public) initializer
565 586 self.init_auto_alias()
566 587 # end __init__
567 588
568 589 def post_config_initialization(self):
569 590 """Post configuration init method
570 591
571 592 This is called after the configuration files have been processed to
572 593 'finalize' the initialization."""
573 594
574 595 rc = self.rc
575 596
576 597 # Load readline proper
577 598 if rc.readline:
578 599 self.init_readline()
579 600
580 601 # log system
581 602 self.logger = Logger(self,logfname='ipython_log.py',logmode='rotate')
582 603 # local shortcut, this is used a LOT
583 604 self.log = self.logger.log
584 605
585 606 # Initialize cache, set in/out prompts and printing system
586 607 self.outputcache = CachedOutput(self,
587 608 rc.cache_size,
588 609 rc.pprint,
589 610 input_sep = rc.separate_in,
590 611 output_sep = rc.separate_out,
591 612 output_sep2 = rc.separate_out2,
592 613 ps1 = rc.prompt_in1,
593 614 ps2 = rc.prompt_in2,
594 615 ps_out = rc.prompt_out,
595 616 pad_left = rc.prompts_pad_left)
596 617
597 618 # user may have over-ridden the default print hook:
598 619 try:
599 620 self.outputcache.__class__.display = self.hooks.display
600 621 except AttributeError:
601 622 pass
602 623
603 624 # I don't like assigning globally to sys, because it means when embedding
604 625 # instances, each embedded instance overrides the previous choice. But
605 626 # sys.displayhook seems to be called internally by exec, so I don't see a
606 627 # way around it.
607 628 sys.displayhook = self.outputcache
608 629
609 630 # Set user colors (don't do it in the constructor above so that it
610 631 # doesn't crash if colors option is invalid)
611 632 self.magic_colors(rc.colors)
612 633
613 634 # Set calling of pdb on exceptions
614 635 self.call_pdb = rc.pdb
615 636
616 637 # Load user aliases
617 638 for alias in rc.alias:
618 639 self.magic_alias(alias)
619 640
620 641 # dynamic data that survives through sessions
621 642 # XXX make the filename a config option?
622 643 persist_base = 'persist'
623 644 if rc.profile:
624 645 persist_base += '_%s' % rc.profile
625 646 self.persist_fname = os.path.join(rc.ipythondir,persist_base)
626 647
627 648 try:
628 649 self.persist = pickle.load(file(self.persist_fname))
629 650 except:
630 651 self.persist = {}
631 652
632 653
633 654 for (key, value) in [(k[2:],v) for (k,v) in self.persist.items() if k.startswith('S:')]:
634 655 try:
635 656 obj = pickle.loads(value)
636 657 except:
637 658
638 659 print "Unable to restore variable '%s', ignoring (use %%store -d to forget!)" % key
639 660 print "The error was:",sys.exc_info()[0]
640 661 continue
641 662
642 663
643 664 self.user_ns[key] = obj
644 665
645 666 def add_builtins(self):
646 667 """Store ipython references into the builtin namespace.
647 668
648 669 Some parts of ipython operate via builtins injected here, which hold a
649 670 reference to IPython itself."""
650 671
651 672 builtins_new = dict(__IPYTHON__ = self,
652 673 ip_set_hook = self.set_hook,
653 674 jobs = self.jobs,
654 675 ipmagic = self.ipmagic,
655 676 ipalias = self.ipalias,
656 677 ipsystem = self.ipsystem,
657 678 )
658 679 for biname,bival in builtins_new.items():
659 680 try:
660 681 # store the orignal value so we can restore it
661 682 self.builtins_added[biname] = __builtin__.__dict__[biname]
662 683 except KeyError:
663 684 # or mark that it wasn't defined, and we'll just delete it at
664 685 # cleanup
665 686 self.builtins_added[biname] = Undefined
666 687 __builtin__.__dict__[biname] = bival
667 688
668 689 # Keep in the builtins a flag for when IPython is active. We set it
669 690 # with setdefault so that multiple nested IPythons don't clobber one
670 691 # another. Each will increase its value by one upon being activated,
671 692 # which also gives us a way to determine the nesting level.
672 693 __builtin__.__dict__.setdefault('__IPYTHON__active',0)
673 694
674 695 def clean_builtins(self):
675 696 """Remove any builtins which might have been added by add_builtins, or
676 697 restore overwritten ones to their previous values."""
677 698 for biname,bival in self.builtins_added.items():
678 699 if bival is Undefined:
679 700 del __builtin__.__dict__[biname]
680 701 else:
681 702 __builtin__.__dict__[biname] = bival
682 703 self.builtins_added.clear()
683 704
684 705 def set_hook(self,name,hook):
685 706 """set_hook(name,hook) -> sets an internal IPython hook.
686 707
687 708 IPython exposes some of its internal API as user-modifiable hooks. By
688 709 resetting one of these hooks, you can modify IPython's behavior to
689 710 call at runtime your own routines."""
690 711
691 712 # At some point in the future, this should validate the hook before it
692 713 # accepts it. Probably at least check that the hook takes the number
693 714 # of args it's supposed to.
694 715 setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__))
695 716
696 717 def set_custom_exc(self,exc_tuple,handler):
697 718 """set_custom_exc(exc_tuple,handler)
698 719
699 720 Set a custom exception handler, which will be called if any of the
700 721 exceptions in exc_tuple occur in the mainloop (specifically, in the
701 722 runcode() method.
702 723
703 724 Inputs:
704 725
705 726 - exc_tuple: a *tuple* of valid exceptions to call the defined
706 727 handler for. It is very important that you use a tuple, and NOT A
707 728 LIST here, because of the way Python's except statement works. If
708 729 you only want to trap a single exception, use a singleton tuple:
709 730
710 731 exc_tuple == (MyCustomException,)
711 732
712 733 - handler: this must be defined as a function with the following
713 734 basic interface: def my_handler(self,etype,value,tb).
714 735
715 736 This will be made into an instance method (via new.instancemethod)
716 737 of IPython itself, and it will be called if any of the exceptions
717 738 listed in the exc_tuple are caught. If the handler is None, an
718 739 internal basic one is used, which just prints basic info.
719 740
720 741 WARNING: by putting in your own exception handler into IPython's main
721 742 execution loop, you run a very good chance of nasty crashes. This
722 743 facility should only be used if you really know what you are doing."""
723 744
724 745 assert type(exc_tuple)==type(()) , \
725 746 "The custom exceptions must be given AS A TUPLE."
726 747
727 748 def dummy_handler(self,etype,value,tb):
728 749 print '*** Simple custom exception handler ***'
729 750 print 'Exception type :',etype
730 751 print 'Exception value:',value
731 752 print 'Traceback :',tb
732 753 print 'Source code :','\n'.join(self.buffer)
733 754
734 755 if handler is None: handler = dummy_handler
735 756
736 757 self.CustomTB = new.instancemethod(handler,self,self.__class__)
737 758 self.custom_exceptions = exc_tuple
738 759
739 760 def set_custom_completer(self,completer,pos=0):
740 761 """set_custom_completer(completer,pos=0)
741 762
742 763 Adds a new custom completer function.
743 764
744 765 The position argument (defaults to 0) is the index in the completers
745 766 list where you want the completer to be inserted."""
746 767
747 768 newcomp = new.instancemethod(completer,self.Completer,
748 769 self.Completer.__class__)
749 770 self.Completer.matchers.insert(pos,newcomp)
750 771
751 772 def _get_call_pdb(self):
752 773 return self._call_pdb
753 774
754 775 def _set_call_pdb(self,val):
755 776
756 777 if val not in (0,1,False,True):
757 778 raise ValueError,'new call_pdb value must be boolean'
758 779
759 780 # store value in instance
760 781 self._call_pdb = val
761 782
762 783 # notify the actual exception handlers
763 784 self.InteractiveTB.call_pdb = val
764 785 if self.isthreaded:
765 786 try:
766 787 self.sys_excepthook.call_pdb = val
767 788 except:
768 789 warn('Failed to activate pdb for threaded exception handler')
769 790
770 791 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
771 792 'Control auto-activation of pdb at exceptions')
772 793
773 794
774 795 # These special functions get installed in the builtin namespace, to
775 796 # provide programmatic (pure python) access to magics, aliases and system
776 797 # calls. This is important for logging, user scripting, and more.
777 798
778 799 # We are basically exposing, via normal python functions, the three
779 800 # mechanisms in which ipython offers special call modes (magics for
780 801 # internal control, aliases for direct system access via pre-selected
781 802 # names, and !cmd for calling arbitrary system commands).
782 803
783 804 def ipmagic(self,arg_s):
784 805 """Call a magic function by name.
785 806
786 807 Input: a string containing the name of the magic function to call and any
787 808 additional arguments to be passed to the magic.
788 809
789 810 ipmagic('name -opt foo bar') is equivalent to typing at the ipython
790 811 prompt:
791 812
792 813 In[1]: %name -opt foo bar
793 814
794 815 To call a magic without arguments, simply use ipmagic('name').
795 816
796 817 This provides a proper Python function to call IPython's magics in any
797 818 valid Python code you can type at the interpreter, including loops and
798 819 compound statements. It is added by IPython to the Python builtin
799 820 namespace upon initialization."""
800 821
801 822 args = arg_s.split(' ',1)
802 823 magic_name = args[0]
803 824 if magic_name.startswith(self.ESC_MAGIC):
804 825 magic_name = magic_name[1:]
805 826 try:
806 827 magic_args = args[1]
807 828 except IndexError:
808 829 magic_args = ''
809 830 fn = getattr(self,'magic_'+magic_name,None)
810 831 if fn is None:
811 832 error("Magic function `%s` not found." % magic_name)
812 833 else:
813 834 magic_args = self.var_expand(magic_args)
814 835 return fn(magic_args)
815 836
816 837 def ipalias(self,arg_s):
817 838 """Call an alias by name.
818 839
819 840 Input: a string containing the name of the alias to call and any
820 841 additional arguments to be passed to the magic.
821 842
822 843 ipalias('name -opt foo bar') is equivalent to typing at the ipython
823 844 prompt:
824 845
825 846 In[1]: name -opt foo bar
826 847
827 848 To call an alias without arguments, simply use ipalias('name').
828 849
829 850 This provides a proper Python function to call IPython's aliases in any
830 851 valid Python code you can type at the interpreter, including loops and
831 852 compound statements. It is added by IPython to the Python builtin
832 853 namespace upon initialization."""
833 854
834 855 args = arg_s.split(' ',1)
835 856 alias_name = args[0]
836 857 try:
837 858 alias_args = args[1]
838 859 except IndexError:
839 860 alias_args = ''
840 861 if alias_name in self.alias_table:
841 862 self.call_alias(alias_name,alias_args)
842 863 else:
843 864 error("Alias `%s` not found." % alias_name)
844 865
845 866 def ipsystem(self,arg_s):
846 867 """Make a system call, using IPython."""
847 868
848 869 self.system(arg_s)
849 870
850 871 def complete(self,text):
851 872 """Return a sorted list of all possible completions on text.
852 873
853 874 Inputs:
854 875
855 876 - text: a string of text to be completed on.
856 877
857 878 This is a wrapper around the completion mechanism, similar to what
858 879 readline does at the command line when the TAB key is hit. By
859 880 exposing it as a method, it can be used by other non-readline
860 881 environments (such as GUIs) for text completion.
861 882
862 883 Simple usage example:
863 884
864 885 In [1]: x = 'hello'
865 886
866 887 In [2]: __IP.complete('x.l')
867 888 Out[2]: ['x.ljust', 'x.lower', 'x.lstrip']"""
868 889
869 890 complete = self.Completer.complete
870 891 state = 0
871 892 # use a dict so we get unique keys, since ipyhton's multiple
872 893 # completers can return duplicates.
873 894 comps = {}
874 895 while True:
875 896 newcomp = complete(text,state)
876 897 if newcomp is None:
877 898 break
878 899 comps[newcomp] = 1
879 900 state += 1
880 901 outcomps = comps.keys()
881 902 outcomps.sort()
882 903 return outcomps
883 904
884 905 def set_completer_frame(self, frame=None):
885 906 if frame:
886 907 self.Completer.namespace = frame.f_locals
887 908 self.Completer.global_namespace = frame.f_globals
888 909 else:
889 910 self.Completer.namespace = self.user_ns
890 911 self.Completer.global_namespace = self.user_global_ns
891 912
892 913 def init_auto_alias(self):
893 914 """Define some aliases automatically.
894 915
895 916 These are ALL parameter-less aliases"""
896 917
897 918 for alias,cmd in self.auto_alias:
898 919 self.alias_table[alias] = (0,cmd)
899 920
900 921 def alias_table_validate(self,verbose=0):
901 922 """Update information about the alias table.
902 923
903 924 In particular, make sure no Python keywords/builtins are in it."""
904 925
905 926 no_alias = self.no_alias
906 927 for k in self.alias_table.keys():
907 928 if k in no_alias:
908 929 del self.alias_table[k]
909 930 if verbose:
910 931 print ("Deleting alias <%s>, it's a Python "
911 932 "keyword or builtin." % k)
912 933
913 934 def set_autoindent(self,value=None):
914 935 """Set the autoindent flag, checking for readline support.
915 936
916 937 If called with no arguments, it acts as a toggle."""
917 938
918 939 if not self.has_readline:
919 940 if os.name == 'posix':
920 941 warn("The auto-indent feature requires the readline library")
921 942 self.autoindent = 0
922 943 return
923 944 if value is None:
924 945 self.autoindent = not self.autoindent
925 946 else:
926 947 self.autoindent = value
927 948
928 949 def rc_set_toggle(self,rc_field,value=None):
929 950 """Set or toggle a field in IPython's rc config. structure.
930 951
931 952 If called with no arguments, it acts as a toggle.
932 953
933 954 If called with a non-existent field, the resulting AttributeError
934 955 exception will propagate out."""
935 956
936 957 rc_val = getattr(self.rc,rc_field)
937 958 if value is None:
938 959 value = not rc_val
939 960 setattr(self.rc,rc_field,value)
940 961
941 962 def user_setup(self,ipythondir,rc_suffix,mode='install'):
942 963 """Install the user configuration directory.
943 964
944 965 Can be called when running for the first time or to upgrade the user's
945 966 .ipython/ directory with the mode parameter. Valid modes are 'install'
946 967 and 'upgrade'."""
947 968
948 969 def wait():
949 970 try:
950 971 raw_input("Please press <RETURN> to start IPython.")
951 972 except EOFError:
952 973 print >> Term.cout
953 974 print '*'*70
954 975
955 976 cwd = os.getcwd() # remember where we started
956 977 glb = glob.glob
957 978 print '*'*70
958 979 if mode == 'install':
959 980 print \
960 981 """Welcome to IPython. I will try to create a personal configuration directory
961 982 where you can customize many aspects of IPython's functionality in:\n"""
962 983 else:
963 984 print 'I am going to upgrade your configuration in:'
964 985
965 986 print ipythondir
966 987
967 988 rcdirend = os.path.join('IPython','UserConfig')
968 989 cfg = lambda d: os.path.join(d,rcdirend)
969 990 try:
970 991 rcdir = filter(os.path.isdir,map(cfg,sys.path))[0]
971 992 except IOError:
972 993 warning = """
973 994 Installation error. IPython's directory was not found.
974 995
975 996 Check the following:
976 997
977 998 The ipython/IPython directory should be in a directory belonging to your
978 999 PYTHONPATH environment variable (that is, it should be in a directory
979 1000 belonging to sys.path). You can copy it explicitly there or just link to it.
980 1001
981 1002 IPython will proceed with builtin defaults.
982 1003 """
983 1004 warn(warning)
984 1005 wait()
985 1006 return
986 1007
987 1008 if mode == 'install':
988 1009 try:
989 1010 shutil.copytree(rcdir,ipythondir)
990 1011 os.chdir(ipythondir)
991 1012 rc_files = glb("ipythonrc*")
992 1013 for rc_file in rc_files:
993 1014 os.rename(rc_file,rc_file+rc_suffix)
994 1015 except:
995 1016 warning = """
996 1017
997 1018 There was a problem with the installation:
998 1019 %s
999 1020 Try to correct it or contact the developers if you think it's a bug.
1000 1021 IPython will proceed with builtin defaults.""" % sys.exc_info()[1]
1001 1022 warn(warning)
1002 1023 wait()
1003 1024 return
1004 1025
1005 1026 elif mode == 'upgrade':
1006 1027 try:
1007 1028 os.chdir(ipythondir)
1008 1029 except:
1009 1030 print """
1010 1031 Can not upgrade: changing to directory %s failed. Details:
1011 1032 %s
1012 1033 """ % (ipythondir,sys.exc_info()[1])
1013 1034 wait()
1014 1035 return
1015 1036 else:
1016 1037 sources = glb(os.path.join(rcdir,'[A-Za-z]*'))
1017 1038 for new_full_path in sources:
1018 1039 new_filename = os.path.basename(new_full_path)
1019 1040 if new_filename.startswith('ipythonrc'):
1020 1041 new_filename = new_filename + rc_suffix
1021 1042 # The config directory should only contain files, skip any
1022 1043 # directories which may be there (like CVS)
1023 1044 if os.path.isdir(new_full_path):
1024 1045 continue
1025 1046 if os.path.exists(new_filename):
1026 1047 old_file = new_filename+'.old'
1027 1048 if os.path.exists(old_file):
1028 1049 os.remove(old_file)
1029 1050 os.rename(new_filename,old_file)
1030 1051 shutil.copy(new_full_path,new_filename)
1031 1052 else:
1032 1053 raise ValueError,'unrecognized mode for install:',`mode`
1033 1054
1034 1055 # Fix line-endings to those native to each platform in the config
1035 1056 # directory.
1036 1057 try:
1037 1058 os.chdir(ipythondir)
1038 1059 except:
1039 1060 print """
1040 1061 Problem: changing to directory %s failed.
1041 1062 Details:
1042 1063 %s
1043 1064
1044 1065 Some configuration files may have incorrect line endings. This should not
1045 1066 cause any problems during execution. """ % (ipythondir,sys.exc_info()[1])
1046 1067 wait()
1047 1068 else:
1048 1069 for fname in glb('ipythonrc*'):
1049 1070 try:
1050 1071 native_line_ends(fname,backup=0)
1051 1072 except IOError:
1052 1073 pass
1053 1074
1054 1075 if mode == 'install':
1055 1076 print """
1056 1077 Successful installation!
1057 1078
1058 1079 Please read the sections 'Initial Configuration' and 'Quick Tips' in the
1059 1080 IPython manual (there are both HTML and PDF versions supplied with the
1060 1081 distribution) to make sure that your system environment is properly configured
1061 1082 to take advantage of IPython's features."""
1062 1083 else:
1063 1084 print """
1064 1085 Successful upgrade!
1065 1086
1066 1087 All files in your directory:
1067 1088 %(ipythondir)s
1068 1089 which would have been overwritten by the upgrade were backed up with a .old
1069 1090 extension. If you had made particular customizations in those files you may
1070 1091 want to merge them back into the new files.""" % locals()
1071 1092 wait()
1072 1093 os.chdir(cwd)
1073 1094 # end user_setup()
1074 1095
1075 1096 def atexit_operations(self):
1076 1097 """This will be executed at the time of exit.
1077 1098
1078 1099 Saving of persistent data should be performed here. """
1079 1100
1101 #print '*** IPython exit cleanup ***' # dbg
1080 1102 # input history
1081 1103 self.savehist()
1082 1104
1083 1105 # Cleanup all tempfiles left around
1084 1106 for tfile in self.tempfiles:
1085 1107 try:
1086 1108 os.unlink(tfile)
1087 1109 except OSError:
1088 1110 pass
1089 1111
1090 1112 # save the "persistent data" catch-all dictionary
1091 1113 try:
1092 1114 pickle.dump(self.persist, open(self.persist_fname,"w"))
1093 1115 except:
1094 1116 print "*** ERROR *** persistent data saving failed."
1095 1117
1096 1118 def savehist(self):
1097 1119 """Save input history to a file (via readline library)."""
1098 1120 try:
1099 1121 self.readline.write_history_file(self.histfile)
1100 1122 except:
1101 1123 print 'Unable to save IPython command history to file: ' + \
1102 1124 `self.histfile`
1103 1125
1104 1126 def pre_readline(self):
1105 1127 """readline hook to be used at the start of each line.
1106 1128
1107 1129 Currently it handles auto-indent only."""
1108 1130
1109 1131 self.readline.insert_text(self.indent_current)
1110 1132
1111 1133 def init_readline(self):
1112 1134 """Command history completion/saving/reloading."""
1113 1135 try:
1114 1136 import readline
1115 1137 except ImportError:
1116 1138 self.has_readline = 0
1117 1139 self.readline = None
1118 1140 # no point in bugging windows users with this every time:
1119 1141 if os.name == 'posix':
1120 1142 warn('Readline services not available on this platform.')
1121 1143 else:
1122 1144 import atexit
1123 1145 from IPython.completer import IPCompleter
1124 1146 self.Completer = IPCompleter(self,
1125 1147 self.user_ns,
1126 1148 self.user_global_ns,
1127 1149 self.rc.readline_omit__names,
1128 1150 self.alias_table)
1129 1151
1130 1152 # Platform-specific configuration
1131 1153 if os.name == 'nt':
1132 1154 self.readline_startup_hook = readline.set_pre_input_hook
1133 1155 else:
1134 1156 self.readline_startup_hook = readline.set_startup_hook
1135 1157
1136 1158 # Load user's initrc file (readline config)
1137 1159 inputrc_name = os.environ.get('INPUTRC')
1138 1160 if inputrc_name is None:
1139 1161 home_dir = get_home_dir()
1140 1162 if home_dir is not None:
1141 1163 inputrc_name = os.path.join(home_dir,'.inputrc')
1142 1164 if os.path.isfile(inputrc_name):
1143 1165 try:
1144 1166 readline.read_init_file(inputrc_name)
1145 1167 except:
1146 1168 warn('Problems reading readline initialization file <%s>'
1147 1169 % inputrc_name)
1148 1170
1149 1171 self.has_readline = 1
1150 1172 self.readline = readline
1151 1173 # save this in sys so embedded copies can restore it properly
1152 1174 sys.ipcompleter = self.Completer.complete
1153 1175 readline.set_completer(self.Completer.complete)
1154 1176
1155 1177 # Configure readline according to user's prefs
1156 1178 for rlcommand in self.rc.readline_parse_and_bind:
1157 1179 readline.parse_and_bind(rlcommand)
1158 1180
1159 1181 # remove some chars from the delimiters list
1160 1182 delims = readline.get_completer_delims()
1161 1183 delims = delims.translate(string._idmap,
1162 1184 self.rc.readline_remove_delims)
1163 1185 readline.set_completer_delims(delims)
1164 1186 # otherwise we end up with a monster history after a while:
1165 1187 readline.set_history_length(1000)
1166 1188 try:
1167 1189 #print '*** Reading readline history' # dbg
1168 1190 readline.read_history_file(self.histfile)
1169 1191 except IOError:
1170 1192 pass # It doesn't exist yet.
1171 1193
1172 1194 atexit.register(self.atexit_operations)
1173 1195 del atexit
1174 1196
1175 1197 # Configure auto-indent for all platforms
1176 1198 self.set_autoindent(self.rc.autoindent)
1177 1199
1178 1200 def _should_recompile(self,e):
1179 1201 """Utility routine for edit_syntax_error"""
1180 1202
1181 1203 if e.filename in ('<ipython console>','<input>','<string>',
1182 1204 '<console>',None):
1183 1205
1184 1206 return False
1185 1207 try:
1186 1208 if not ask_yes_no('Return to editor to correct syntax error? '
1187 1209 '[Y/n] ','y'):
1188 1210 return False
1189 1211 except EOFError:
1190 1212 return False
1191 1213
1192 1214 def int0(x):
1193 1215 try:
1194 1216 return int(x)
1195 1217 except TypeError:
1196 1218 return 0
1197 1219 # always pass integer line and offset values to editor hook
1198 1220 self.hooks.fix_error_editor(e.filename,
1199 1221 int0(e.lineno),int0(e.offset),e.msg)
1200 1222 return True
1201 1223
1202 1224 def edit_syntax_error(self):
1203 1225 """The bottom half of the syntax error handler called in the main loop.
1204 1226
1205 1227 Loop until syntax error is fixed or user cancels.
1206 1228 """
1207 1229
1208 1230 while self.SyntaxTB.last_syntax_error:
1209 1231 # copy and clear last_syntax_error
1210 1232 err = self.SyntaxTB.clear_err_state()
1211 1233 if not self._should_recompile(err):
1212 1234 return
1213 1235 try:
1214 1236 # may set last_syntax_error again if a SyntaxError is raised
1215 1237 self.safe_execfile(err.filename,self.shell.user_ns)
1216 1238 except:
1217 1239 self.showtraceback()
1218 1240 else:
1219 1241 f = file(err.filename)
1220 1242 try:
1221 1243 sys.displayhook(f.read())
1222 1244 finally:
1223 1245 f.close()
1224 1246
1225 1247 def showsyntaxerror(self, filename=None):
1226 1248 """Display the syntax error that just occurred.
1227 1249
1228 1250 This doesn't display a stack trace because there isn't one.
1229 1251
1230 1252 If a filename is given, it is stuffed in the exception instead
1231 1253 of what was there before (because Python's parser always uses
1232 1254 "<string>" when reading from a string).
1233 1255 """
1234 1256 etype, value, last_traceback = sys.exc_info()
1235 1257 if filename and etype is SyntaxError:
1236 1258 # Work hard to stuff the correct filename in the exception
1237 1259 try:
1238 1260 msg, (dummy_filename, lineno, offset, line) = value
1239 1261 except:
1240 1262 # Not the format we expect; leave it alone
1241 1263 pass
1242 1264 else:
1243 1265 # Stuff in the right filename
1244 1266 try:
1245 1267 # Assume SyntaxError is a class exception
1246 1268 value = SyntaxError(msg, (filename, lineno, offset, line))
1247 1269 except:
1248 1270 # If that failed, assume SyntaxError is a string
1249 1271 value = msg, (filename, lineno, offset, line)
1250 1272 self.SyntaxTB(etype,value,[])
1251 1273
1252 1274 def debugger(self):
1253 1275 """Call the pdb debugger."""
1254 1276
1255 1277 if not self.rc.pdb:
1256 1278 return
1257 1279 pdb.pm()
1258 1280
1259 1281 def showtraceback(self,exc_tuple = None,filename=None):
1260 1282 """Display the exception that just occurred."""
1261 1283
1262 1284 # Though this won't be called by syntax errors in the input line,
1263 1285 # there may be SyntaxError cases whith imported code.
1264 1286 if exc_tuple is None:
1265 1287 type, value, tb = sys.exc_info()
1266 1288 else:
1267 1289 type, value, tb = exc_tuple
1268 1290 if type is SyntaxError:
1269 1291 self.showsyntaxerror(filename)
1270 1292 else:
1271 1293 self.InteractiveTB()
1272 1294 if self.InteractiveTB.call_pdb and self.has_readline:
1273 1295 # pdb mucks up readline, fix it back
1274 1296 self.readline.set_completer(self.Completer.complete)
1275 1297
1276 1298 def mainloop(self,banner=None):
1277 1299 """Creates the local namespace and starts the mainloop.
1278 1300
1279 1301 If an optional banner argument is given, it will override the
1280 1302 internally created default banner."""
1281 1303
1282 1304 if self.rc.c: # Emulate Python's -c option
1283 1305 self.exec_init_cmd()
1284 1306 if banner is None:
1285 1307 if self.rc.banner:
1286 1308 banner = self.BANNER+self.banner2
1287 1309 else:
1288 1310 banner = ''
1289 1311 self.interact(banner)
1290 1312
1291 1313 def exec_init_cmd(self):
1292 1314 """Execute a command given at the command line.
1293 1315
1294 1316 This emulates Python's -c option."""
1295 1317
1296 1318 sys.argv = ['-c']
1297 1319 self.push(self.rc.c)
1298 1320
1299 1321 def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0):
1300 1322 """Embeds IPython into a running python program.
1301 1323
1302 1324 Input:
1303 1325
1304 1326 - header: An optional header message can be specified.
1305 1327
1306 1328 - local_ns, global_ns: working namespaces. If given as None, the
1307 1329 IPython-initialized one is updated with __main__.__dict__, so that
1308 1330 program variables become visible but user-specific configuration
1309 1331 remains possible.
1310 1332
1311 1333 - stack_depth: specifies how many levels in the stack to go to
1312 1334 looking for namespaces (when local_ns and global_ns are None). This
1313 1335 allows an intermediate caller to make sure that this function gets
1314 1336 the namespace from the intended level in the stack. By default (0)
1315 1337 it will get its locals and globals from the immediate caller.
1316 1338
1317 1339 Warning: it's possible to use this in a program which is being run by
1318 1340 IPython itself (via %run), but some funny things will happen (a few
1319 1341 globals get overwritten). In the future this will be cleaned up, as
1320 1342 there is no fundamental reason why it can't work perfectly."""
1321 1343
1322 1344 # Get locals and globals from caller
1323 1345 if local_ns is None or global_ns is None:
1324 1346 call_frame = sys._getframe(stack_depth).f_back
1325 1347
1326 1348 if local_ns is None:
1327 1349 local_ns = call_frame.f_locals
1328 1350 if global_ns is None:
1329 1351 global_ns = call_frame.f_globals
1330 1352
1331 1353 # Update namespaces and fire up interpreter
1332 1354
1333 1355 # The global one is easy, we can just throw it in
1334 1356 self.user_global_ns = global_ns
1335 1357
1336 1358 # but the user/local one is tricky: ipython needs it to store internal
1337 1359 # data, but we also need the locals. We'll copy locals in the user
1338 1360 # one, but will track what got copied so we can delete them at exit.
1339 1361 # This is so that a later embedded call doesn't see locals from a
1340 1362 # previous call (which most likely existed in a separate scope).
1341 1363 local_varnames = local_ns.keys()
1342 1364 self.user_ns.update(local_ns)
1343 1365
1344 1366 # Patch for global embedding to make sure that things don't overwrite
1345 1367 # user globals accidentally. Thanks to Richard <rxe@renre-europe.com>
1346 1368 # FIXME. Test this a bit more carefully (the if.. is new)
1347 1369 if local_ns is None and global_ns is None:
1348 1370 self.user_global_ns.update(__main__.__dict__)
1349 1371
1350 1372 # make sure the tab-completer has the correct frame information, so it
1351 1373 # actually completes using the frame's locals/globals
1352 1374 self.set_completer_frame()
1353 1375
1354 1376 # before activating the interactive mode, we need to make sure that
1355 1377 # all names in the builtin namespace needed by ipython point to
1356 1378 # ourselves, and not to other instances.
1357 1379 self.add_builtins()
1358 1380
1359 1381 self.interact(header)
1360 1382
1361 1383 # now, purge out the user namespace from anything we might have added
1362 1384 # from the caller's local namespace
1363 1385 delvar = self.user_ns.pop
1364 1386 for var in local_varnames:
1365 1387 delvar(var,None)
1366 1388 # and clean builtins we may have overridden
1367 1389 self.clean_builtins()
1368 1390
1369 1391 def interact(self, banner=None):
1370 1392 """Closely emulate the interactive Python console.
1371 1393
1372 1394 The optional banner argument specify the banner to print
1373 1395 before the first interaction; by default it prints a banner
1374 1396 similar to the one printed by the real Python interpreter,
1375 1397 followed by the current class name in parentheses (so as not
1376 1398 to confuse this with the real interpreter -- since it's so
1377 1399 close!).
1378 1400
1379 1401 """
1380 1402 cprt = 'Type "copyright", "credits" or "license" for more information.'
1381 1403 if banner is None:
1382 1404 self.write("Python %s on %s\n%s\n(%s)\n" %
1383 1405 (sys.version, sys.platform, cprt,
1384 1406 self.__class__.__name__))
1385 1407 else:
1386 1408 self.write(banner)
1387 1409
1388 1410 more = 0
1389 1411
1390 1412 # Mark activity in the builtins
1391 1413 __builtin__.__dict__['__IPYTHON__active'] += 1
1392 1414
1393 1415 # exit_now is set by a call to %Exit or %Quit
1394 1416 self.exit_now = False
1395 1417 while not self.exit_now:
1396 1418
1397 1419 try:
1398 1420 if more:
1399 1421 prompt = self.outputcache.prompt2
1400 1422 if self.autoindent:
1401 1423 self.readline_startup_hook(self.pre_readline)
1402 1424 else:
1403 1425 prompt = self.outputcache.prompt1
1404 1426 try:
1405 1427 line = self.raw_input(prompt,more)
1406 1428 if self.autoindent:
1407 1429 self.readline_startup_hook(None)
1408 1430 except EOFError:
1409 1431 if self.autoindent:
1410 1432 self.readline_startup_hook(None)
1411 1433 self.write("\n")
1412 1434 self.exit()
1413 1435 else:
1414 1436 more = self.push(line)
1415 1437
1416 1438 if (self.SyntaxTB.last_syntax_error and
1417 1439 self.rc.autoedit_syntax):
1418 1440 self.edit_syntax_error()
1419 1441
1420 1442 except KeyboardInterrupt:
1421 1443 self.write("\nKeyboardInterrupt\n")
1422 1444 self.resetbuffer()
1423 1445 more = 0
1424 1446 # keep cache in sync with the prompt counter:
1425 1447 self.outputcache.prompt_count -= 1
1426 1448
1427 1449 if self.autoindent:
1428 1450 self.indent_current_nsp = 0
1429 1451 self.indent_current = ' '* self.indent_current_nsp
1430 1452
1431 1453 except bdb.BdbQuit:
1432 1454 warn("The Python debugger has exited with a BdbQuit exception.\n"
1433 1455 "Because of how pdb handles the stack, it is impossible\n"
1434 1456 "for IPython to properly format this particular exception.\n"
1435 1457 "IPython will resume normal operation.")
1436 1458
1437 1459 # We are off again...
1438 1460 __builtin__.__dict__['__IPYTHON__active'] -= 1
1439 1461
1440 1462 def excepthook(self, type, value, tb):
1441 1463 """One more defense for GUI apps that call sys.excepthook.
1442 1464
1443 1465 GUI frameworks like wxPython trap exceptions and call
1444 1466 sys.excepthook themselves. I guess this is a feature that
1445 1467 enables them to keep running after exceptions that would
1446 1468 otherwise kill their mainloop. This is a bother for IPython
1447 1469 which excepts to catch all of the program exceptions with a try:
1448 1470 except: statement.
1449 1471
1450 1472 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1451 1473 any app directly invokes sys.excepthook, it will look to the user like
1452 1474 IPython crashed. In order to work around this, we can disable the
1453 1475 CrashHandler and replace it with this excepthook instead, which prints a
1454 1476 regular traceback using our InteractiveTB. In this fashion, apps which
1455 1477 call sys.excepthook will generate a regular-looking exception from
1456 1478 IPython, and the CrashHandler will only be triggered by real IPython
1457 1479 crashes.
1458 1480
1459 1481 This hook should be used sparingly, only in places which are not likely
1460 1482 to be true IPython errors.
1461 1483 """
1462 1484
1463 1485 self.InteractiveTB(type, value, tb, tb_offset=0)
1464 1486 if self.InteractiveTB.call_pdb and self.has_readline:
1465 1487 self.readline.set_completer(self.Completer.complete)
1466 1488
1467 1489 def call_alias(self,alias,rest=''):
1468 1490 """Call an alias given its name and the rest of the line.
1469 1491
1470 1492 This function MUST be given a proper alias, because it doesn't make
1471 1493 any checks when looking up into the alias table. The caller is
1472 1494 responsible for invoking it only with a valid alias."""
1473 1495
1474 1496 #print 'ALIAS: <%s>+<%s>' % (alias,rest) # dbg
1475 1497 nargs,cmd = self.alias_table[alias]
1476 1498 # Expand the %l special to be the user's input line
1477 1499 if cmd.find('%l') >= 0:
1478 1500 cmd = cmd.replace('%l',rest)
1479 1501 rest = ''
1480 1502 if nargs==0:
1481 1503 # Simple, argument-less aliases
1482 1504 cmd = '%s %s' % (cmd,rest)
1483 1505 else:
1484 1506 # Handle aliases with positional arguments
1485 1507 args = rest.split(None,nargs)
1486 1508 if len(args)< nargs:
1487 1509 error('Alias <%s> requires %s arguments, %s given.' %
1488 1510 (alias,nargs,len(args)))
1489 1511 return
1490 1512 cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
1491 1513 # Now call the macro, evaluating in the user's namespace
1492 1514 try:
1493 1515 self.system(cmd)
1494 1516 except:
1495 1517 self.showtraceback()
1496 1518
1497 1519 def autoindent_update(self,line):
1498 1520 """Keep track of the indent level."""
1521
1499 1522 if self.autoindent:
1500 1523 if line:
1501 ini_spaces = ini_spaces_re.match(line)
1502 if ini_spaces:
1503 nspaces = ini_spaces.end()
1504 else:
1505 nspaces = 0
1506 self.indent_current_nsp = nspaces
1524 self.indent_current_nsp = num_ini_spaces(line)
1507 1525
1508 1526 if line[-1] == ':':
1509 1527 self.indent_current_nsp += 4
1510 1528 elif dedent_re.match(line):
1511 1529 self.indent_current_nsp -= 4
1512 1530 else:
1513 1531 self.indent_current_nsp = 0
1514 1532
1515 1533 # indent_current is the actual string to be inserted
1516 1534 # by the readline hooks for indentation
1517 1535 self.indent_current = ' '* self.indent_current_nsp
1518 1536
1519 1537 def runlines(self,lines):
1520 1538 """Run a string of one or more lines of source.
1521 1539
1522 1540 This method is capable of running a string containing multiple source
1523 1541 lines, as if they had been entered at the IPython prompt. Since it
1524 1542 exposes IPython's processing machinery, the given strings can contain
1525 1543 magic calls (%magic), special shell access (!cmd), etc."""
1526 1544
1527 1545 # We must start with a clean buffer, in case this is run from an
1528 1546 # interactive IPython session (via a magic, for example).
1529 1547 self.resetbuffer()
1530 1548 lines = lines.split('\n')
1531 1549 more = 0
1532 1550 for line in lines:
1533 1551 # skip blank lines so we don't mess up the prompt counter, but do
1534 1552 # NOT skip even a blank line if we are in a code block (more is
1535 1553 # true)
1536 1554 if line or more:
1537 1555 more = self.push(self.prefilter(line,more))
1538 1556 # IPython's runsource returns None if there was an error
1539 1557 # compiling the code. This allows us to stop processing right
1540 1558 # away, so the user gets the error message at the right place.
1541 1559 if more is None:
1542 1560 break
1543 1561 # final newline in case the input didn't have it, so that the code
1544 1562 # actually does get executed
1545 1563 if more:
1546 1564 self.push('\n')
1547 1565
1548 1566 def runsource(self, source, filename='<input>', symbol='single'):
1549 1567 """Compile and run some source in the interpreter.
1550 1568
1551 1569 Arguments are as for compile_command().
1552 1570
1553 1571 One several things can happen:
1554 1572
1555 1573 1) The input is incorrect; compile_command() raised an
1556 1574 exception (SyntaxError or OverflowError). A syntax traceback
1557 1575 will be printed by calling the showsyntaxerror() method.
1558 1576
1559 1577 2) The input is incomplete, and more input is required;
1560 1578 compile_command() returned None. Nothing happens.
1561 1579
1562 1580 3) The input is complete; compile_command() returned a code
1563 1581 object. The code is executed by calling self.runcode() (which
1564 1582 also handles run-time exceptions, except for SystemExit).
1565 1583
1566 1584 The return value is:
1567 1585
1568 1586 - True in case 2
1569 1587
1570 1588 - False in the other cases, unless an exception is raised, where
1571 1589 None is returned instead. This can be used by external callers to
1572 1590 know whether to continue feeding input or not.
1573 1591
1574 1592 The return value can be used to decide whether to use sys.ps1 or
1575 1593 sys.ps2 to prompt the next line."""
1576 1594
1577 1595 try:
1578 1596 code = self.compile(source,filename,symbol)
1579 1597 except (OverflowError, SyntaxError, ValueError):
1580 1598 # Case 1
1581 1599 self.showsyntaxerror(filename)
1582 1600 return None
1583 1601
1584 1602 if code is None:
1585 1603 # Case 2
1586 1604 return True
1587 1605
1588 1606 # Case 3
1589 1607 # We store the code object so that threaded shells and
1590 1608 # custom exception handlers can access all this info if needed.
1591 1609 # The source corresponding to this can be obtained from the
1592 1610 # buffer attribute as '\n'.join(self.buffer).
1593 1611 self.code_to_run = code
1594 1612 # now actually execute the code object
1595 1613 if self.runcode(code) == 0:
1596 1614 return False
1597 1615 else:
1598 1616 return None
1599 1617
1600 1618 def runcode(self,code_obj):
1601 1619 """Execute a code object.
1602 1620
1603 1621 When an exception occurs, self.showtraceback() is called to display a
1604 1622 traceback.
1605 1623
1606 1624 Return value: a flag indicating whether the code to be run completed
1607 1625 successfully:
1608 1626
1609 1627 - 0: successful execution.
1610 1628 - 1: an error occurred.
1611 1629 """
1612 1630
1613 1631 # Set our own excepthook in case the user code tries to call it
1614 1632 # directly, so that the IPython crash handler doesn't get triggered
1615 1633 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
1616 1634
1617 1635 # we save the original sys.excepthook in the instance, in case config
1618 1636 # code (such as magics) needs access to it.
1619 1637 self.sys_excepthook = old_excepthook
1620 1638 outflag = 1 # happens in more places, so it's easier as default
1621 1639 try:
1622 1640 try:
1623 1641 # Embedded instances require separate global/local namespaces
1624 1642 # so they can see both the surrounding (local) namespace and
1625 1643 # the module-level globals when called inside another function.
1626 1644 if self.embedded:
1627 1645 exec code_obj in self.user_global_ns, self.user_ns
1628 1646 # Normal (non-embedded) instances should only have a single
1629 1647 # namespace for user code execution, otherwise functions won't
1630 1648 # see interactive top-level globals.
1631 1649 else:
1632 1650 exec code_obj in self.user_ns
1633 1651 finally:
1634 1652 # Reset our crash handler in place
1635 1653 sys.excepthook = old_excepthook
1636 1654 except SystemExit:
1637 1655 self.resetbuffer()
1638 1656 self.showtraceback()
1639 1657 warn("Type exit or quit to exit IPython "
1640 1658 "(%Exit or %Quit do so unconditionally).",level=1)
1641 1659 except self.custom_exceptions:
1642 1660 etype,value,tb = sys.exc_info()
1643 1661 self.CustomTB(etype,value,tb)
1644 1662 except:
1645 1663 self.showtraceback()
1646 1664 else:
1647 1665 outflag = 0
1648 1666 if softspace(sys.stdout, 0):
1649 1667 print
1650 1668 # Flush out code object which has been run (and source)
1651 1669 self.code_to_run = None
1652 1670 return outflag
1653 1671
1654 1672 def push(self, line):
1655 1673 """Push a line to the interpreter.
1656 1674
1657 1675 The line should not have a trailing newline; it may have
1658 1676 internal newlines. The line is appended to a buffer and the
1659 1677 interpreter's runsource() method is called with the
1660 1678 concatenated contents of the buffer as source. If this
1661 1679 indicates that the command was executed or invalid, the buffer
1662 1680 is reset; otherwise, the command is incomplete, and the buffer
1663 1681 is left as it was after the line was appended. The return
1664 1682 value is 1 if more input is required, 0 if the line was dealt
1665 1683 with in some way (this is the same as runsource()).
1666 1684 """
1667 1685
1668 1686 # autoindent management should be done here, and not in the
1669 1687 # interactive loop, since that one is only seen by keyboard input. We
1670 1688 # need this done correctly even for code run via runlines (which uses
1671 1689 # push).
1672 1690
1673 1691 #print 'push line: <%s>' % line # dbg
1674 1692 self.autoindent_update(line)
1675 1693
1676 1694 self.buffer.append(line)
1677 1695 more = self.runsource('\n'.join(self.buffer), self.filename)
1678 1696 if not more:
1679 1697 self.resetbuffer()
1680 1698 return more
1681 1699
1682 1700 def resetbuffer(self):
1683 1701 """Reset the input buffer."""
1684 1702 self.buffer[:] = []
1685 1703
1686 1704 def raw_input(self,prompt='',continue_prompt=False):
1687 1705 """Write a prompt and read a line.
1688 1706
1689 1707 The returned line does not include the trailing newline.
1690 1708 When the user enters the EOF key sequence, EOFError is raised.
1691 1709
1692 1710 Optional inputs:
1693 1711
1694 1712 - prompt(''): a string to be printed to prompt the user.
1695 1713
1696 1714 - continue_prompt(False): whether this line is the first one or a
1697 1715 continuation in a sequence of inputs.
1698 1716 """
1699 1717
1700 1718 line = raw_input_original(prompt)
1701 1719 # Try to be reasonably smart about not re-indenting pasted input more
1702 1720 # than necessary. We do this by trimming out the auto-indent initial
1703 1721 # spaces, if the user's actual input started itself with whitespace.
1704 if self.autoindent:
1705 line2 = line[self.indent_current_nsp:]
1706 if line2[0:1] in (' ','\t'):
1707 line = line2
1722 #debugp('self.buffer[-1]')
1723 ## if self.autoindent:
1724 ## try:
1725 ## prev_line = self.buffer[-1]
1726 ## except IndexError:
1727 ## prev_line = ''
1728 ## prev_indent = num_ini_spaces(prev_line)
1729 ## debugp('prev_indent')
1730 ## # Split the user's input
1731 ## line1 = line[:self.indent_current_nsp]
1732 ## line2 = line[self.indent_current_nsp:]
1733 ## if line1.isspace() and line2 and \
1734 ## num_ini_spaces(line2)==prev_indent:
1735 ## line = line2
1736 #debugp('line')
1737 #debugp('line1')
1738 #debugp('line2')
1739 ## if line1.isspace() and line2 and line2[0:1] in (' ','\t'):
1740 ## line = line2
1741 ## debugp('line')
1708 1742 return self.prefilter(line,continue_prompt)
1709 1743
1710 1744 def split_user_input(self,line):
1711 1745 """Split user input into pre-char, function part and rest."""
1712 1746
1713 1747 lsplit = self.line_split.match(line)
1714 1748 if lsplit is None: # no regexp match returns None
1715 1749 try:
1716 1750 iFun,theRest = line.split(None,1)
1717 1751 except ValueError:
1718 1752 iFun,theRest = line,''
1719 1753 pre = re.match('^(\s*)(.*)',line).groups()[0]
1720 1754 else:
1721 1755 pre,iFun,theRest = lsplit.groups()
1722 1756
1723 1757 #print 'line:<%s>' % line # dbg
1724 1758 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun.strip(),theRest) # dbg
1725 1759 return pre,iFun.strip(),theRest
1726 1760
1727 1761 def _prefilter(self, line, continue_prompt):
1728 1762 """Calls different preprocessors, depending on the form of line."""
1729 1763
1730 1764 # All handlers *must* return a value, even if it's blank ('').
1731 1765
1732 1766 # Lines are NOT logged here. Handlers should process the line as
1733 1767 # needed, update the cache AND log it (so that the input cache array
1734 1768 # stays synced).
1735 1769
1736 1770 # This function is _very_ delicate, and since it's also the one which
1737 1771 # determines IPython's response to user input, it must be as efficient
1738 1772 # as possible. For this reason it has _many_ returns in it, trying
1739 1773 # always to exit as quickly as it can figure out what it needs to do.
1740 1774
1741 1775 # This function is the main responsible for maintaining IPython's
1742 1776 # behavior respectful of Python's semantics. So be _very_ careful if
1743 1777 # making changes to anything here.
1744 1778
1745 1779 #.....................................................................
1746 1780 # Code begins
1747 1781
1748 1782 #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg
1749 1783
1750 1784 # save the line away in case we crash, so the post-mortem handler can
1751 1785 # record it
1752 1786 self._last_input_line = line
1753 1787
1754 1788 #print '***line: <%s>' % line # dbg
1755 1789
1756 1790 # the input history needs to track even empty lines
1757 1791 if not line.strip():
1758 1792 if not continue_prompt:
1759 1793 self.outputcache.prompt_count -= 1
1760 1794 return self.handle_normal(line,continue_prompt)
1761 1795 #return self.handle_normal('',continue_prompt)
1762 1796
1763 1797 # print '***cont',continue_prompt # dbg
1764 1798 # special handlers are only allowed for single line statements
1765 1799 if continue_prompt and not self.rc.multi_line_specials:
1766 1800 return self.handle_normal(line,continue_prompt)
1767 1801
1768 1802 # For the rest, we need the structure of the input
1769 1803 pre,iFun,theRest = self.split_user_input(line)
1770 1804 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
1771 1805
1772 1806 # First check for explicit escapes in the last/first character
1773 1807 handler = None
1774 1808 if line[-1] == self.ESC_HELP:
1775 1809 handler = self.esc_handlers.get(line[-1]) # the ? can be at the end
1776 1810 if handler is None:
1777 1811 # look at the first character of iFun, NOT of line, so we skip
1778 1812 # leading whitespace in multiline input
1779 1813 handler = self.esc_handlers.get(iFun[0:1])
1780 1814 if handler is not None:
1781 1815 return handler(line,continue_prompt,pre,iFun,theRest)
1782 1816 # Emacs ipython-mode tags certain input lines
1783 1817 if line.endswith('# PYTHON-MODE'):
1784 1818 return self.handle_emacs(line,continue_prompt)
1785 1819
1786 1820 # Next, check if we can automatically execute this thing
1787 1821
1788 1822 # Allow ! in multi-line statements if multi_line_specials is on:
1789 1823 if continue_prompt and self.rc.multi_line_specials and \
1790 1824 iFun.startswith(self.ESC_SHELL):
1791 1825 return self.handle_shell_escape(line,continue_prompt,
1792 1826 pre=pre,iFun=iFun,
1793 1827 theRest=theRest)
1794 1828
1795 1829 # Let's try to find if the input line is a magic fn
1796 1830 oinfo = None
1797 1831 if hasattr(self,'magic_'+iFun):
1798 1832 # WARNING: _ofind uses getattr(), so it can consume generators and
1799 1833 # cause other side effects.
1800 1834 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
1801 1835 if oinfo['ismagic']:
1802 1836 # Be careful not to call magics when a variable assignment is
1803 1837 # being made (ls='hi', for example)
1804 1838 if self.rc.automagic and \
1805 1839 (len(theRest)==0 or theRest[0] not in '!=()<>,') and \
1806 1840 (self.rc.multi_line_specials or not continue_prompt):
1807 1841 return self.handle_magic(line,continue_prompt,
1808 1842 pre,iFun,theRest)
1809 1843 else:
1810 1844 return self.handle_normal(line,continue_prompt)
1811 1845
1812 1846 # If the rest of the line begins with an (in)equality, assginment or
1813 1847 # function call, we should not call _ofind but simply execute it.
1814 1848 # This avoids spurious geattr() accesses on objects upon assignment.
1815 1849 #
1816 1850 # It also allows users to assign to either alias or magic names true
1817 1851 # python variables (the magic/alias systems always take second seat to
1818 1852 # true python code).
1819 1853 if theRest and theRest[0] in '!=()':
1820 1854 return self.handle_normal(line,continue_prompt)
1821 1855
1822 1856 if oinfo is None:
1823 1857 # let's try to ensure that _oinfo is ONLY called when autocall is
1824 1858 # on. Since it has inevitable potential side effects, at least
1825 1859 # having autocall off should be a guarantee to the user that no
1826 1860 # weird things will happen.
1827 1861
1828 1862 if self.rc.autocall:
1829 1863 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
1830 1864 else:
1831 1865 # in this case, all that's left is either an alias or
1832 1866 # processing the line normally.
1833 1867 if iFun in self.alias_table:
1834 1868 return self.handle_alias(line,continue_prompt,
1835 1869 pre,iFun,theRest)
1836 1870 else:
1837 1871 return self.handle_normal(line,continue_prompt)
1838 1872
1839 1873 if not oinfo['found']:
1840 1874 return self.handle_normal(line,continue_prompt)
1841 1875 else:
1842 1876 #print 'iFun <%s> rest <%s>' % (iFun,theRest) # dbg
1843 1877 if oinfo['isalias']:
1844 1878 return self.handle_alias(line,continue_prompt,
1845 1879 pre,iFun,theRest)
1846 1880
1847 1881 if self.rc.autocall and \
1848 1882 not self.re_exclude_auto.match(theRest) and \
1849 1883 self.re_fun_name.match(iFun) and \
1850 1884 callable(oinfo['obj']) :
1851 1885 #print 'going auto' # dbg
1852 1886 return self.handle_auto(line,continue_prompt,
1853 1887 pre,iFun,theRest,oinfo['obj'])
1854 1888 else:
1855 1889 #print 'was callable?', callable(oinfo['obj']) # dbg
1856 1890 return self.handle_normal(line,continue_prompt)
1857 1891
1858 1892 # If we get here, we have a normal Python line. Log and return.
1859 1893 return self.handle_normal(line,continue_prompt)
1860 1894
1861 1895 def _prefilter_dumb(self, line, continue_prompt):
1862 1896 """simple prefilter function, for debugging"""
1863 1897 return self.handle_normal(line,continue_prompt)
1864 1898
1865 1899 # Set the default prefilter() function (this can be user-overridden)
1866 1900 prefilter = _prefilter
1867 1901
1868 1902 def handle_normal(self,line,continue_prompt=None,
1869 1903 pre=None,iFun=None,theRest=None):
1870 1904 """Handle normal input lines. Use as a template for handlers."""
1871 1905
1872 1906 # With autoindent on, we need some way to exit the input loop, and I
1873 1907 # don't want to force the user to have to backspace all the way to
1874 1908 # clear the line. The rule will be in this case, that either two
1875 1909 # lines of pure whitespace in a row, or a line of pure whitespace but
1876 1910 # of a size different to the indent level, will exit the input loop.
1877 1911
1878 if (continue_prompt and self.autoindent and isspace(line) and
1879 (line != self.indent_current or isspace(self.buffer[-1]))):
1912 if (continue_prompt and self.autoindent and line.isspace() and
1913 (line != self.indent_current or (self.buffer[-1]).isspace() )):
1880 1914 line = ''
1881 1915
1882 1916 self.log(line,continue_prompt)
1883 1917 return line
1884 1918
1885 1919 def handle_alias(self,line,continue_prompt=None,
1886 1920 pre=None,iFun=None,theRest=None):
1887 1921 """Handle alias input lines. """
1888 1922
1889 1923 # pre is needed, because it carries the leading whitespace. Otherwise
1890 1924 # aliases won't work in indented sections.
1891 1925 line_out = '%sipalias(%s)' % (pre,make_quoted_expr(iFun + " " + theRest))
1892 1926 self.log(line_out,continue_prompt)
1893 1927 return line_out
1894 1928
1895 1929 def handle_shell_escape(self, line, continue_prompt=None,
1896 1930 pre=None,iFun=None,theRest=None):
1897 1931 """Execute the line in a shell, empty return value"""
1898 1932
1899 1933 #print 'line in :', `line` # dbg
1900 1934 # Example of a special handler. Others follow a similar pattern.
1901 1935 if line.lstrip().startswith('!!'):
1902 1936 # rewrite iFun/theRest to properly hold the call to %sx and
1903 1937 # the actual command to be executed, so handle_magic can work
1904 1938 # correctly
1905 1939 theRest = '%s %s' % (iFun[2:],theRest)
1906 1940 iFun = 'sx'
1907 1941 return self.handle_magic('%ssx %s' % (self.ESC_MAGIC,line[2:]),
1908 1942 continue_prompt,pre,iFun,theRest)
1909 1943 else:
1910 1944 cmd=line.lstrip()[1:]
1911 1945 line_out = '%sipsystem(%s)' % (pre,make_quoted_expr(cmd))
1912 1946 # update cache/log and return
1913 1947 self.log(line_out,continue_prompt)
1914 1948 return line_out
1915 1949
1916 1950 def handle_magic(self, line, continue_prompt=None,
1917 1951 pre=None,iFun=None,theRest=None):
1918 1952 """Execute magic functions."""
1919 1953
1920 1954
1921 1955 cmd = '%sipmagic(%s)' % (pre,make_quoted_expr(iFun + " " + theRest))
1922 1956 self.log(cmd,continue_prompt)
1923 1957 #print 'in handle_magic, cmd=<%s>' % cmd # dbg
1924 1958 return cmd
1925 1959
1926 1960 def handle_auto(self, line, continue_prompt=None,
1927 1961 pre=None,iFun=None,theRest=None,obj=None):
1928 1962 """Hande lines which can be auto-executed, quoting if requested."""
1929 1963
1930 1964 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
1931 1965
1932 1966 # This should only be active for single-line input!
1933 1967 if continue_prompt:
1934 1968 self.log(line,continue_prompt)
1935 1969 return line
1936 1970
1937 1971 auto_rewrite = True
1938 1972 if pre == self.ESC_QUOTE:
1939 1973 # Auto-quote splitting on whitespace
1940 1974 newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) )
1941 1975 elif pre == self.ESC_QUOTE2:
1942 1976 # Auto-quote whole string
1943 1977 newcmd = '%s("%s")' % (iFun,theRest)
1944 1978 else:
1945 1979 # Auto-paren.
1946 1980 # We only apply it to argument-less calls if the autocall
1947 1981 # parameter is set to 2. We only need to check that autocall is <
1948 1982 # 2, since this function isn't called unless it's at least 1.
1949 1983 if not theRest and (self.rc.autocall < 2):
1950 1984 newcmd = '%s %s' % (iFun,theRest)
1951 1985 auto_rewrite = False
1952 1986 else:
1953 1987 if theRest.startswith('['):
1954 1988 if hasattr(obj,'__getitem__'):
1955 1989 # Don't autocall in this case: item access for an object
1956 1990 # which is BOTH callable and implements __getitem__.
1957 1991 newcmd = '%s %s' % (iFun,theRest)
1958 1992 auto_rewrite = False
1959 1993 else:
1960 1994 # if the object doesn't support [] access, go ahead and
1961 1995 # autocall
1962 1996 newcmd = '%s(%s)' % (iFun.rstrip(),theRest)
1963 1997 elif theRest.endswith(';'):
1964 1998 newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1])
1965 1999 else:
1966 2000 newcmd = '%s(%s)' % (iFun.rstrip(),theRest)
1967 2001
1968 2002 if auto_rewrite:
1969 2003 print >>Term.cout, self.outputcache.prompt1.auto_rewrite() + newcmd
1970 2004 # log what is now valid Python, not the actual user input (without the
1971 2005 # final newline)
1972 2006 self.log(newcmd,continue_prompt)
1973 2007 return newcmd
1974 2008
1975 2009 def handle_help(self, line, continue_prompt=None,
1976 2010 pre=None,iFun=None,theRest=None):
1977 2011 """Try to get some help for the object.
1978 2012
1979 2013 obj? or ?obj -> basic information.
1980 2014 obj?? or ??obj -> more details.
1981 2015 """
1982 2016
1983 2017 # We need to make sure that we don't process lines which would be
1984 2018 # otherwise valid python, such as "x=1 # what?"
1985 2019 try:
1986 2020 codeop.compile_command(line)
1987 2021 except SyntaxError:
1988 2022 # We should only handle as help stuff which is NOT valid syntax
1989 2023 if line[0]==self.ESC_HELP:
1990 2024 line = line[1:]
1991 2025 elif line[-1]==self.ESC_HELP:
1992 2026 line = line[:-1]
1993 2027 self.log('#?'+line)
1994 2028 if line:
1995 2029 self.magic_pinfo(line)
1996 2030 else:
1997 2031 page(self.usage,screen_lines=self.rc.screen_length)
1998 2032 return '' # Empty string is needed here!
1999 2033 except:
2000 2034 # Pass any other exceptions through to the normal handler
2001 2035 return self.handle_normal(line,continue_prompt)
2002 2036 else:
2003 2037 # If the code compiles ok, we should handle it normally
2004 2038 return self.handle_normal(line,continue_prompt)
2005 2039
2006 2040 def handle_emacs(self,line,continue_prompt=None,
2007 2041 pre=None,iFun=None,theRest=None):
2008 2042 """Handle input lines marked by python-mode."""
2009 2043
2010 2044 # Currently, nothing is done. Later more functionality can be added
2011 2045 # here if needed.
2012 2046
2013 2047 # The input cache shouldn't be updated
2014 2048
2015 2049 return line
2016 2050
2017 2051 def mktempfile(self,data=None):
2018 2052 """Make a new tempfile and return its filename.
2019 2053
2020 2054 This makes a call to tempfile.mktemp, but it registers the created
2021 2055 filename internally so ipython cleans it up at exit time.
2022 2056
2023 2057 Optional inputs:
2024 2058
2025 2059 - data(None): if data is given, it gets written out to the temp file
2026 2060 immediately, and the file is closed again."""
2027 2061
2028 2062 filename = tempfile.mktemp('.py','ipython_edit_')
2029 2063 self.tempfiles.append(filename)
2030 2064
2031 2065 if data:
2032 2066 tmp_file = open(filename,'w')
2033 2067 tmp_file.write(data)
2034 2068 tmp_file.close()
2035 2069 return filename
2036 2070
2037 2071 def write(self,data):
2038 2072 """Write a string to the default output"""
2039 2073 Term.cout.write(data)
2040 2074
2041 2075 def write_err(self,data):
2042 2076 """Write a string to the default error output"""
2043 2077 Term.cerr.write(data)
2044 2078
2045 2079 def exit(self):
2046 2080 """Handle interactive exit.
2047 2081
2048 2082 This method sets the exit_now attribute."""
2049 2083
2050 2084 if self.rc.confirm_exit:
2051 2085 if ask_yes_no('Do you really want to exit ([y]/n)?','y'):
2052 2086 self.exit_now = True
2053 2087 else:
2054 2088 self.exit_now = True
2055 2089 return self.exit_now
2056 2090
2057 2091 def safe_execfile(self,fname,*where,**kw):
2058 2092 fname = os.path.expanduser(fname)
2059 2093
2060 2094 # find things also in current directory
2061 2095 dname = os.path.dirname(fname)
2062 2096 if not sys.path.count(dname):
2063 2097 sys.path.append(dname)
2064 2098
2065 2099 try:
2066 2100 xfile = open(fname)
2067 2101 except:
2068 2102 print >> Term.cerr, \
2069 2103 'Could not open file <%s> for safe execution.' % fname
2070 2104 return None
2071 2105
2072 2106 kw.setdefault('islog',0)
2073 2107 kw.setdefault('quiet',1)
2074 2108 kw.setdefault('exit_ignore',0)
2075 2109 first = xfile.readline()
2076 2110 loghead = str(self.loghead_tpl).split('\n',1)[0].strip()
2077 2111 xfile.close()
2078 2112 # line by line execution
2079 2113 if first.startswith(loghead) or kw['islog']:
2080 2114 print 'Loading log file <%s> one line at a time...' % fname
2081 2115 if kw['quiet']:
2082 2116 stdout_save = sys.stdout
2083 2117 sys.stdout = StringIO.StringIO()
2084 2118 try:
2085 2119 globs,locs = where[0:2]
2086 2120 except:
2087 2121 try:
2088 2122 globs = locs = where[0]
2089 2123 except:
2090 2124 globs = locs = globals()
2091 2125 badblocks = []
2092 2126
2093 2127 # we also need to identify indented blocks of code when replaying
2094 2128 # logs and put them together before passing them to an exec
2095 2129 # statement. This takes a bit of regexp and look-ahead work in the
2096 2130 # file. It's easiest if we swallow the whole thing in memory
2097 2131 # first, and manually walk through the lines list moving the
2098 2132 # counter ourselves.
2099 2133 indent_re = re.compile('\s+\S')
2100 2134 xfile = open(fname)
2101 2135 filelines = xfile.readlines()
2102 2136 xfile.close()
2103 2137 nlines = len(filelines)
2104 2138 lnum = 0
2105 2139 while lnum < nlines:
2106 2140 line = filelines[lnum]
2107 2141 lnum += 1
2108 2142 # don't re-insert logger status info into cache
2109 2143 if line.startswith('#log#'):
2110 2144 continue
2111 2145 else:
2112 2146 # build a block of code (maybe a single line) for execution
2113 2147 block = line
2114 2148 try:
2115 2149 next = filelines[lnum] # lnum has already incremented
2116 2150 except:
2117 2151 next = None
2118 2152 while next and indent_re.match(next):
2119 2153 block += next
2120 2154 lnum += 1
2121 2155 try:
2122 2156 next = filelines[lnum]
2123 2157 except:
2124 2158 next = None
2125 2159 # now execute the block of one or more lines
2126 2160 try:
2127 2161 exec block in globs,locs
2128 2162 except SystemExit:
2129 2163 pass
2130 2164 except:
2131 2165 badblocks.append(block.rstrip())
2132 2166 if kw['quiet']: # restore stdout
2133 2167 sys.stdout.close()
2134 2168 sys.stdout = stdout_save
2135 2169 print 'Finished replaying log file <%s>' % fname
2136 2170 if badblocks:
2137 2171 print >> sys.stderr, ('\nThe following lines/blocks in file '
2138 2172 '<%s> reported errors:' % fname)
2139 2173
2140 2174 for badline in badblocks:
2141 2175 print >> sys.stderr, badline
2142 2176 else: # regular file execution
2143 2177 try:
2144 2178 execfile(fname,*where)
2145 2179 except SyntaxError:
2146 2180 etype,evalue = sys.exc_info()[:2]
2147 2181 self.SyntaxTB(etype,evalue,[])
2148 2182 warn('Failure executing file: <%s>' % fname)
2149 2183 except SystemExit,status:
2150 2184 if not kw['exit_ignore']:
2151 2185 self.InteractiveTB()
2152 2186 warn('Failure executing file: <%s>' % fname)
2153 2187 except:
2154 2188 self.InteractiveTB()
2155 2189 warn('Failure executing file: <%s>' % fname)
2156 2190
2157 2191 #************************* end of file <iplib.py> *****************************
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