##// END OF EJS Templates
Merging upstream changes from trunk (after fixing small conflicts).
Fernando Perez -
r1872:d21e2734 merge
parent child Browse files
Show More
@@ -1,2158 +1,2161 b''
1 1 # -*- coding: utf-8 -*-
2 2 """General purpose utilities.
3 3
4 4 This is a grab-bag of stuff I find useful in most programs I write. Some of
5 5 these things are also convenient when working at the command line.
6 6 """
7 7
8 8 #*****************************************************************************
9 9 # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu>
10 10 #
11 11 # Distributed under the terms of the BSD License. The full license is in
12 12 # the file COPYING, distributed as part of this software.
13 13 #*****************************************************************************
14 14
15 15 #****************************************************************************
16 16 # required modules from the Python standard library
17 17 import __main__
18 18 import commands
19 19 try:
20 20 import doctest
21 21 except ImportError:
22 22 pass
23 23 import os
24 24 import platform
25 25 import re
26 26 import shlex
27 27 import shutil
28 28 import subprocess
29 29 import sys
30 30 import tempfile
31 31 import time
32 32 import types
33 33 import warnings
34 34
35 35 # Curses and termios are Unix-only modules
36 36 try:
37 37 import curses
38 38 # We need termios as well, so if its import happens to raise, we bail on
39 39 # using curses altogether.
40 40 import termios
41 41 except ImportError:
42 42 USE_CURSES = False
43 43 else:
44 44 # Curses on Solaris may not be complete, so we can't use it there
45 45 USE_CURSES = hasattr(curses,'initscr')
46 46
47 47 # Other IPython utilities
48 48 import IPython
49 49 from IPython.Itpl import Itpl,itpl,printpl
50 50 from IPython import DPyGetOpt, platutils
51 51 from IPython.generics import result_display
52 52 import IPython.ipapi
53 53 from IPython.external.path import path
54 54 if os.name == "nt":
55 55 from IPython.winconsole import get_console_size
56 56
57 57 try:
58 58 set
59 59 except:
60 60 from sets import Set as set
61 61
62 62
63 63 #****************************************************************************
64 64 # Exceptions
65 65 class Error(Exception):
66 66 """Base class for exceptions in this module."""
67 67 pass
68 68
69 69 #----------------------------------------------------------------------------
70 70 class IOStream:
71 71 def __init__(self,stream,fallback):
72 72 if not hasattr(stream,'write') or not hasattr(stream,'flush'):
73 73 stream = fallback
74 74 self.stream = stream
75 75 self._swrite = stream.write
76 76 self.flush = stream.flush
77 77
78 78 def write(self,data):
79 79 try:
80 80 self._swrite(data)
81 81 except:
82 82 try:
83 83 # print handles some unicode issues which may trip a plain
84 84 # write() call. Attempt to emulate write() by using a
85 85 # trailing comma
86 86 print >> self.stream, data,
87 87 except:
88 88 # if we get here, something is seriously broken.
89 89 print >> sys.stderr, \
90 90 'ERROR - failed to write data to stream:', self.stream
91 91
92 92 def close(self):
93 93 pass
94 94
95 95
96 96 class IOTerm:
97 97 """ Term holds the file or file-like objects for handling I/O operations.
98 98
99 99 These are normally just sys.stdin, sys.stdout and sys.stderr but for
100 100 Windows they can can replaced to allow editing the strings before they are
101 101 displayed."""
102 102
103 103 # In the future, having IPython channel all its I/O operations through
104 104 # this class will make it easier to embed it into other environments which
105 105 # are not a normal terminal (such as a GUI-based shell)
106 106 def __init__(self,cin=None,cout=None,cerr=None):
107 107 self.cin = IOStream(cin,sys.stdin)
108 108 self.cout = IOStream(cout,sys.stdout)
109 109 self.cerr = IOStream(cerr,sys.stderr)
110 110
111 111 # Global variable to be used for all I/O
112 112 Term = IOTerm()
113 113
114 114 import IPython.rlineimpl as readline
115 115 # Remake Term to use the readline i/o facilities
116 116 if sys.platform == 'win32' and readline.have_readline:
117 117
118 118 Term = IOTerm(cout=readline._outputfile,cerr=readline._outputfile)
119 119
120 120
121 121 #****************************************************************************
122 122 # Generic warning/error printer, used by everything else
123 123 def warn(msg,level=2,exit_val=1):
124 124 """Standard warning printer. Gives formatting consistency.
125 125
126 126 Output is sent to Term.cerr (sys.stderr by default).
127 127
128 128 Options:
129 129
130 130 -level(2): allows finer control:
131 131 0 -> Do nothing, dummy function.
132 132 1 -> Print message.
133 133 2 -> Print 'WARNING:' + message. (Default level).
134 134 3 -> Print 'ERROR:' + message.
135 135 4 -> Print 'FATAL ERROR:' + message and trigger a sys.exit(exit_val).
136 136
137 137 -exit_val (1): exit value returned by sys.exit() for a level 4
138 138 warning. Ignored for all other levels."""
139 139
140 140 if level>0:
141 141 header = ['','','WARNING: ','ERROR: ','FATAL ERROR: ']
142 142 print >> Term.cerr, '%s%s' % (header[level],msg)
143 143 if level == 4:
144 144 print >> Term.cerr,'Exiting.\n'
145 145 sys.exit(exit_val)
146 146
147 147 def info(msg):
148 148 """Equivalent to warn(msg,level=1)."""
149 149
150 150 warn(msg,level=1)
151 151
152 152 def error(msg):
153 153 """Equivalent to warn(msg,level=3)."""
154 154
155 155 warn(msg,level=3)
156 156
157 157 def fatal(msg,exit_val=1):
158 158 """Equivalent to warn(msg,exit_val=exit_val,level=4)."""
159 159
160 160 warn(msg,exit_val=exit_val,level=4)
161 161
162 162 #---------------------------------------------------------------------------
163 163 # Debugging routines
164 164 #
165 165 def debugx(expr,pre_msg=''):
166 166 """Print the value of an expression from the caller's frame.
167 167
168 168 Takes an expression, evaluates it in the caller's frame and prints both
169 169 the given expression and the resulting value (as well as a debug mark
170 170 indicating the name of the calling function. The input must be of a form
171 171 suitable for eval().
172 172
173 173 An optional message can be passed, which will be prepended to the printed
174 174 expr->value pair."""
175 175
176 176 cf = sys._getframe(1)
177 177 print '[DBG:%s] %s%s -> %r' % (cf.f_code.co_name,pre_msg,expr,
178 178 eval(expr,cf.f_globals,cf.f_locals))
179 179
180 180 # deactivate it by uncommenting the following line, which makes it a no-op
181 181 #def debugx(expr,pre_msg=''): pass
182 182
183 183 #----------------------------------------------------------------------------
184 184 StringTypes = types.StringTypes
185 185
186 186 # Basic timing functionality
187 187
188 188 # If possible (Unix), use the resource module instead of time.clock()
189 189 try:
190 190 import resource
191 191 def clocku():
192 192 """clocku() -> floating point number
193 193
194 194 Return the *USER* CPU time in seconds since the start of the process.
195 195 This is done via a call to resource.getrusage, so it avoids the
196 196 wraparound problems in time.clock()."""
197 197
198 198 return resource.getrusage(resource.RUSAGE_SELF)[0]
199 199
200 200 def clocks():
201 201 """clocks() -> floating point number
202 202
203 203 Return the *SYSTEM* CPU time in seconds since the start of the process.
204 204 This is done via a call to resource.getrusage, so it avoids the
205 205 wraparound problems in time.clock()."""
206 206
207 207 return resource.getrusage(resource.RUSAGE_SELF)[1]
208 208
209 209 def clock():
210 210 """clock() -> floating point number
211 211
212 212 Return the *TOTAL USER+SYSTEM* CPU time in seconds since the start of
213 213 the process. This is done via a call to resource.getrusage, so it
214 214 avoids the wraparound problems in time.clock()."""
215 215
216 216 u,s = resource.getrusage(resource.RUSAGE_SELF)[:2]
217 217 return u+s
218 218
219 219 def clock2():
220 220 """clock2() -> (t_user,t_system)
221 221
222 222 Similar to clock(), but return a tuple of user/system times."""
223 223 return resource.getrusage(resource.RUSAGE_SELF)[:2]
224 224
225 225 except ImportError:
226 226 # There is no distinction of user/system time under windows, so we just use
227 227 # time.clock() for everything...
228 228 clocku = clocks = clock = time.clock
229 229 def clock2():
230 230 """Under windows, system CPU time can't be measured.
231 231
232 232 This just returns clock() and zero."""
233 233 return time.clock(),0.0
234 234
235 235 def timings_out(reps,func,*args,**kw):
236 236 """timings_out(reps,func,*args,**kw) -> (t_total,t_per_call,output)
237 237
238 238 Execute a function reps times, return a tuple with the elapsed total
239 239 CPU time in seconds, the time per call and the function's output.
240 240
241 241 Under Unix, the return value is the sum of user+system time consumed by
242 242 the process, computed via the resource module. This prevents problems
243 243 related to the wraparound effect which the time.clock() function has.
244 244
245 245 Under Windows the return value is in wall clock seconds. See the
246 246 documentation for the time module for more details."""
247 247
248 248 reps = int(reps)
249 249 assert reps >=1, 'reps must be >= 1'
250 250 if reps==1:
251 251 start = clock()
252 252 out = func(*args,**kw)
253 253 tot_time = clock()-start
254 254 else:
255 255 rng = xrange(reps-1) # the last time is executed separately to store output
256 256 start = clock()
257 257 for dummy in rng: func(*args,**kw)
258 258 out = func(*args,**kw) # one last time
259 259 tot_time = clock()-start
260 260 av_time = tot_time / reps
261 261 return tot_time,av_time,out
262 262
263 263 def timings(reps,func,*args,**kw):
264 264 """timings(reps,func,*args,**kw) -> (t_total,t_per_call)
265 265
266 266 Execute a function reps times, return a tuple with the elapsed total CPU
267 267 time in seconds and the time per call. These are just the first two values
268 268 in timings_out()."""
269 269
270 270 return timings_out(reps,func,*args,**kw)[0:2]
271 271
272 272 def timing(func,*args,**kw):
273 273 """timing(func,*args,**kw) -> t_total
274 274
275 275 Execute a function once, return the elapsed total CPU time in
276 276 seconds. This is just the first value in timings_out()."""
277 277
278 278 return timings_out(1,func,*args,**kw)[0]
279 279
280 280 #****************************************************************************
281 281 # file and system
282 282
283 283 def arg_split(s,posix=False):
284 284 """Split a command line's arguments in a shell-like manner.
285 285
286 286 This is a modified version of the standard library's shlex.split()
287 287 function, but with a default of posix=False for splitting, so that quotes
288 288 in inputs are respected."""
289 289
290 290 # XXX - there may be unicode-related problems here!!! I'm not sure that
291 291 # shlex is truly unicode-safe, so it might be necessary to do
292 292 #
293 293 # s = s.encode(sys.stdin.encoding)
294 294 #
295 295 # first, to ensure that shlex gets a normal string. Input from anyone who
296 296 # knows more about unicode and shlex than I would be good to have here...
297 297 lex = shlex.shlex(s, posix=posix)
298 298 lex.whitespace_split = True
299 299 return list(lex)
300 300
301 301 def system(cmd,verbose=0,debug=0,header=''):
302 302 """Execute a system command, return its exit status.
303 303
304 304 Options:
305 305
306 306 - verbose (0): print the command to be executed.
307 307
308 308 - debug (0): only print, do not actually execute.
309 309
310 310 - header (''): Header to print on screen prior to the executed command (it
311 311 is only prepended to the command, no newlines are added).
312 312
313 313 Note: a stateful version of this function is available through the
314 314 SystemExec class."""
315 315
316 316 stat = 0
317 317 if verbose or debug: print header+cmd
318 318 sys.stdout.flush()
319 319 if not debug: stat = os.system(cmd)
320 320 return stat
321 321
322 322 def abbrev_cwd():
323 323 """ Return abbreviated version of cwd, e.g. d:mydir """
324 324 cwd = os.getcwd().replace('\\','/')
325 325 drivepart = ''
326 326 tail = cwd
327 327 if sys.platform == 'win32':
328 328 if len(cwd) < 4:
329 329 return cwd
330 330 drivepart,tail = os.path.splitdrive(cwd)
331 331
332 332
333 333 parts = tail.split('/')
334 334 if len(parts) > 2:
335 335 tail = '/'.join(parts[-2:])
336 336
337 337 return (drivepart + (
338 338 cwd == '/' and '/' or tail))
339 339
340 340
341 341 # This function is used by ipython in a lot of places to make system calls.
342 342 # We need it to be slightly different under win32, due to the vagaries of
343 343 # 'network shares'. A win32 override is below.
344 344
345 345 def shell(cmd,verbose=0,debug=0,header=''):
346 346 """Execute a command in the system shell, always return None.
347 347
348 348 Options:
349 349
350 350 - verbose (0): print the command to be executed.
351 351
352 352 - debug (0): only print, do not actually execute.
353 353
354 354 - header (''): Header to print on screen prior to the executed command (it
355 355 is only prepended to the command, no newlines are added).
356 356
357 357 Note: this is similar to genutils.system(), but it returns None so it can
358 358 be conveniently used in interactive loops without getting the return value
359 359 (typically 0) printed many times."""
360 360
361 361 stat = 0
362 362 if verbose or debug: print header+cmd
363 363 # flush stdout so we don't mangle python's buffering
364 364 sys.stdout.flush()
365 365
366 366 if not debug:
367 367 platutils.set_term_title("IPy " + cmd)
368 368 os.system(cmd)
369 369 platutils.set_term_title("IPy " + abbrev_cwd())
370 370
371 371 # override shell() for win32 to deal with network shares
372 372 if os.name in ('nt','dos'):
373 373
374 374 shell_ori = shell
375 375
376 376 def shell(cmd,verbose=0,debug=0,header=''):
377 377 if os.getcwd().startswith(r"\\"):
378 378 path = os.getcwd()
379 379 # change to c drive (cannot be on UNC-share when issuing os.system,
380 380 # as cmd.exe cannot handle UNC addresses)
381 381 os.chdir("c:")
382 382 # issue pushd to the UNC-share and then run the command
383 383 try:
384 384 shell_ori('"pushd %s&&"'%path+cmd,verbose,debug,header)
385 385 finally:
386 386 os.chdir(path)
387 387 else:
388 388 shell_ori(cmd,verbose,debug,header)
389 389
390 390 shell.__doc__ = shell_ori.__doc__
391 391
392 392 def getoutput(cmd,verbose=0,debug=0,header='',split=0):
393 393 """Dummy substitute for perl's backquotes.
394 394
395 395 Executes a command and returns the output.
396 396
397 397 Accepts the same arguments as system(), plus:
398 398
399 399 - split(0): if true, the output is returned as a list split on newlines.
400 400
401 401 Note: a stateful version of this function is available through the
402 402 SystemExec class.
403 403
404 404 This is pretty much deprecated and rarely used,
405 405 genutils.getoutputerror may be what you need.
406 406
407 407 """
408 408
409 409 if verbose or debug: print header+cmd
410 410 if not debug:
411 411 output = os.popen(cmd).read()
412 412 # stipping last \n is here for backwards compat.
413 413 if output.endswith('\n'):
414 414 output = output[:-1]
415 415 if split:
416 416 return output.split('\n')
417 417 else:
418 418 return output
419 419
420 420 def getoutputerror(cmd,verbose=0,debug=0,header='',split=0):
421 421 """Return (standard output,standard error) of executing cmd in a shell.
422 422
423 423 Accepts the same arguments as system(), plus:
424 424
425 425 - split(0): if true, each of stdout/err is returned as a list split on
426 426 newlines.
427 427
428 428 Note: a stateful version of this function is available through the
429 429 SystemExec class."""
430 430
431 431 if verbose or debug: print header+cmd
432 432 if not cmd:
433 433 if split:
434 434 return [],[]
435 435 else:
436 436 return '',''
437 437 if not debug:
438 438 pin,pout,perr = os.popen3(cmd)
439 439 tout = pout.read().rstrip()
440 440 terr = perr.read().rstrip()
441 441 pin.close()
442 442 pout.close()
443 443 perr.close()
444 444 if split:
445 445 return tout.split('\n'),terr.split('\n')
446 446 else:
447 447 return tout,terr
448 448
449 449 # for compatibility with older naming conventions
450 450 xsys = system
451 451 bq = getoutput
452 452
453 453 class SystemExec:
454 454 """Access the system and getoutput functions through a stateful interface.
455 455
456 456 Note: here we refer to the system and getoutput functions from this
457 457 library, not the ones from the standard python library.
458 458
459 459 This class offers the system and getoutput functions as methods, but the
460 460 verbose, debug and header parameters can be set for the instance (at
461 461 creation time or later) so that they don't need to be specified on each
462 462 call.
463 463
464 464 For efficiency reasons, there's no way to override the parameters on a
465 465 per-call basis other than by setting instance attributes. If you need
466 466 local overrides, it's best to directly call system() or getoutput().
467 467
468 468 The following names are provided as alternate options:
469 469 - xsys: alias to system
470 470 - bq: alias to getoutput
471 471
472 472 An instance can then be created as:
473 473 >>> sysexec = SystemExec(verbose=1,debug=0,header='Calling: ')
474 474 """
475 475
476 476 def __init__(self,verbose=0,debug=0,header='',split=0):
477 477 """Specify the instance's values for verbose, debug and header."""
478 478 setattr_list(self,'verbose debug header split')
479 479
480 480 def system(self,cmd):
481 481 """Stateful interface to system(), with the same keyword parameters."""
482 482
483 483 system(cmd,self.verbose,self.debug,self.header)
484 484
485 485 def shell(self,cmd):
486 486 """Stateful interface to shell(), with the same keyword parameters."""
487 487
488 488 shell(cmd,self.verbose,self.debug,self.header)
489 489
490 490 xsys = system # alias
491 491
492 492 def getoutput(self,cmd):
493 493 """Stateful interface to getoutput()."""
494 494
495 495 return getoutput(cmd,self.verbose,self.debug,self.header,self.split)
496 496
497 497 def getoutputerror(self,cmd):
498 498 """Stateful interface to getoutputerror()."""
499 499
500 500 return getoutputerror(cmd,self.verbose,self.debug,self.header,self.split)
501 501
502 502 bq = getoutput # alias
503 503
504 504 #-----------------------------------------------------------------------------
505 505 def mutex_opts(dict,ex_op):
506 506 """Check for presence of mutually exclusive keys in a dict.
507 507
508 508 Call: mutex_opts(dict,[[op1a,op1b],[op2a,op2b]...]"""
509 509 for op1,op2 in ex_op:
510 510 if op1 in dict and op2 in dict:
511 511 raise ValueError,'\n*** ERROR in Arguments *** '\
512 512 'Options '+op1+' and '+op2+' are mutually exclusive.'
513 513
514 514 #-----------------------------------------------------------------------------
515 515 def get_py_filename(name):
516 516 """Return a valid python filename in the current directory.
517 517
518 518 If the given name is not a file, it adds '.py' and searches again.
519 519 Raises IOError with an informative message if the file isn't found."""
520 520
521 521 name = os.path.expanduser(name)
522 522 if not os.path.isfile(name) and not name.endswith('.py'):
523 523 name += '.py'
524 524 if os.path.isfile(name):
525 525 return name
526 526 else:
527 527 raise IOError,'File `%s` not found.' % name
528 528
529 529 #-----------------------------------------------------------------------------
530 530 def filefind(fname,alt_dirs = None):
531 531 """Return the given filename either in the current directory, if it
532 532 exists, or in a specified list of directories.
533 533
534 534 ~ expansion is done on all file and directory names.
535 535
536 536 Upon an unsuccessful search, raise an IOError exception."""
537 537
538 538 if alt_dirs is None:
539 539 try:
540 540 alt_dirs = get_home_dir()
541 541 except HomeDirError:
542 542 alt_dirs = os.getcwd()
543 543 search = [fname] + list_strings(alt_dirs)
544 544 search = map(os.path.expanduser,search)
545 545 #print 'search list for',fname,'list:',search # dbg
546 546 fname = search[0]
547 547 if os.path.isfile(fname):
548 548 return fname
549 549 for direc in search[1:]:
550 550 testname = os.path.join(direc,fname)
551 551 #print 'testname',testname # dbg
552 552 if os.path.isfile(testname):
553 553 return testname
554 554 raise IOError,'File' + `fname` + \
555 555 ' not found in current or supplied directories:' + `alt_dirs`
556 556
557 557 #----------------------------------------------------------------------------
558 558 def file_read(filename):
559 559 """Read a file and close it. Returns the file source."""
560 560 fobj = open(filename,'r');
561 561 source = fobj.read();
562 562 fobj.close()
563 563 return source
564 564
565 565 def file_readlines(filename):
566 566 """Read a file and close it. Returns the file source using readlines()."""
567 567 fobj = open(filename,'r');
568 568 lines = fobj.readlines();
569 569 fobj.close()
570 570 return lines
571 571
572 572 #----------------------------------------------------------------------------
573 573 def target_outdated(target,deps):
574 574 """Determine whether a target is out of date.
575 575
576 576 target_outdated(target,deps) -> 1/0
577 577
578 578 deps: list of filenames which MUST exist.
579 579 target: single filename which may or may not exist.
580 580
581 581 If target doesn't exist or is older than any file listed in deps, return
582 582 true, otherwise return false.
583 583 """
584 584 try:
585 585 target_time = os.path.getmtime(target)
586 586 except os.error:
587 587 return 1
588 588 for dep in deps:
589 589 dep_time = os.path.getmtime(dep)
590 590 if dep_time > target_time:
591 591 #print "For target",target,"Dep failed:",dep # dbg
592 592 #print "times (dep,tar):",dep_time,target_time # dbg
593 593 return 1
594 594 return 0
595 595
596 596 #-----------------------------------------------------------------------------
597 597 def target_update(target,deps,cmd):
598 598 """Update a target with a given command given a list of dependencies.
599 599
600 600 target_update(target,deps,cmd) -> runs cmd if target is outdated.
601 601
602 602 This is just a wrapper around target_outdated() which calls the given
603 603 command if target is outdated."""
604 604
605 605 if target_outdated(target,deps):
606 606 xsys(cmd)
607 607
608 608 #----------------------------------------------------------------------------
609 609 def unquote_ends(istr):
610 610 """Remove a single pair of quotes from the endpoints of a string."""
611 611
612 612 if not istr:
613 613 return istr
614 614 if (istr[0]=="'" and istr[-1]=="'") or \
615 615 (istr[0]=='"' and istr[-1]=='"'):
616 616 return istr[1:-1]
617 617 else:
618 618 return istr
619 619
620 620 #----------------------------------------------------------------------------
621 621 def process_cmdline(argv,names=[],defaults={},usage=''):
622 622 """ Process command-line options and arguments.
623 623
624 624 Arguments:
625 625
626 626 - argv: list of arguments, typically sys.argv.
627 627
628 628 - names: list of option names. See DPyGetOpt docs for details on options
629 629 syntax.
630 630
631 631 - defaults: dict of default values.
632 632
633 633 - usage: optional usage notice to print if a wrong argument is passed.
634 634
635 635 Return a dict of options and a list of free arguments."""
636 636
637 637 getopt = DPyGetOpt.DPyGetOpt()
638 638 getopt.setIgnoreCase(0)
639 639 getopt.parseConfiguration(names)
640 640
641 641 try:
642 642 getopt.processArguments(argv)
643 643 except DPyGetOpt.ArgumentError, exc:
644 644 print usage
645 645 warn('"%s"' % exc,level=4)
646 646
647 647 defaults.update(getopt.optionValues)
648 648 args = getopt.freeValues
649 649
650 650 return defaults,args
651 651
652 652 #----------------------------------------------------------------------------
653 653 def optstr2types(ostr):
654 654 """Convert a string of option names to a dict of type mappings.
655 655
656 656 optstr2types(str) -> {None:'string_opts',int:'int_opts',float:'float_opts'}
657 657
658 658 This is used to get the types of all the options in a string formatted
659 659 with the conventions of DPyGetOpt. The 'type' None is used for options
660 660 which are strings (they need no further conversion). This function's main
661 661 use is to get a typemap for use with read_dict().
662 662 """
663 663
664 664 typeconv = {None:'',int:'',float:''}
665 665 typemap = {'s':None,'i':int,'f':float}
666 666 opt_re = re.compile(r'([\w]*)([^:=]*:?=?)([sif]?)')
667 667
668 668 for w in ostr.split():
669 669 oname,alias,otype = opt_re.match(w).groups()
670 670 if otype == '' or alias == '!': # simple switches are integers too
671 671 otype = 'i'
672 672 typeconv[typemap[otype]] += oname + ' '
673 673 return typeconv
674 674
675 675 #----------------------------------------------------------------------------
676 676 def read_dict(filename,type_conv=None,**opt):
677 677 r"""Read a dictionary of key=value pairs from an input file, optionally
678 678 performing conversions on the resulting values.
679 679
680 680 read_dict(filename,type_conv,**opt) -> dict
681 681
682 682 Only one value per line is accepted, the format should be
683 683 # optional comments are ignored
684 684 key value\n
685 685
686 686 Args:
687 687
688 688 - type_conv: A dictionary specifying which keys need to be converted to
689 689 which types. By default all keys are read as strings. This dictionary
690 690 should have as its keys valid conversion functions for strings
691 691 (int,long,float,complex, or your own). The value for each key
692 692 (converter) should be a whitespace separated string containing the names
693 693 of all the entries in the file to be converted using that function. For
694 694 keys to be left alone, use None as the conversion function (only needed
695 695 with purge=1, see below).
696 696
697 697 - opt: dictionary with extra options as below (default in parens)
698 698
699 699 purge(0): if set to 1, all keys *not* listed in type_conv are purged out
700 700 of the dictionary to be returned. If purge is going to be used, the
701 701 set of keys to be left as strings also has to be explicitly specified
702 702 using the (non-existent) conversion function None.
703 703
704 704 fs(None): field separator. This is the key/value separator to be used
705 705 when parsing the file. The None default means any whitespace [behavior
706 706 of string.split()].
707 707
708 708 strip(0): if 1, strip string values of leading/trailinig whitespace.
709 709
710 710 warn(1): warning level if requested keys are not found in file.
711 711 - 0: silently ignore.
712 712 - 1: inform but proceed.
713 713 - 2: raise KeyError exception.
714 714
715 715 no_empty(0): if 1, remove keys with whitespace strings as a value.
716 716
717 717 unique([]): list of keys (or space separated string) which can't be
718 718 repeated. If one such key is found in the file, each new instance
719 719 overwrites the previous one. For keys not listed here, the behavior is
720 720 to make a list of all appearances.
721 721
722 722 Example:
723 723
724 724 If the input file test.ini contains (we put it in a string to keep the test
725 725 self-contained):
726 726
727 727 >>> test_ini = '''\
728 728 ... i 3
729 729 ... x 4.5
730 730 ... y 5.5
731 731 ... s hi ho'''
732 732
733 733 Then we can use it as follows:
734 734 >>> type_conv={int:'i',float:'x',None:'s'}
735 735
736 736 >>> d = read_dict(test_ini)
737 737
738 738 >>> sorted(d.items())
739 739 [('i', '3'), ('s', 'hi ho'), ('x', '4.5'), ('y', '5.5')]
740 740
741 741 >>> d = read_dict(test_ini,type_conv)
742 742
743 743 >>> sorted(d.items())
744 744 [('i', 3), ('s', 'hi ho'), ('x', 4.5), ('y', '5.5')]
745 745
746 746 >>> d = read_dict(test_ini,type_conv,purge=True)
747 747
748 748 >>> sorted(d.items())
749 749 [('i', 3), ('s', 'hi ho'), ('x', 4.5)]
750 750 """
751 751
752 752 # starting config
753 753 opt.setdefault('purge',0)
754 754 opt.setdefault('fs',None) # field sep defaults to any whitespace
755 755 opt.setdefault('strip',0)
756 756 opt.setdefault('warn',1)
757 757 opt.setdefault('no_empty',0)
758 758 opt.setdefault('unique','')
759 759 if type(opt['unique']) in StringTypes:
760 760 unique_keys = qw(opt['unique'])
761 761 elif type(opt['unique']) in (types.TupleType,types.ListType):
762 762 unique_keys = opt['unique']
763 763 else:
764 764 raise ValueError, 'Unique keys must be given as a string, List or Tuple'
765 765
766 766 dict = {}
767 767
768 768 # first read in table of values as strings
769 769 if '\n' in filename:
770 770 lines = filename.splitlines()
771 771 file = None
772 772 else:
773 773 file = open(filename,'r')
774 774 lines = file.readlines()
775 775 for line in lines:
776 776 line = line.strip()
777 777 if len(line) and line[0]=='#': continue
778 778 if len(line)>0:
779 779 lsplit = line.split(opt['fs'],1)
780 780 try:
781 781 key,val = lsplit
782 782 except ValueError:
783 783 key,val = lsplit[0],''
784 784 key = key.strip()
785 785 if opt['strip']: val = val.strip()
786 786 if val == "''" or val == '""': val = ''
787 787 if opt['no_empty'] and (val=='' or val.isspace()):
788 788 continue
789 789 # if a key is found more than once in the file, build a list
790 790 # unless it's in the 'unique' list. In that case, last found in file
791 791 # takes precedence. User beware.
792 792 try:
793 793 if dict[key] and key in unique_keys:
794 794 dict[key] = val
795 795 elif type(dict[key]) is types.ListType:
796 796 dict[key].append(val)
797 797 else:
798 798 dict[key] = [dict[key],val]
799 799 except KeyError:
800 800 dict[key] = val
801 801 # purge if requested
802 802 if opt['purge']:
803 803 accepted_keys = qwflat(type_conv.values())
804 804 for key in dict.keys():
805 805 if key in accepted_keys: continue
806 806 del(dict[key])
807 807 # now convert if requested
808 808 if type_conv==None: return dict
809 809 conversions = type_conv.keys()
810 810 try: conversions.remove(None)
811 811 except: pass
812 812 for convert in conversions:
813 813 for val in qw(type_conv[convert]):
814 814 try:
815 815 dict[val] = convert(dict[val])
816 816 except KeyError,e:
817 817 if opt['warn'] == 0:
818 818 pass
819 819 elif opt['warn'] == 1:
820 820 print >>sys.stderr, 'Warning: key',val,\
821 821 'not found in file',filename
822 822 elif opt['warn'] == 2:
823 823 raise KeyError,e
824 824 else:
825 825 raise ValueError,'Warning level must be 0,1 or 2'
826 826
827 827 return dict
828 828
829 829 #----------------------------------------------------------------------------
830 830 def flag_calls(func):
831 831 """Wrap a function to detect and flag when it gets called.
832 832
833 833 This is a decorator which takes a function and wraps it in a function with
834 834 a 'called' attribute. wrapper.called is initialized to False.
835 835
836 836 The wrapper.called attribute is set to False right before each call to the
837 837 wrapped function, so if the call fails it remains False. After the call
838 838 completes, wrapper.called is set to True and the output is returned.
839 839
840 840 Testing for truth in wrapper.called allows you to determine if a call to
841 841 func() was attempted and succeeded."""
842 842
843 843 def wrapper(*args,**kw):
844 844 wrapper.called = False
845 845 out = func(*args,**kw)
846 846 wrapper.called = True
847 847 return out
848 848
849 849 wrapper.called = False
850 850 wrapper.__doc__ = func.__doc__
851 851 return wrapper
852 852
853 853 #----------------------------------------------------------------------------
854 854 def dhook_wrap(func,*a,**k):
855 855 """Wrap a function call in a sys.displayhook controller.
856 856
857 857 Returns a wrapper around func which calls func, with all its arguments and
858 858 keywords unmodified, using the default sys.displayhook. Since IPython
859 859 modifies sys.displayhook, it breaks the behavior of certain systems that
860 860 rely on the default behavior, notably doctest.
861 861 """
862 862
863 863 def f(*a,**k):
864 864
865 865 dhook_s = sys.displayhook
866 866 sys.displayhook = sys.__displayhook__
867 867 try:
868 868 out = func(*a,**k)
869 869 finally:
870 870 sys.displayhook = dhook_s
871 871
872 872 return out
873 873
874 874 f.__doc__ = func.__doc__
875 875 return f
876 876
877 877 #----------------------------------------------------------------------------
878 878 def doctest_reload():
879 879 """Properly reload doctest to reuse it interactively.
880 880
881 881 This routine:
882 882
883 883 - reloads doctest
884 884
885 885 - resets its global 'master' attribute to None, so that multiple uses of
886 886 the module interactively don't produce cumulative reports.
887 887
888 888 - Monkeypatches its core test runner method to protect it from IPython's
889 889 modified displayhook. Doctest expects the default displayhook behavior
890 890 deep down, so our modification breaks it completely. For this reason, a
891 891 hard monkeypatch seems like a reasonable solution rather than asking
892 892 users to manually use a different doctest runner when under IPython."""
893 893
894 894 import doctest
895 895 reload(doctest)
896 896 doctest.master=None
897 897
898 898 try:
899 899 doctest.DocTestRunner
900 900 except AttributeError:
901 901 # This is only for python 2.3 compatibility, remove once we move to
902 902 # 2.4 only.
903 903 pass
904 904 else:
905 905 doctest.DocTestRunner.run = dhook_wrap(doctest.DocTestRunner.run)
906 906
907 907 #----------------------------------------------------------------------------
908 908 class HomeDirError(Error):
909 909 pass
910 910
911 911 def get_home_dir():
912 912 """Return the closest possible equivalent to a 'home' directory.
913 913
914 914 We first try $HOME. Absent that, on NT it's $HOMEDRIVE\$HOMEPATH.
915 915
916 916 Currently only Posix and NT are implemented, a HomeDirError exception is
917 917 raised for all other OSes. """
918 918
919 919 isdir = os.path.isdir
920 920 env = os.environ
921 921
922 922 # first, check py2exe distribution root directory for _ipython.
923 923 # This overrides all. Normally does not exist.
924 924
925 if '\\library.zip\\' in IPython.__file__.lower():
926 root, rest = IPython.__file__.lower().split('library.zip')
927 if isdir(root + '_ipython'):
928 os.environ["IPYKITROOT"] = root.rstrip('\\')
929 return root
930
925 if hasattr(sys, "frozen"): #Is frozen by py2exe
926 if '\\library.zip\\' in IPython.__file__.lower():#libraries compressed to zip-file
927 root, rest = IPython.__file__.lower().split('library.zip')
928 else:
929 root=os.path.join(os.path.split(IPython.__file__)[0],"../../")
930 root=os.path.abspath(root).rstrip('\\')
931 if isdir(os.path.join(root, '_ipython')):
932 os.environ["IPYKITROOT"] = root
933 return root
931 934 try:
932 935 homedir = env['HOME']
933 936 if not isdir(homedir):
934 937 # in case a user stuck some string which does NOT resolve to a
935 938 # valid path, it's as good as if we hadn't foud it
936 939 raise KeyError
937 940 return homedir
938 941 except KeyError:
939 942 if os.name == 'posix':
940 943 raise HomeDirError,'undefined $HOME, IPython can not proceed.'
941 944 elif os.name == 'nt':
942 945 # For some strange reason, win9x returns 'nt' for os.name.
943 946 try:
944 947 homedir = os.path.join(env['HOMEDRIVE'],env['HOMEPATH'])
945 948 if not isdir(homedir):
946 949 homedir = os.path.join(env['USERPROFILE'])
947 950 if not isdir(homedir):
948 951 raise HomeDirError
949 952 return homedir
950 except:
953 except KeyError:
951 954 try:
952 955 # Use the registry to get the 'My Documents' folder.
953 956 import _winreg as wreg
954 957 key = wreg.OpenKey(wreg.HKEY_CURRENT_USER,
955 958 "Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders")
956 959 homedir = wreg.QueryValueEx(key,'Personal')[0]
957 960 key.Close()
958 961 if not isdir(homedir):
959 962 e = ('Invalid "Personal" folder registry key '
960 963 'typically "My Documents".\n'
961 964 'Value: %s\n'
962 965 'This is not a valid directory on your system.' %
963 966 homedir)
964 967 raise HomeDirError(e)
965 968 return homedir
966 969 except HomeDirError:
967 970 raise
968 971 except:
969 972 return 'C:\\'
970 973 elif os.name == 'dos':
971 974 # Desperate, may do absurd things in classic MacOS. May work under DOS.
972 975 return 'C:\\'
973 976 else:
974 977 raise HomeDirError,'support for your operating system not implemented.'
975 978
976 979
977 980 def get_ipython_dir():
978 981 """Get the IPython directory for this platform and user.
979 982
980 983 This uses the logic in `get_home_dir` to find the home directory
981 984 and the adds either .ipython or _ipython to the end of the path.
982 985 """
983 986 if os.name == 'posix':
984 987 ipdir_def = '.ipython'
985 988 else:
986 989 ipdir_def = '_ipython'
987 990 home_dir = get_home_dir()
988 991 ipdir = os.path.abspath(os.environ.get('IPYTHONDIR',
989 os.path.join(home_dir,ipdir_def)))
990 return ipdir
992 os.path.join(home_dir, ipdir_def)))
993 return ipdir.decode(sys.getfilesystemencoding())
991 994
992 995 def get_security_dir():
993 996 """Get the IPython security directory.
994 997
995 998 This directory is the default location for all security related files,
996 999 including SSL/TLS certificates and FURL files.
997 1000
998 1001 If the directory does not exist, it is created with 0700 permissions.
999 1002 If it exists, permissions are set to 0700.
1000 1003 """
1001 1004 security_dir = os.path.join(get_ipython_dir(), 'security')
1002 1005 if not os.path.isdir(security_dir):
1003 1006 os.mkdir(security_dir, 0700)
1004 1007 else:
1005 1008 os.chmod(security_dir, 0700)
1006 1009 return security_dir
1007 1010
1008 1011 #****************************************************************************
1009 1012 # strings and text
1010 1013
1011 1014 class LSString(str):
1012 1015 """String derivative with a special access attributes.
1013 1016
1014 1017 These are normal strings, but with the special attributes:
1015 1018
1016 1019 .l (or .list) : value as list (split on newlines).
1017 1020 .n (or .nlstr): original value (the string itself).
1018 1021 .s (or .spstr): value as whitespace-separated string.
1019 1022 .p (or .paths): list of path objects
1020 1023
1021 1024 Any values which require transformations are computed only once and
1022 1025 cached.
1023 1026
1024 1027 Such strings are very useful to efficiently interact with the shell, which
1025 1028 typically only understands whitespace-separated options for commands."""
1026 1029
1027 1030 def get_list(self):
1028 1031 try:
1029 1032 return self.__list
1030 1033 except AttributeError:
1031 1034 self.__list = self.split('\n')
1032 1035 return self.__list
1033 1036
1034 1037 l = list = property(get_list)
1035 1038
1036 1039 def get_spstr(self):
1037 1040 try:
1038 1041 return self.__spstr
1039 1042 except AttributeError:
1040 1043 self.__spstr = self.replace('\n',' ')
1041 1044 return self.__spstr
1042 1045
1043 1046 s = spstr = property(get_spstr)
1044 1047
1045 1048 def get_nlstr(self):
1046 1049 return self
1047 1050
1048 1051 n = nlstr = property(get_nlstr)
1049 1052
1050 1053 def get_paths(self):
1051 1054 try:
1052 1055 return self.__paths
1053 1056 except AttributeError:
1054 1057 self.__paths = [path(p) for p in self.split('\n') if os.path.exists(p)]
1055 1058 return self.__paths
1056 1059
1057 1060 p = paths = property(get_paths)
1058 1061
1059 1062 def print_lsstring(arg):
1060 1063 """ Prettier (non-repr-like) and more informative printer for LSString """
1061 1064 print "LSString (.p, .n, .l, .s available). Value:"
1062 1065 print arg
1063 1066
1064 1067 print_lsstring = result_display.when_type(LSString)(print_lsstring)
1065 1068
1066 1069 #----------------------------------------------------------------------------
1067 1070 class SList(list):
1068 1071 """List derivative with a special access attributes.
1069 1072
1070 1073 These are normal lists, but with the special attributes:
1071 1074
1072 1075 .l (or .list) : value as list (the list itself).
1073 1076 .n (or .nlstr): value as a string, joined on newlines.
1074 1077 .s (or .spstr): value as a string, joined on spaces.
1075 1078 .p (or .paths): list of path objects
1076 1079
1077 1080 Any values which require transformations are computed only once and
1078 1081 cached."""
1079 1082
1080 1083 def get_list(self):
1081 1084 return self
1082 1085
1083 1086 l = list = property(get_list)
1084 1087
1085 1088 def get_spstr(self):
1086 1089 try:
1087 1090 return self.__spstr
1088 1091 except AttributeError:
1089 1092 self.__spstr = ' '.join(self)
1090 1093 return self.__spstr
1091 1094
1092 1095 s = spstr = property(get_spstr)
1093 1096
1094 1097 def get_nlstr(self):
1095 1098 try:
1096 1099 return self.__nlstr
1097 1100 except AttributeError:
1098 1101 self.__nlstr = '\n'.join(self)
1099 1102 return self.__nlstr
1100 1103
1101 1104 n = nlstr = property(get_nlstr)
1102 1105
1103 1106 def get_paths(self):
1104 1107 try:
1105 1108 return self.__paths
1106 1109 except AttributeError:
1107 1110 self.__paths = [path(p) for p in self if os.path.exists(p)]
1108 1111 return self.__paths
1109 1112
1110 1113 p = paths = property(get_paths)
1111 1114
1112 1115 def grep(self, pattern, prune = False, field = None):
1113 1116 """ Return all strings matching 'pattern' (a regex or callable)
1114 1117
1115 1118 This is case-insensitive. If prune is true, return all items
1116 1119 NOT matching the pattern.
1117 1120
1118 1121 If field is specified, the match must occur in the specified
1119 1122 whitespace-separated field.
1120 1123
1121 1124 Examples::
1122 1125
1123 1126 a.grep( lambda x: x.startswith('C') )
1124 1127 a.grep('Cha.*log', prune=1)
1125 1128 a.grep('chm', field=-1)
1126 1129 """
1127 1130
1128 1131 def match_target(s):
1129 1132 if field is None:
1130 1133 return s
1131 1134 parts = s.split()
1132 1135 try:
1133 1136 tgt = parts[field]
1134 1137 return tgt
1135 1138 except IndexError:
1136 1139 return ""
1137 1140
1138 1141 if isinstance(pattern, basestring):
1139 1142 pred = lambda x : re.search(pattern, x, re.IGNORECASE)
1140 1143 else:
1141 1144 pred = pattern
1142 1145 if not prune:
1143 1146 return SList([el for el in self if pred(match_target(el))])
1144 1147 else:
1145 1148 return SList([el for el in self if not pred(match_target(el))])
1146 1149 def fields(self, *fields):
1147 1150 """ Collect whitespace-separated fields from string list
1148 1151
1149 1152 Allows quick awk-like usage of string lists.
1150 1153
1151 1154 Example data (in var a, created by 'a = !ls -l')::
1152 1155 -rwxrwxrwx 1 ville None 18 Dec 14 2006 ChangeLog
1153 1156 drwxrwxrwx+ 6 ville None 0 Oct 24 18:05 IPython
1154 1157
1155 1158 a.fields(0) is ['-rwxrwxrwx', 'drwxrwxrwx+']
1156 1159 a.fields(1,0) is ['1 -rwxrwxrwx', '6 drwxrwxrwx+']
1157 1160 (note the joining by space).
1158 1161 a.fields(-1) is ['ChangeLog', 'IPython']
1159 1162
1160 1163 IndexErrors are ignored.
1161 1164
1162 1165 Without args, fields() just split()'s the strings.
1163 1166 """
1164 1167 if len(fields) == 0:
1165 1168 return [el.split() for el in self]
1166 1169
1167 1170 res = SList()
1168 1171 for el in [f.split() for f in self]:
1169 1172 lineparts = []
1170 1173
1171 1174 for fd in fields:
1172 1175 try:
1173 1176 lineparts.append(el[fd])
1174 1177 except IndexError:
1175 1178 pass
1176 1179 if lineparts:
1177 1180 res.append(" ".join(lineparts))
1178 1181
1179 1182 return res
1180 1183 def sort(self,field= None, nums = False):
1181 1184 """ sort by specified fields (see fields())
1182 1185
1183 1186 Example::
1184 1187 a.sort(1, nums = True)
1185 1188
1186 1189 Sorts a by second field, in numerical order (so that 21 > 3)
1187 1190
1188 1191 """
1189 1192
1190 1193 #decorate, sort, undecorate
1191 1194 if field is not None:
1192 1195 dsu = [[SList([line]).fields(field), line] for line in self]
1193 1196 else:
1194 1197 dsu = [[line, line] for line in self]
1195 1198 if nums:
1196 1199 for i in range(len(dsu)):
1197 1200 numstr = "".join([ch for ch in dsu[i][0] if ch.isdigit()])
1198 1201 try:
1199 1202 n = int(numstr)
1200 1203 except ValueError:
1201 1204 n = 0;
1202 1205 dsu[i][0] = n
1203 1206
1204 1207
1205 1208 dsu.sort()
1206 1209 return SList([t[1] for t in dsu])
1207 1210
1208 1211 def print_slist(arg):
1209 1212 """ Prettier (non-repr-like) and more informative printer for SList """
1210 1213 print "SList (.p, .n, .l, .s, .grep(), .fields(), sort() available):"
1211 1214 if hasattr(arg, 'hideonce') and arg.hideonce:
1212 1215 arg.hideonce = False
1213 1216 return
1214 1217
1215 1218 nlprint(arg)
1216 1219
1217 1220 print_slist = result_display.when_type(SList)(print_slist)
1218 1221
1219 1222
1220 1223
1221 1224 #----------------------------------------------------------------------------
1222 1225 def esc_quotes(strng):
1223 1226 """Return the input string with single and double quotes escaped out"""
1224 1227
1225 1228 return strng.replace('"','\\"').replace("'","\\'")
1226 1229
1227 1230 #----------------------------------------------------------------------------
1228 1231 def make_quoted_expr(s):
1229 1232 """Return string s in appropriate quotes, using raw string if possible.
1230 1233
1231 1234 XXX - example removed because it caused encoding errors in documentation
1232 1235 generation. We need a new example that doesn't contain invalid chars.
1233 1236
1234 1237 Note the use of raw string and padding at the end to allow trailing
1235 1238 backslash.
1236 1239 """
1237 1240
1238 1241 tail = ''
1239 1242 tailpadding = ''
1240 1243 raw = ''
1241 1244 if "\\" in s:
1242 1245 raw = 'r'
1243 1246 if s.endswith('\\'):
1244 1247 tail = '[:-1]'
1245 1248 tailpadding = '_'
1246 1249 if '"' not in s:
1247 1250 quote = '"'
1248 1251 elif "'" not in s:
1249 1252 quote = "'"
1250 1253 elif '"""' not in s and not s.endswith('"'):
1251 1254 quote = '"""'
1252 1255 elif "'''" not in s and not s.endswith("'"):
1253 1256 quote = "'''"
1254 1257 else:
1255 1258 # give up, backslash-escaped string will do
1256 1259 return '"%s"' % esc_quotes(s)
1257 1260 res = raw + quote + s + tailpadding + quote + tail
1258 1261 return res
1259 1262
1260 1263
1261 1264 #----------------------------------------------------------------------------
1262 1265 def raw_input_multi(header='', ps1='==> ', ps2='..> ',terminate_str = '.'):
1263 1266 """Take multiple lines of input.
1264 1267
1265 1268 A list with each line of input as a separate element is returned when a
1266 1269 termination string is entered (defaults to a single '.'). Input can also
1267 1270 terminate via EOF (^D in Unix, ^Z-RET in Windows).
1268 1271
1269 1272 Lines of input which end in \\ are joined into single entries (and a
1270 1273 secondary continuation prompt is issued as long as the user terminates
1271 1274 lines with \\). This allows entering very long strings which are still
1272 1275 meant to be treated as single entities.
1273 1276 """
1274 1277
1275 1278 try:
1276 1279 if header:
1277 1280 header += '\n'
1278 1281 lines = [raw_input(header + ps1)]
1279 1282 except EOFError:
1280 1283 return []
1281 1284 terminate = [terminate_str]
1282 1285 try:
1283 1286 while lines[-1:] != terminate:
1284 1287 new_line = raw_input(ps1)
1285 1288 while new_line.endswith('\\'):
1286 1289 new_line = new_line[:-1] + raw_input(ps2)
1287 1290 lines.append(new_line)
1288 1291
1289 1292 return lines[:-1] # don't return the termination command
1290 1293 except EOFError:
1291 1294 print
1292 1295 return lines
1293 1296
1294 1297 #----------------------------------------------------------------------------
1295 1298 def raw_input_ext(prompt='', ps2='... '):
1296 1299 """Similar to raw_input(), but accepts extended lines if input ends with \\."""
1297 1300
1298 1301 line = raw_input(prompt)
1299 1302 while line.endswith('\\'):
1300 1303 line = line[:-1] + raw_input(ps2)
1301 1304 return line
1302 1305
1303 1306 #----------------------------------------------------------------------------
1304 1307 def ask_yes_no(prompt,default=None):
1305 1308 """Asks a question and returns a boolean (y/n) answer.
1306 1309
1307 1310 If default is given (one of 'y','n'), it is used if the user input is
1308 1311 empty. Otherwise the question is repeated until an answer is given.
1309 1312
1310 1313 An EOF is treated as the default answer. If there is no default, an
1311 1314 exception is raised to prevent infinite loops.
1312 1315
1313 1316 Valid answers are: y/yes/n/no (match is not case sensitive)."""
1314 1317
1315 1318 answers = {'y':True,'n':False,'yes':True,'no':False}
1316 1319 ans = None
1317 1320 while ans not in answers.keys():
1318 1321 try:
1319 1322 ans = raw_input(prompt+' ').lower()
1320 1323 if not ans: # response was an empty string
1321 1324 ans = default
1322 1325 except KeyboardInterrupt:
1323 1326 pass
1324 1327 except EOFError:
1325 1328 if default in answers.keys():
1326 1329 ans = default
1327 1330 print
1328 1331 else:
1329 1332 raise
1330 1333
1331 1334 return answers[ans]
1332 1335
1333 1336 #----------------------------------------------------------------------------
1334 1337 def marquee(txt='',width=78,mark='*'):
1335 1338 """Return the input string centered in a 'marquee'."""
1336 1339 if not txt:
1337 1340 return (mark*width)[:width]
1338 1341 nmark = (width-len(txt)-2)/len(mark)/2
1339 1342 if nmark < 0: nmark =0
1340 1343 marks = mark*nmark
1341 1344 return '%s %s %s' % (marks,txt,marks)
1342 1345
1343 1346 #----------------------------------------------------------------------------
1344 1347 class EvalDict:
1345 1348 """
1346 1349 Emulate a dict which evaluates its contents in the caller's frame.
1347 1350
1348 1351 Usage:
1349 1352 >>> number = 19
1350 1353
1351 1354 >>> text = "python"
1352 1355
1353 1356 >>> print "%(text.capitalize())s %(number/9.0).1f rules!" % EvalDict()
1354 1357 Python 2.1 rules!
1355 1358 """
1356 1359
1357 1360 # This version is due to sismex01@hebmex.com on c.l.py, and is basically a
1358 1361 # modified (shorter) version of:
1359 1362 # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66018 by
1360 1363 # Skip Montanaro (skip@pobox.com).
1361 1364
1362 1365 def __getitem__(self, name):
1363 1366 frame = sys._getframe(1)
1364 1367 return eval(name, frame.f_globals, frame.f_locals)
1365 1368
1366 1369 EvalString = EvalDict # for backwards compatibility
1367 1370 #----------------------------------------------------------------------------
1368 1371 def qw(words,flat=0,sep=None,maxsplit=-1):
1369 1372 """Similar to Perl's qw() operator, but with some more options.
1370 1373
1371 1374 qw(words,flat=0,sep=' ',maxsplit=-1) -> words.split(sep,maxsplit)
1372 1375
1373 1376 words can also be a list itself, and with flat=1, the output will be
1374 1377 recursively flattened.
1375 1378
1376 1379 Examples:
1377 1380
1378 1381 >>> qw('1 2')
1379 1382 ['1', '2']
1380 1383
1381 1384 >>> qw(['a b','1 2',['m n','p q']])
1382 1385 [['a', 'b'], ['1', '2'], [['m', 'n'], ['p', 'q']]]
1383 1386
1384 1387 >>> qw(['a b','1 2',['m n','p q']],flat=1)
1385 1388 ['a', 'b', '1', '2', 'm', 'n', 'p', 'q']
1386 1389 """
1387 1390
1388 1391 if type(words) in StringTypes:
1389 1392 return [word.strip() for word in words.split(sep,maxsplit)
1390 1393 if word and not word.isspace() ]
1391 1394 if flat:
1392 1395 return flatten(map(qw,words,[1]*len(words)))
1393 1396 return map(qw,words)
1394 1397
1395 1398 #----------------------------------------------------------------------------
1396 1399 def qwflat(words,sep=None,maxsplit=-1):
1397 1400 """Calls qw(words) in flat mode. It's just a convenient shorthand."""
1398 1401 return qw(words,1,sep,maxsplit)
1399 1402
1400 1403 #----------------------------------------------------------------------------
1401 1404 def qw_lol(indata):
1402 1405 """qw_lol('a b') -> [['a','b']],
1403 1406 otherwise it's just a call to qw().
1404 1407
1405 1408 We need this to make sure the modules_some keys *always* end up as a
1406 1409 list of lists."""
1407 1410
1408 1411 if type(indata) in StringTypes:
1409 1412 return [qw(indata)]
1410 1413 else:
1411 1414 return qw(indata)
1412 1415
1413 1416 #-----------------------------------------------------------------------------
1414 1417 def list_strings(arg):
1415 1418 """Always return a list of strings, given a string or list of strings
1416 1419 as input."""
1417 1420
1418 1421 if type(arg) in StringTypes: return [arg]
1419 1422 else: return arg
1420 1423
1421 1424 #----------------------------------------------------------------------------
1422 1425 def grep(pat,list,case=1):
1423 1426 """Simple minded grep-like function.
1424 1427 grep(pat,list) returns occurrences of pat in list, None on failure.
1425 1428
1426 1429 It only does simple string matching, with no support for regexps. Use the
1427 1430 option case=0 for case-insensitive matching."""
1428 1431
1429 1432 # This is pretty crude. At least it should implement copying only references
1430 1433 # to the original data in case it's big. Now it copies the data for output.
1431 1434 out=[]
1432 1435 if case:
1433 1436 for term in list:
1434 1437 if term.find(pat)>-1: out.append(term)
1435 1438 else:
1436 1439 lpat=pat.lower()
1437 1440 for term in list:
1438 1441 if term.lower().find(lpat)>-1: out.append(term)
1439 1442
1440 1443 if len(out): return out
1441 1444 else: return None
1442 1445
1443 1446 #----------------------------------------------------------------------------
1444 1447 def dgrep(pat,*opts):
1445 1448 """Return grep() on dir()+dir(__builtins__).
1446 1449
1447 1450 A very common use of grep() when working interactively."""
1448 1451
1449 1452 return grep(pat,dir(__main__)+dir(__main__.__builtins__),*opts)
1450 1453
1451 1454 #----------------------------------------------------------------------------
1452 1455 def idgrep(pat):
1453 1456 """Case-insensitive dgrep()"""
1454 1457
1455 1458 return dgrep(pat,0)
1456 1459
1457 1460 #----------------------------------------------------------------------------
1458 1461 def igrep(pat,list):
1459 1462 """Synonym for case-insensitive grep."""
1460 1463
1461 1464 return grep(pat,list,case=0)
1462 1465
1463 1466 #----------------------------------------------------------------------------
1464 1467 def indent(str,nspaces=4,ntabs=0):
1465 1468 """Indent a string a given number of spaces or tabstops.
1466 1469
1467 1470 indent(str,nspaces=4,ntabs=0) -> indent str by ntabs+nspaces.
1468 1471 """
1469 1472 if str is None:
1470 1473 return
1471 1474 ind = '\t'*ntabs+' '*nspaces
1472 1475 outstr = '%s%s' % (ind,str.replace(os.linesep,os.linesep+ind))
1473 1476 if outstr.endswith(os.linesep+ind):
1474 1477 return outstr[:-len(ind)]
1475 1478 else:
1476 1479 return outstr
1477 1480
1478 1481 #-----------------------------------------------------------------------------
1479 1482 def native_line_ends(filename,backup=1):
1480 1483 """Convert (in-place) a file to line-ends native to the current OS.
1481 1484
1482 1485 If the optional backup argument is given as false, no backup of the
1483 1486 original file is left. """
1484 1487
1485 1488 backup_suffixes = {'posix':'~','dos':'.bak','nt':'.bak','mac':'.bak'}
1486 1489
1487 1490 bak_filename = filename + backup_suffixes[os.name]
1488 1491
1489 1492 original = open(filename).read()
1490 1493 shutil.copy2(filename,bak_filename)
1491 1494 try:
1492 1495 new = open(filename,'wb')
1493 1496 new.write(os.linesep.join(original.splitlines()))
1494 1497 new.write(os.linesep) # ALWAYS put an eol at the end of the file
1495 1498 new.close()
1496 1499 except:
1497 1500 os.rename(bak_filename,filename)
1498 1501 if not backup:
1499 1502 try:
1500 1503 os.remove(bak_filename)
1501 1504 except:
1502 1505 pass
1503 1506
1504 1507 #----------------------------------------------------------------------------
1505 1508 def get_pager_cmd(pager_cmd = None):
1506 1509 """Return a pager command.
1507 1510
1508 1511 Makes some attempts at finding an OS-correct one."""
1509 1512
1510 1513 if os.name == 'posix':
1511 1514 default_pager_cmd = 'less -r' # -r for color control sequences
1512 1515 elif os.name in ['nt','dos']:
1513 1516 default_pager_cmd = 'type'
1514 1517
1515 1518 if pager_cmd is None:
1516 1519 try:
1517 1520 pager_cmd = os.environ['PAGER']
1518 1521 except:
1519 1522 pager_cmd = default_pager_cmd
1520 1523 return pager_cmd
1521 1524
1522 1525 #-----------------------------------------------------------------------------
1523 1526 def get_pager_start(pager,start):
1524 1527 """Return the string for paging files with an offset.
1525 1528
1526 1529 This is the '+N' argument which less and more (under Unix) accept.
1527 1530 """
1528 1531
1529 1532 if pager in ['less','more']:
1530 1533 if start:
1531 1534 start_string = '+' + str(start)
1532 1535 else:
1533 1536 start_string = ''
1534 1537 else:
1535 1538 start_string = ''
1536 1539 return start_string
1537 1540
1538 1541 #----------------------------------------------------------------------------
1539 1542 # (X)emacs on W32 doesn't like to be bypassed with msvcrt.getch()
1540 1543 if os.name == 'nt' and os.environ.get('TERM','dumb') != 'emacs':
1541 1544 import msvcrt
1542 1545 def page_more():
1543 1546 """ Smart pausing between pages
1544 1547
1545 1548 @return: True if need print more lines, False if quit
1546 1549 """
1547 1550 Term.cout.write('---Return to continue, q to quit--- ')
1548 1551 ans = msvcrt.getch()
1549 1552 if ans in ("q", "Q"):
1550 1553 result = False
1551 1554 else:
1552 1555 result = True
1553 1556 Term.cout.write("\b"*37 + " "*37 + "\b"*37)
1554 1557 return result
1555 1558 else:
1556 1559 def page_more():
1557 1560 ans = raw_input('---Return to continue, q to quit--- ')
1558 1561 if ans.lower().startswith('q'):
1559 1562 return False
1560 1563 else:
1561 1564 return True
1562 1565
1563 1566 esc_re = re.compile(r"(\x1b[^m]+m)")
1564 1567
1565 1568 def page_dumb(strng,start=0,screen_lines=25):
1566 1569 """Very dumb 'pager' in Python, for when nothing else works.
1567 1570
1568 1571 Only moves forward, same interface as page(), except for pager_cmd and
1569 1572 mode."""
1570 1573
1571 1574 out_ln = strng.splitlines()[start:]
1572 1575 screens = chop(out_ln,screen_lines-1)
1573 1576 if len(screens) == 1:
1574 1577 print >>Term.cout, os.linesep.join(screens[0])
1575 1578 else:
1576 1579 last_escape = ""
1577 1580 for scr in screens[0:-1]:
1578 1581 hunk = os.linesep.join(scr)
1579 1582 print >>Term.cout, last_escape + hunk
1580 1583 if not page_more():
1581 1584 return
1582 1585 esc_list = esc_re.findall(hunk)
1583 1586 if len(esc_list) > 0:
1584 1587 last_escape = esc_list[-1]
1585 1588 print >>Term.cout, last_escape + os.linesep.join(screens[-1])
1586 1589
1587 1590 #----------------------------------------------------------------------------
1588 1591 def page(strng,start=0,screen_lines=0,pager_cmd = None):
1589 1592 """Print a string, piping through a pager after a certain length.
1590 1593
1591 1594 The screen_lines parameter specifies the number of *usable* lines of your
1592 1595 terminal screen (total lines minus lines you need to reserve to show other
1593 1596 information).
1594 1597
1595 1598 If you set screen_lines to a number <=0, page() will try to auto-determine
1596 1599 your screen size and will only use up to (screen_size+screen_lines) for
1597 1600 printing, paging after that. That is, if you want auto-detection but need
1598 1601 to reserve the bottom 3 lines of the screen, use screen_lines = -3, and for
1599 1602 auto-detection without any lines reserved simply use screen_lines = 0.
1600 1603
1601 1604 If a string won't fit in the allowed lines, it is sent through the
1602 1605 specified pager command. If none given, look for PAGER in the environment,
1603 1606 and ultimately default to less.
1604 1607
1605 1608 If no system pager works, the string is sent through a 'dumb pager'
1606 1609 written in python, very simplistic.
1607 1610 """
1608 1611
1609 1612 # Some routines may auto-compute start offsets incorrectly and pass a
1610 1613 # negative value. Offset to 0 for robustness.
1611 1614 start = max(0,start)
1612 1615
1613 1616 # first, try the hook
1614 1617 ip = IPython.ipapi.get()
1615 1618 if ip:
1616 1619 try:
1617 1620 ip.IP.hooks.show_in_pager(strng)
1618 1621 return
1619 1622 except IPython.ipapi.TryNext:
1620 1623 pass
1621 1624
1622 1625 # Ugly kludge, but calling curses.initscr() flat out crashes in emacs
1623 1626 TERM = os.environ.get('TERM','dumb')
1624 1627 if TERM in ['dumb','emacs'] and os.name != 'nt':
1625 1628 print strng
1626 1629 return
1627 1630 # chop off the topmost part of the string we don't want to see
1628 1631 str_lines = strng.split(os.linesep)[start:]
1629 1632 str_toprint = os.linesep.join(str_lines)
1630 1633 num_newlines = len(str_lines)
1631 1634 len_str = len(str_toprint)
1632 1635
1633 1636 # Dumb heuristics to guesstimate number of on-screen lines the string
1634 1637 # takes. Very basic, but good enough for docstrings in reasonable
1635 1638 # terminals. If someone later feels like refining it, it's not hard.
1636 1639 numlines = max(num_newlines,int(len_str/80)+1)
1637 1640
1638 1641 if os.name == "nt":
1639 1642 screen_lines_def = get_console_size(defaulty=25)[1]
1640 1643 else:
1641 1644 screen_lines_def = 25 # default value if we can't auto-determine
1642 1645
1643 1646 # auto-determine screen size
1644 1647 if screen_lines <= 0:
1645 1648 if TERM=='xterm':
1646 1649 use_curses = USE_CURSES
1647 1650 else:
1648 1651 # curses causes problems on many terminals other than xterm.
1649 1652 use_curses = False
1650 1653 if use_curses:
1651 1654 # There is a bug in curses, where *sometimes* it fails to properly
1652 1655 # initialize, and then after the endwin() call is made, the
1653 1656 # terminal is left in an unusable state. Rather than trying to
1654 1657 # check everytime for this (by requesting and comparing termios
1655 1658 # flags each time), we just save the initial terminal state and
1656 1659 # unconditionally reset it every time. It's cheaper than making
1657 1660 # the checks.
1658 1661 term_flags = termios.tcgetattr(sys.stdout)
1659 1662 scr = curses.initscr()
1660 1663 screen_lines_real,screen_cols = scr.getmaxyx()
1661 1664 curses.endwin()
1662 1665 # Restore terminal state in case endwin() didn't.
1663 1666 termios.tcsetattr(sys.stdout,termios.TCSANOW,term_flags)
1664 1667 # Now we have what we needed: the screen size in rows/columns
1665 1668 screen_lines += screen_lines_real
1666 1669 #print '***Screen size:',screen_lines_real,'lines x',\
1667 1670 #screen_cols,'columns.' # dbg
1668 1671 else:
1669 1672 screen_lines += screen_lines_def
1670 1673
1671 1674 #print 'numlines',numlines,'screenlines',screen_lines # dbg
1672 1675 if numlines <= screen_lines :
1673 1676 #print '*** normal print' # dbg
1674 1677 print >>Term.cout, str_toprint
1675 1678 else:
1676 1679 # Try to open pager and default to internal one if that fails.
1677 1680 # All failure modes are tagged as 'retval=1', to match the return
1678 1681 # value of a failed system command. If any intermediate attempt
1679 1682 # sets retval to 1, at the end we resort to our own page_dumb() pager.
1680 1683 pager_cmd = get_pager_cmd(pager_cmd)
1681 1684 pager_cmd += ' ' + get_pager_start(pager_cmd,start)
1682 1685 if os.name == 'nt':
1683 1686 if pager_cmd.startswith('type'):
1684 1687 # The default WinXP 'type' command is failing on complex strings.
1685 1688 retval = 1
1686 1689 else:
1687 1690 tmpname = tempfile.mktemp('.txt')
1688 1691 tmpfile = file(tmpname,'wt')
1689 1692 tmpfile.write(strng)
1690 1693 tmpfile.close()
1691 1694 cmd = "%s < %s" % (pager_cmd,tmpname)
1692 1695 if os.system(cmd):
1693 1696 retval = 1
1694 1697 else:
1695 1698 retval = None
1696 1699 os.remove(tmpname)
1697 1700 else:
1698 1701 try:
1699 1702 retval = None
1700 1703 # if I use popen4, things hang. No idea why.
1701 1704 #pager,shell_out = os.popen4(pager_cmd)
1702 1705 pager = os.popen(pager_cmd,'w')
1703 1706 pager.write(strng)
1704 1707 pager.close()
1705 1708 retval = pager.close() # success returns None
1706 1709 except IOError,msg: # broken pipe when user quits
1707 1710 if msg.args == (32,'Broken pipe'):
1708 1711 retval = None
1709 1712 else:
1710 1713 retval = 1
1711 1714 except OSError:
1712 1715 # Other strange problems, sometimes seen in Win2k/cygwin
1713 1716 retval = 1
1714 1717 if retval is not None:
1715 1718 page_dumb(strng,screen_lines=screen_lines)
1716 1719
1717 1720 #----------------------------------------------------------------------------
1718 1721 def page_file(fname,start = 0, pager_cmd = None):
1719 1722 """Page a file, using an optional pager command and starting line.
1720 1723 """
1721 1724
1722 1725 pager_cmd = get_pager_cmd(pager_cmd)
1723 1726 pager_cmd += ' ' + get_pager_start(pager_cmd,start)
1724 1727
1725 1728 try:
1726 1729 if os.environ['TERM'] in ['emacs','dumb']:
1727 1730 raise EnvironmentError
1728 1731 xsys(pager_cmd + ' ' + fname)
1729 1732 except:
1730 1733 try:
1731 1734 if start > 0:
1732 1735 start -= 1
1733 1736 page(open(fname).read(),start)
1734 1737 except:
1735 1738 print 'Unable to show file',`fname`
1736 1739
1737 1740
1738 1741 #----------------------------------------------------------------------------
1739 1742 def snip_print(str,width = 75,print_full = 0,header = ''):
1740 1743 """Print a string snipping the midsection to fit in width.
1741 1744
1742 1745 print_full: mode control:
1743 1746 - 0: only snip long strings
1744 1747 - 1: send to page() directly.
1745 1748 - 2: snip long strings and ask for full length viewing with page()
1746 1749 Return 1 if snipping was necessary, 0 otherwise."""
1747 1750
1748 1751 if print_full == 1:
1749 1752 page(header+str)
1750 1753 return 0
1751 1754
1752 1755 print header,
1753 1756 if len(str) < width:
1754 1757 print str
1755 1758 snip = 0
1756 1759 else:
1757 1760 whalf = int((width -5)/2)
1758 1761 print str[:whalf] + ' <...> ' + str[-whalf:]
1759 1762 snip = 1
1760 1763 if snip and print_full == 2:
1761 1764 if raw_input(header+' Snipped. View (y/n)? [N]').lower() == 'y':
1762 1765 page(str)
1763 1766 return snip
1764 1767
1765 1768 #****************************************************************************
1766 1769 # lists, dicts and structures
1767 1770
1768 1771 def belong(candidates,checklist):
1769 1772 """Check whether a list of items appear in a given list of options.
1770 1773
1771 1774 Returns a list of 1 and 0, one for each candidate given."""
1772 1775
1773 1776 return [x in checklist for x in candidates]
1774 1777
1775 1778 #----------------------------------------------------------------------------
1776 1779 def uniq_stable(elems):
1777 1780 """uniq_stable(elems) -> list
1778 1781
1779 1782 Return from an iterable, a list of all the unique elements in the input,
1780 1783 but maintaining the order in which they first appear.
1781 1784
1782 1785 A naive solution to this problem which just makes a dictionary with the
1783 1786 elements as keys fails to respect the stability condition, since
1784 1787 dictionaries are unsorted by nature.
1785 1788
1786 1789 Note: All elements in the input must be valid dictionary keys for this
1787 1790 routine to work, as it internally uses a dictionary for efficiency
1788 1791 reasons."""
1789 1792
1790 1793 unique = []
1791 1794 unique_dict = {}
1792 1795 for nn in elems:
1793 1796 if nn not in unique_dict:
1794 1797 unique.append(nn)
1795 1798 unique_dict[nn] = None
1796 1799 return unique
1797 1800
1798 1801 #----------------------------------------------------------------------------
1799 1802 class NLprinter:
1800 1803 """Print an arbitrarily nested list, indicating index numbers.
1801 1804
1802 1805 An instance of this class called nlprint is available and callable as a
1803 1806 function.
1804 1807
1805 1808 nlprint(list,indent=' ',sep=': ') -> prints indenting each level by 'indent'
1806 1809 and using 'sep' to separate the index from the value. """
1807 1810
1808 1811 def __init__(self):
1809 1812 self.depth = 0
1810 1813
1811 1814 def __call__(self,lst,pos='',**kw):
1812 1815 """Prints the nested list numbering levels."""
1813 1816 kw.setdefault('indent',' ')
1814 1817 kw.setdefault('sep',': ')
1815 1818 kw.setdefault('start',0)
1816 1819 kw.setdefault('stop',len(lst))
1817 1820 # we need to remove start and stop from kw so they don't propagate
1818 1821 # into a recursive call for a nested list.
1819 1822 start = kw['start']; del kw['start']
1820 1823 stop = kw['stop']; del kw['stop']
1821 1824 if self.depth == 0 and 'header' in kw.keys():
1822 1825 print kw['header']
1823 1826
1824 1827 for idx in range(start,stop):
1825 1828 elem = lst[idx]
1826 1829 if type(elem)==type([]):
1827 1830 self.depth += 1
1828 1831 self.__call__(elem,itpl('$pos$idx,'),**kw)
1829 1832 self.depth -= 1
1830 1833 else:
1831 1834 printpl(kw['indent']*self.depth+'$pos$idx$kw["sep"]$elem')
1832 1835
1833 1836 nlprint = NLprinter()
1834 1837 #----------------------------------------------------------------------------
1835 1838 def all_belong(candidates,checklist):
1836 1839 """Check whether a list of items ALL appear in a given list of options.
1837 1840
1838 1841 Returns a single 1 or 0 value."""
1839 1842
1840 1843 return 1-(0 in [x in checklist for x in candidates])
1841 1844
1842 1845 #----------------------------------------------------------------------------
1843 1846 def sort_compare(lst1,lst2,inplace = 1):
1844 1847 """Sort and compare two lists.
1845 1848
1846 1849 By default it does it in place, thus modifying the lists. Use inplace = 0
1847 1850 to avoid that (at the cost of temporary copy creation)."""
1848 1851 if not inplace:
1849 1852 lst1 = lst1[:]
1850 1853 lst2 = lst2[:]
1851 1854 lst1.sort(); lst2.sort()
1852 1855 return lst1 == lst2
1853 1856
1854 1857 #----------------------------------------------------------------------------
1855 1858 def list2dict(lst):
1856 1859 """Takes a list of (key,value) pairs and turns it into a dict."""
1857 1860
1858 1861 dic = {}
1859 1862 for k,v in lst: dic[k] = v
1860 1863 return dic
1861 1864
1862 1865 #----------------------------------------------------------------------------
1863 1866 def list2dict2(lst,default=''):
1864 1867 """Takes a list and turns it into a dict.
1865 1868 Much slower than list2dict, but more versatile. This version can take
1866 1869 lists with sublists of arbitrary length (including sclars)."""
1867 1870
1868 1871 dic = {}
1869 1872 for elem in lst:
1870 1873 if type(elem) in (types.ListType,types.TupleType):
1871 1874 size = len(elem)
1872 1875 if size == 0:
1873 1876 pass
1874 1877 elif size == 1:
1875 1878 dic[elem] = default
1876 1879 else:
1877 1880 k,v = elem[0], elem[1:]
1878 1881 if len(v) == 1: v = v[0]
1879 1882 dic[k] = v
1880 1883 else:
1881 1884 dic[elem] = default
1882 1885 return dic
1883 1886
1884 1887 #----------------------------------------------------------------------------
1885 1888 def flatten(seq):
1886 1889 """Flatten a list of lists (NOT recursive, only works for 2d lists)."""
1887 1890
1888 1891 return [x for subseq in seq for x in subseq]
1889 1892
1890 1893 #----------------------------------------------------------------------------
1891 1894 def get_slice(seq,start=0,stop=None,step=1):
1892 1895 """Get a slice of a sequence with variable step. Specify start,stop,step."""
1893 1896 if stop == None:
1894 1897 stop = len(seq)
1895 1898 item = lambda i: seq[i]
1896 1899 return map(item,xrange(start,stop,step))
1897 1900
1898 1901 #----------------------------------------------------------------------------
1899 1902 def chop(seq,size):
1900 1903 """Chop a sequence into chunks of the given size."""
1901 1904 chunk = lambda i: seq[i:i+size]
1902 1905 return map(chunk,xrange(0,len(seq),size))
1903 1906
1904 1907 #----------------------------------------------------------------------------
1905 1908 # with is a keyword as of python 2.5, so this function is renamed to withobj
1906 1909 # from its old 'with' name.
1907 1910 def with_obj(object, **args):
1908 1911 """Set multiple attributes for an object, similar to Pascal's with.
1909 1912
1910 1913 Example:
1911 1914 with_obj(jim,
1912 1915 born = 1960,
1913 1916 haircolour = 'Brown',
1914 1917 eyecolour = 'Green')
1915 1918
1916 1919 Credit: Greg Ewing, in
1917 1920 http://mail.python.org/pipermail/python-list/2001-May/040703.html.
1918 1921
1919 1922 NOTE: up until IPython 0.7.2, this was called simply 'with', but 'with'
1920 1923 has become a keyword for Python 2.5, so we had to rename it."""
1921 1924
1922 1925 object.__dict__.update(args)
1923 1926
1924 1927 #----------------------------------------------------------------------------
1925 1928 def setattr_list(obj,alist,nspace = None):
1926 1929 """Set a list of attributes for an object taken from a namespace.
1927 1930
1928 1931 setattr_list(obj,alist,nspace) -> sets in obj all the attributes listed in
1929 1932 alist with their values taken from nspace, which must be a dict (something
1930 1933 like locals() will often do) If nspace isn't given, locals() of the
1931 1934 *caller* is used, so in most cases you can omit it.
1932 1935
1933 1936 Note that alist can be given as a string, which will be automatically
1934 1937 split into a list on whitespace. If given as a list, it must be a list of
1935 1938 *strings* (the variable names themselves), not of variables."""
1936 1939
1937 1940 # this grabs the local variables from the *previous* call frame -- that is
1938 1941 # the locals from the function that called setattr_list().
1939 1942 # - snipped from weave.inline()
1940 1943 if nspace is None:
1941 1944 call_frame = sys._getframe().f_back
1942 1945 nspace = call_frame.f_locals
1943 1946
1944 1947 if type(alist) in StringTypes:
1945 1948 alist = alist.split()
1946 1949 for attr in alist:
1947 1950 val = eval(attr,nspace)
1948 1951 setattr(obj,attr,val)
1949 1952
1950 1953 #----------------------------------------------------------------------------
1951 1954 def getattr_list(obj,alist,*args):
1952 1955 """getattr_list(obj,alist[, default]) -> attribute list.
1953 1956
1954 1957 Get a list of named attributes for an object. When a default argument is
1955 1958 given, it is returned when the attribute doesn't exist; without it, an
1956 1959 exception is raised in that case.
1957 1960
1958 1961 Note that alist can be given as a string, which will be automatically
1959 1962 split into a list on whitespace. If given as a list, it must be a list of
1960 1963 *strings* (the variable names themselves), not of variables."""
1961 1964
1962 1965 if type(alist) in StringTypes:
1963 1966 alist = alist.split()
1964 1967 if args:
1965 1968 if len(args)==1:
1966 1969 default = args[0]
1967 1970 return map(lambda attr: getattr(obj,attr,default),alist)
1968 1971 else:
1969 1972 raise ValueError,'getattr_list() takes only one optional argument'
1970 1973 else:
1971 1974 return map(lambda attr: getattr(obj,attr),alist)
1972 1975
1973 1976 #----------------------------------------------------------------------------
1974 1977 def map_method(method,object_list,*argseq,**kw):
1975 1978 """map_method(method,object_list,*args,**kw) -> list
1976 1979
1977 1980 Return a list of the results of applying the methods to the items of the
1978 1981 argument sequence(s). If more than one sequence is given, the method is
1979 1982 called with an argument list consisting of the corresponding item of each
1980 1983 sequence. All sequences must be of the same length.
1981 1984
1982 1985 Keyword arguments are passed verbatim to all objects called.
1983 1986
1984 1987 This is Python code, so it's not nearly as fast as the builtin map()."""
1985 1988
1986 1989 out_list = []
1987 1990 idx = 0
1988 1991 for object in object_list:
1989 1992 try:
1990 1993 handler = getattr(object, method)
1991 1994 except AttributeError:
1992 1995 out_list.append(None)
1993 1996 else:
1994 1997 if argseq:
1995 1998 args = map(lambda lst:lst[idx],argseq)
1996 1999 #print 'ob',object,'hand',handler,'ar',args # dbg
1997 2000 out_list.append(handler(args,**kw))
1998 2001 else:
1999 2002 out_list.append(handler(**kw))
2000 2003 idx += 1
2001 2004 return out_list
2002 2005
2003 2006 #----------------------------------------------------------------------------
2004 2007 def get_class_members(cls):
2005 2008 ret = dir(cls)
2006 2009 if hasattr(cls,'__bases__'):
2007 2010 for base in cls.__bases__:
2008 2011 ret.extend(get_class_members(base))
2009 2012 return ret
2010 2013
2011 2014 #----------------------------------------------------------------------------
2012 2015 def dir2(obj):
2013 2016 """dir2(obj) -> list of strings
2014 2017
2015 2018 Extended version of the Python builtin dir(), which does a few extra
2016 2019 checks, and supports common objects with unusual internals that confuse
2017 2020 dir(), such as Traits and PyCrust.
2018 2021
2019 2022 This version is guaranteed to return only a list of true strings, whereas
2020 2023 dir() returns anything that objects inject into themselves, even if they
2021 2024 are later not really valid for attribute access (many extension libraries
2022 2025 have such bugs).
2023 2026 """
2024 2027
2025 2028 # Start building the attribute list via dir(), and then complete it
2026 2029 # with a few extra special-purpose calls.
2027 2030 words = dir(obj)
2028 2031
2029 2032 if hasattr(obj,'__class__'):
2030 2033 words.append('__class__')
2031 2034 words.extend(get_class_members(obj.__class__))
2032 2035 #if '__base__' in words: 1/0
2033 2036
2034 2037 # Some libraries (such as traits) may introduce duplicates, we want to
2035 2038 # track and clean this up if it happens
2036 2039 may_have_dupes = False
2037 2040
2038 2041 # this is the 'dir' function for objects with Enthought's traits
2039 2042 if hasattr(obj, 'trait_names'):
2040 2043 try:
2041 2044 words.extend(obj.trait_names())
2042 2045 may_have_dupes = True
2043 2046 except TypeError:
2044 2047 # This will happen if `obj` is a class and not an instance.
2045 2048 pass
2046 2049
2047 2050 # Support for PyCrust-style _getAttributeNames magic method.
2048 2051 if hasattr(obj, '_getAttributeNames'):
2049 2052 try:
2050 2053 words.extend(obj._getAttributeNames())
2051 2054 may_have_dupes = True
2052 2055 except TypeError:
2053 2056 # `obj` is a class and not an instance. Ignore
2054 2057 # this error.
2055 2058 pass
2056 2059
2057 2060 if may_have_dupes:
2058 2061 # eliminate possible duplicates, as some traits may also
2059 2062 # appear as normal attributes in the dir() call.
2060 2063 words = list(set(words))
2061 2064 words.sort()
2062 2065
2063 2066 # filter out non-string attributes which may be stuffed by dir() calls
2064 2067 # and poor coding in third-party modules
2065 2068 return [w for w in words if isinstance(w, basestring)]
2066 2069
2067 2070 #----------------------------------------------------------------------------
2068 2071 def import_fail_info(mod_name,fns=None):
2069 2072 """Inform load failure for a module."""
2070 2073
2071 2074 if fns == None:
2072 2075 warn("Loading of %s failed.\n" % (mod_name,))
2073 2076 else:
2074 2077 warn("Loading of %s from %s failed.\n" % (fns,mod_name))
2075 2078
2076 2079 #----------------------------------------------------------------------------
2077 2080 # Proposed popitem() extension, written as a method
2078 2081
2079 2082
2080 2083 class NotGiven: pass
2081 2084
2082 2085 def popkey(dct,key,default=NotGiven):
2083 2086 """Return dct[key] and delete dct[key].
2084 2087
2085 2088 If default is given, return it if dct[key] doesn't exist, otherwise raise
2086 2089 KeyError. """
2087 2090
2088 2091 try:
2089 2092 val = dct[key]
2090 2093 except KeyError:
2091 2094 if default is NotGiven:
2092 2095 raise
2093 2096 else:
2094 2097 return default
2095 2098 else:
2096 2099 del dct[key]
2097 2100 return val
2098 2101
2099 2102 def wrap_deprecated(func, suggest = '<nothing>'):
2100 2103 def newFunc(*args, **kwargs):
2101 2104 warnings.warn("Call to deprecated function %s, use %s instead" %
2102 2105 ( func.__name__, suggest),
2103 2106 category=DeprecationWarning,
2104 2107 stacklevel = 2)
2105 2108 return func(*args, **kwargs)
2106 2109 return newFunc
2107 2110
2108 2111
2109 2112 def _num_cpus_unix():
2110 2113 """Return the number of active CPUs on a Unix system."""
2111 2114 return os.sysconf("SC_NPROCESSORS_ONLN")
2112 2115
2113 2116
2114 2117 def _num_cpus_darwin():
2115 2118 """Return the number of active CPUs on a Darwin system."""
2116 2119 p = subprocess.Popen(['sysctl','-n','hw.ncpu'],stdout=subprocess.PIPE)
2117 2120 return p.stdout.read()
2118 2121
2119 2122
2120 2123 def _num_cpus_windows():
2121 2124 """Return the number of active CPUs on a Windows system."""
2122 2125 return os.environ.get("NUMBER_OF_PROCESSORS")
2123 2126
2124 2127
2125 2128 def num_cpus():
2126 2129 """Return the effective number of CPUs in the system as an integer.
2127 2130
2128 2131 This cross-platform function makes an attempt at finding the total number of
2129 2132 available CPUs in the system, as returned by various underlying system and
2130 2133 python calls.
2131 2134
2132 2135 If it can't find a sensible answer, it returns 1 (though an error *may* make
2133 2136 it return a large positive number that's actually incorrect).
2134 2137 """
2135 2138
2136 2139 # Many thanks to the Parallel Python project (http://www.parallelpython.com)
2137 2140 # for the names of the keys we needed to look up for this function. This
2138 2141 # code was inspired by their equivalent function.
2139 2142
2140 2143 ncpufuncs = {'Linux':_num_cpus_unix,
2141 2144 'Darwin':_num_cpus_darwin,
2142 2145 'Windows':_num_cpus_windows,
2143 2146 # On Vista, python < 2.5.2 has a bug and returns 'Microsoft'
2144 2147 # See http://bugs.python.org/issue1082 for details.
2145 2148 'Microsoft':_num_cpus_windows,
2146 2149 }
2147 2150
2148 2151 ncpufunc = ncpufuncs.get(platform.system(),
2149 2152 # default to unix version (Solaris, AIX, etc)
2150 2153 _num_cpus_unix)
2151 2154
2152 2155 try:
2153 2156 ncpus = max(1,int(ncpufunc()))
2154 2157 except:
2155 2158 ncpus = 1
2156 2159 return ncpus
2157 2160
2158 2161 #*************************** end of file <genutils.py> **********************
@@ -1,2789 +1,2790 b''
1 1 # -*- coding: utf-8 -*-
2 2 """
3 3 IPython -- An enhanced Interactive Python
4 4
5 5 Requires Python 2.4 or newer.
6 6
7 7 This file contains all the classes and helper functions specific to IPython.
8 8 """
9 9
10 10 #*****************************************************************************
11 11 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
12 12 # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu>
13 13 #
14 14 # Distributed under the terms of the BSD License. The full license is in
15 15 # the file COPYING, distributed as part of this software.
16 16 #
17 17 # Note: this code originally subclassed code.InteractiveConsole from the
18 18 # Python standard library. Over time, all of that class has been copied
19 19 # verbatim here for modifications which could not be accomplished by
20 20 # subclassing. At this point, there are no dependencies at all on the code
21 21 # module anymore (it is not even imported). The Python License (sec. 2)
22 22 # allows for this, but it's always nice to acknowledge credit where credit is
23 23 # due.
24 24 #*****************************************************************************
25 25
26 26 #****************************************************************************
27 27 # Modules and globals
28 28
29 29 # Python standard modules
30 30 import __main__
31 31 import __builtin__
32 32 import StringIO
33 33 import bdb
34 34 import cPickle as pickle
35 35 import codeop
36 36 import exceptions
37 37 import glob
38 38 import inspect
39 39 import keyword
40 40 import new
41 41 import os
42 42 import pydoc
43 43 import re
44 44 import shutil
45 45 import string
46 46 import sys
47 47 import tempfile
48 48 import traceback
49 49 import types
50 50 from pprint import pprint, pformat
51 51
52 52 # IPython's own modules
53 53 #import IPython
54 54 from IPython import Debugger,OInspect,PyColorize,ultraTB
55 55 from IPython.ColorANSI import ColorScheme,ColorSchemeTable # too long names
56 56 from IPython.Extensions import pickleshare
57 57 from IPython.FakeModule import FakeModule
58 58 from IPython.Itpl import Itpl,itpl,printpl,ItplNS,itplns
59 59 from IPython.Logger import Logger
60 60 from IPython.Magic import Magic
61 61 from IPython.Prompts import CachedOutput
62 62 from IPython.ipstruct import Struct
63 63 from IPython.background_jobs import BackgroundJobManager
64 64 from IPython.usage import cmd_line_usage,interactive_usage
65 65 from IPython.genutils import *
66 66 from IPython.strdispatch import StrDispatch
67 67 import IPython.ipapi
68 68 import IPython.history
69 69 import IPython.prefilter as prefilter
70 70 import IPython.shadowns
71 71 # Globals
72 72
73 73 # store the builtin raw_input globally, and use this always, in case user code
74 74 # overwrites it (like wx.py.PyShell does)
75 75 raw_input_original = raw_input
76 76
77 77 # compiled regexps for autoindent management
78 78 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
79 79
80 80
81 81 #****************************************************************************
82 82 # Some utility function definitions
83 83
84 84 ini_spaces_re = re.compile(r'^(\s+)')
85 85
86 86 def num_ini_spaces(strng):
87 87 """Return the number of initial spaces in a string"""
88 88
89 89 ini_spaces = ini_spaces_re.match(strng)
90 90 if ini_spaces:
91 91 return ini_spaces.end()
92 92 else:
93 93 return 0
94 94
95 95 def softspace(file, newvalue):
96 96 """Copied from code.py, to remove the dependency"""
97 97
98 98 oldvalue = 0
99 99 try:
100 100 oldvalue = file.softspace
101 101 except AttributeError:
102 102 pass
103 103 try:
104 104 file.softspace = newvalue
105 105 except (AttributeError, TypeError):
106 106 # "attribute-less object" or "read-only attributes"
107 107 pass
108 108 return oldvalue
109 109
110 110
111 111 #****************************************************************************
112 112 # Local use exceptions
113 113 class SpaceInInput(exceptions.Exception): pass
114 114
115 115
116 116 #****************************************************************************
117 117 # Local use classes
118 118 class Bunch: pass
119 119
120 120 class Undefined: pass
121 121
122 122 class Quitter(object):
123 123 """Simple class to handle exit, similar to Python 2.5's.
124 124
125 125 It handles exiting in an ipython-safe manner, which the one in Python 2.5
126 126 doesn't do (obviously, since it doesn't know about ipython)."""
127 127
128 128 def __init__(self,shell,name):
129 129 self.shell = shell
130 130 self.name = name
131 131
132 132 def __repr__(self):
133 133 return 'Type %s() to exit.' % self.name
134 134 __str__ = __repr__
135 135
136 136 def __call__(self):
137 137 self.shell.exit()
138 138
139 139 class InputList(list):
140 140 """Class to store user input.
141 141
142 142 It's basically a list, but slices return a string instead of a list, thus
143 143 allowing things like (assuming 'In' is an instance):
144 144
145 145 exec In[4:7]
146 146
147 147 or
148 148
149 149 exec In[5:9] + In[14] + In[21:25]"""
150 150
151 151 def __getslice__(self,i,j):
152 152 return ''.join(list.__getslice__(self,i,j))
153 153
154 154 class SyntaxTB(ultraTB.ListTB):
155 155 """Extension which holds some state: the last exception value"""
156 156
157 157 def __init__(self,color_scheme = 'NoColor'):
158 158 ultraTB.ListTB.__init__(self,color_scheme)
159 159 self.last_syntax_error = None
160 160
161 161 def __call__(self, etype, value, elist):
162 162 self.last_syntax_error = value
163 163 ultraTB.ListTB.__call__(self,etype,value,elist)
164 164
165 165 def clear_err_state(self):
166 166 """Return the current error state and clear it"""
167 167 e = self.last_syntax_error
168 168 self.last_syntax_error = None
169 169 return e
170 170
171 171 #****************************************************************************
172 172 # Main IPython class
173 173
174 174 # FIXME: the Magic class is a mixin for now, and will unfortunately remain so
175 175 # until a full rewrite is made. I've cleaned all cross-class uses of
176 176 # attributes and methods, but too much user code out there relies on the
177 177 # equlity %foo == __IP.magic_foo, so I can't actually remove the mixin usage.
178 178 #
179 179 # But at least now, all the pieces have been separated and we could, in
180 180 # principle, stop using the mixin. This will ease the transition to the
181 181 # chainsaw branch.
182 182
183 183 # For reference, the following is the list of 'self.foo' uses in the Magic
184 184 # class as of 2005-12-28. These are names we CAN'T use in the main ipython
185 185 # class, to prevent clashes.
186 186
187 187 # ['self.__class__', 'self.__dict__', 'self._inspect', 'self._ofind',
188 188 # 'self.arg_err', 'self.extract_input', 'self.format_', 'self.lsmagic',
189 189 # 'self.magic_', 'self.options_table', 'self.parse', 'self.shell',
190 190 # 'self.value']
191 191
192 192 class InteractiveShell(object,Magic):
193 193 """An enhanced console for Python."""
194 194
195 195 # class attribute to indicate whether the class supports threads or not.
196 196 # Subclasses with thread support should override this as needed.
197 197 isthreaded = False
198 198
199 199 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
200 200 user_ns=None,user_global_ns=None,banner2='',
201 201 custom_exceptions=((),None),embedded=False):
202 202
203 203 # log system
204 204 self.logger = Logger(self,logfname='ipython_log.py',logmode='rotate')
205 205
206 206 # Job manager (for jobs run as background threads)
207 207 self.jobs = BackgroundJobManager()
208 208
209 209 # Store the actual shell's name
210 210 self.name = name
211 211 self.more = False
212 212
213 213 # We need to know whether the instance is meant for embedding, since
214 214 # global/local namespaces need to be handled differently in that case
215 215 self.embedded = embedded
216 216 if embedded:
217 217 # Control variable so users can, from within the embedded instance,
218 218 # permanently deactivate it.
219 219 self.embedded_active = True
220 220
221 221 # command compiler
222 222 self.compile = codeop.CommandCompiler()
223 223
224 224 # User input buffer
225 225 self.buffer = []
226 226
227 227 # Default name given in compilation of code
228 228 self.filename = '<ipython console>'
229 229
230 230 # Install our own quitter instead of the builtins. For python2.3-2.4,
231 231 # this brings in behavior like 2.5, and for 2.5 it's identical.
232 232 __builtin__.exit = Quitter(self,'exit')
233 233 __builtin__.quit = Quitter(self,'quit')
234 234
235 235 # Make an empty namespace, which extension writers can rely on both
236 236 # existing and NEVER being used by ipython itself. This gives them a
237 237 # convenient location for storing additional information and state
238 238 # their extensions may require, without fear of collisions with other
239 239 # ipython names that may develop later.
240 240 self.meta = Struct()
241 241
242 242 # Create the namespace where the user will operate. user_ns is
243 243 # normally the only one used, and it is passed to the exec calls as
244 244 # the locals argument. But we do carry a user_global_ns namespace
245 245 # given as the exec 'globals' argument, This is useful in embedding
246 246 # situations where the ipython shell opens in a context where the
247 247 # distinction between locals and globals is meaningful. For
248 248 # non-embedded contexts, it is just the same object as the user_ns dict.
249 249
250 250 # FIXME. For some strange reason, __builtins__ is showing up at user
251 251 # level as a dict instead of a module. This is a manual fix, but I
252 252 # should really track down where the problem is coming from. Alex
253 253 # Schmolck reported this problem first.
254 254
255 255 # A useful post by Alex Martelli on this topic:
256 256 # Re: inconsistent value from __builtins__
257 257 # Von: Alex Martelli <aleaxit@yahoo.com>
258 258 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
259 259 # Gruppen: comp.lang.python
260 260
261 261 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
262 262 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
263 263 # > <type 'dict'>
264 264 # > >>> print type(__builtins__)
265 265 # > <type 'module'>
266 266 # > Is this difference in return value intentional?
267 267
268 268 # Well, it's documented that '__builtins__' can be either a dictionary
269 269 # or a module, and it's been that way for a long time. Whether it's
270 270 # intentional (or sensible), I don't know. In any case, the idea is
271 271 # that if you need to access the built-in namespace directly, you
272 272 # should start with "import __builtin__" (note, no 's') which will
273 273 # definitely give you a module. Yeah, it's somewhat confusing:-(.
274 274
275 275 # These routines return properly built dicts as needed by the rest of
276 276 # the code, and can also be used by extension writers to generate
277 277 # properly initialized namespaces.
278 278 user_ns, user_global_ns = IPython.ipapi.make_user_namespaces(user_ns,
279 279 user_global_ns)
280 280
281 281 # Assign namespaces
282 282 # This is the namespace where all normal user variables live
283 283 self.user_ns = user_ns
284 284 self.user_global_ns = user_global_ns
285 285
286 286 # An auxiliary namespace that checks what parts of the user_ns were
287 287 # loaded at startup, so we can list later only variables defined in
288 288 # actual interactive use. Since it is always a subset of user_ns, it
289 289 # doesn't need to be seaparately tracked in the ns_table
290 290 self.user_config_ns = {}
291 291
292 292 # A namespace to keep track of internal data structures to prevent
293 293 # them from cluttering user-visible stuff. Will be updated later
294 294 self.internal_ns = {}
295 295
296 296 # Namespace of system aliases. Each entry in the alias
297 297 # table must be a 2-tuple of the form (N,name), where N is the number
298 298 # of positional arguments of the alias.
299 299 self.alias_table = {}
300 300
301 301 # Now that FakeModule produces a real module, we've run into a nasty
302 302 # problem: after script execution (via %run), the module where the user
303 303 # code ran is deleted. Now that this object is a true module (needed
304 304 # so docetst and other tools work correctly), the Python module
305 305 # teardown mechanism runs over it, and sets to None every variable
306 306 # present in that module. Top-level references to objects from the
307 307 # script survive, because the user_ns is updated with them. However,
308 308 # calling functions defined in the script that use other things from
309 309 # the script will fail, because the function's closure had references
310 310 # to the original objects, which are now all None. So we must protect
311 311 # these modules from deletion by keeping a cache. To avoid keeping
312 312 # stale modules around (we only need the one from the last run), we use
313 313 # a dict keyed with the full path to the script, so only the last
314 314 # version of the module is held in the cache. The %reset command will
315 315 # flush this cache. See the cache_main_mod() and clear_main_mod_cache()
316 316 # methods for details on use.
317 317 self._user_main_modules = {}
318 318
319 319 # A table holding all the namespaces IPython deals with, so that
320 320 # introspection facilities can search easily.
321 321 self.ns_table = {'user':user_ns,
322 322 'user_global':user_global_ns,
323 323 'alias':self.alias_table,
324 324 'internal':self.internal_ns,
325 325 'builtin':__builtin__.__dict__
326 326 }
327 327
328 328 # Similarly, track all namespaces where references can be held and that
329 329 # we can safely clear (so it can NOT include builtin). This one can be
330 330 # a simple list.
331 331 self.ns_refs_table = [ user_ns, user_global_ns, self.user_config_ns,
332 332 self.alias_table, self.internal_ns,
333 333 self._user_main_modules ]
334 334
335 335 # We need to insert into sys.modules something that looks like a
336 336 # module but which accesses the IPython namespace, for shelve and
337 337 # pickle to work interactively. Normally they rely on getting
338 338 # everything out of __main__, but for embedding purposes each IPython
339 339 # instance has its own private namespace, so we can't go shoving
340 340 # everything into __main__.
341 341
342 342 # note, however, that we should only do this for non-embedded
343 343 # ipythons, which really mimic the __main__.__dict__ with their own
344 344 # namespace. Embedded instances, on the other hand, should not do
345 345 # this because they need to manage the user local/global namespaces
346 346 # only, but they live within a 'normal' __main__ (meaning, they
347 347 # shouldn't overtake the execution environment of the script they're
348 348 # embedded in).
349 349
350 350 if not embedded:
351 351 try:
352 352 main_name = self.user_ns['__name__']
353 353 except KeyError:
354 354 raise KeyError,'user_ns dictionary MUST have a "__name__" key'
355 355 else:
356 356 #print "pickle hack in place" # dbg
357 357 #print 'main_name:',main_name # dbg
358 358 sys.modules[main_name] = FakeModule(self.user_ns)
359 359
360 360 # List of input with multi-line handling.
361 361 self.input_hist = InputList()
362 362 # This one will hold the 'raw' input history, without any
363 363 # pre-processing. This will allow users to retrieve the input just as
364 364 # it was exactly typed in by the user, with %hist -r.
365 365 self.input_hist_raw = InputList()
366 366
367 367 # list of visited directories
368 368 try:
369 369 self.dir_hist = [os.getcwd()]
370 370 except OSError:
371 371 self.dir_hist = []
372 372
373 373 # dict of output history
374 374 self.output_hist = {}
375 375
376 376 # Get system encoding at startup time. Certain terminals (like Emacs
377 377 # under Win32 have it set to None, and we need to have a known valid
378 378 # encoding to use in the raw_input() method
379 379 try:
380 380 self.stdin_encoding = sys.stdin.encoding or 'ascii'
381 381 except AttributeError:
382 382 self.stdin_encoding = 'ascii'
383 383
384 384 # dict of things NOT to alias (keywords, builtins and some magics)
385 385 no_alias = {}
386 386 no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias']
387 387 for key in keyword.kwlist + no_alias_magics:
388 388 no_alias[key] = 1
389 389 no_alias.update(__builtin__.__dict__)
390 390 self.no_alias = no_alias
391 391
392 392 # Object variable to store code object waiting execution. This is
393 393 # used mainly by the multithreaded shells, but it can come in handy in
394 394 # other situations. No need to use a Queue here, since it's a single
395 395 # item which gets cleared once run.
396 396 self.code_to_run = None
397 397
398 398 # escapes for automatic behavior on the command line
399 399 self.ESC_SHELL = '!'
400 400 self.ESC_SH_CAP = '!!'
401 401 self.ESC_HELP = '?'
402 402 self.ESC_MAGIC = '%'
403 403 self.ESC_QUOTE = ','
404 404 self.ESC_QUOTE2 = ';'
405 405 self.ESC_PAREN = '/'
406 406
407 407 # And their associated handlers
408 408 self.esc_handlers = {self.ESC_PAREN : self.handle_auto,
409 409 self.ESC_QUOTE : self.handle_auto,
410 410 self.ESC_QUOTE2 : self.handle_auto,
411 411 self.ESC_MAGIC : self.handle_magic,
412 412 self.ESC_HELP : self.handle_help,
413 413 self.ESC_SHELL : self.handle_shell_escape,
414 414 self.ESC_SH_CAP : self.handle_shell_escape,
415 415 }
416 416
417 417 # class initializations
418 418 Magic.__init__(self,self)
419 419
420 420 # Python source parser/formatter for syntax highlighting
421 421 pyformat = PyColorize.Parser().format
422 422 self.pycolorize = lambda src: pyformat(src,'str',self.rc['colors'])
423 423
424 424 # hooks holds pointers used for user-side customizations
425 425 self.hooks = Struct()
426 426
427 427 self.strdispatchers = {}
428 428
429 429 # Set all default hooks, defined in the IPython.hooks module.
430 430 hooks = IPython.hooks
431 431 for hook_name in hooks.__all__:
432 432 # default hooks have priority 100, i.e. low; user hooks should have
433 433 # 0-100 priority
434 434 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
435 435 #print "bound hook",hook_name
436 436
437 437 # Flag to mark unconditional exit
438 438 self.exit_now = False
439 439
440 440 self.usage_min = """\
441 441 An enhanced console for Python.
442 442 Some of its features are:
443 443 - Readline support if the readline library is present.
444 444 - Tab completion in the local namespace.
445 445 - Logging of input, see command-line options.
446 446 - System shell escape via ! , eg !ls.
447 447 - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.)
448 448 - Keeps track of locally defined variables via %who, %whos.
449 449 - Show object information with a ? eg ?x or x? (use ?? for more info).
450 450 """
451 451 if usage: self.usage = usage
452 452 else: self.usage = self.usage_min
453 453
454 454 # Storage
455 455 self.rc = rc # This will hold all configuration information
456 456 self.pager = 'less'
457 457 # temporary files used for various purposes. Deleted at exit.
458 458 self.tempfiles = []
459 459
460 460 # Keep track of readline usage (later set by init_readline)
461 461 self.has_readline = False
462 462
463 463 # template for logfile headers. It gets resolved at runtime by the
464 464 # logstart method.
465 465 self.loghead_tpl = \
466 466 """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE ***
467 467 #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW
468 468 #log# opts = %s
469 469 #log# args = %s
470 470 #log# It is safe to make manual edits below here.
471 471 #log#-----------------------------------------------------------------------
472 472 """
473 473 # for pushd/popd management
474 474 try:
475 475 self.home_dir = get_home_dir()
476 476 except HomeDirError,msg:
477 477 fatal(msg)
478 478
479 479 self.dir_stack = []
480 480
481 481 # Functions to call the underlying shell.
482 482
483 483 # The first is similar to os.system, but it doesn't return a value,
484 484 # and it allows interpolation of variables in the user's namespace.
485 485 self.system = lambda cmd: \
486 486 self.hooks.shell_hook(self.var_expand(cmd,depth=2))
487 487
488 488 # These are for getoutput and getoutputerror:
489 489 self.getoutput = lambda cmd: \
490 490 getoutput(self.var_expand(cmd,depth=2),
491 491 header=self.rc.system_header,
492 492 verbose=self.rc.system_verbose)
493 493
494 494 self.getoutputerror = lambda cmd: \
495 495 getoutputerror(self.var_expand(cmd,depth=2),
496 496 header=self.rc.system_header,
497 497 verbose=self.rc.system_verbose)
498 498
499 499
500 500 # keep track of where we started running (mainly for crash post-mortem)
501 501 self.starting_dir = os.getcwd()
502 502
503 503 # Various switches which can be set
504 504 self.CACHELENGTH = 5000 # this is cheap, it's just text
505 505 self.BANNER = "Python %(version)s on %(platform)s\n" % sys.__dict__
506 506 self.banner2 = banner2
507 507
508 508 # TraceBack handlers:
509 509
510 510 # Syntax error handler.
511 511 self.SyntaxTB = SyntaxTB(color_scheme='NoColor')
512 512
513 513 # The interactive one is initialized with an offset, meaning we always
514 514 # want to remove the topmost item in the traceback, which is our own
515 515 # internal code. Valid modes: ['Plain','Context','Verbose']
516 516 self.InteractiveTB = ultraTB.AutoFormattedTB(mode = 'Plain',
517 517 color_scheme='NoColor',
518 518 tb_offset = 1)
519 519
520 520 # IPython itself shouldn't crash. This will produce a detailed
521 521 # post-mortem if it does. But we only install the crash handler for
522 522 # non-threaded shells, the threaded ones use a normal verbose reporter
523 523 # and lose the crash handler. This is because exceptions in the main
524 524 # thread (such as in GUI code) propagate directly to sys.excepthook,
525 525 # and there's no point in printing crash dumps for every user exception.
526 526 if self.isthreaded:
527 527 ipCrashHandler = ultraTB.FormattedTB()
528 528 else:
529 529 from IPython import CrashHandler
530 530 ipCrashHandler = CrashHandler.IPythonCrashHandler(self)
531 531 self.set_crash_handler(ipCrashHandler)
532 532
533 533 # and add any custom exception handlers the user may have specified
534 534 self.set_custom_exc(*custom_exceptions)
535 535
536 536 # indentation management
537 537 self.autoindent = False
538 538 self.indent_current_nsp = 0
539 539
540 540 # Make some aliases automatically
541 541 # Prepare list of shell aliases to auto-define
542 542 if os.name == 'posix':
543 543 auto_alias = ('mkdir mkdir', 'rmdir rmdir',
544 544 'mv mv -i','rm rm -i','cp cp -i',
545 545 'cat cat','less less','clear clear',
546 546 # a better ls
547 547 'ls ls -F',
548 548 # long ls
549 549 'll ls -lF')
550 550 # Extra ls aliases with color, which need special treatment on BSD
551 551 # variants
552 552 ls_extra = ( # color ls
553 553 'lc ls -F -o --color',
554 554 # ls normal files only
555 555 'lf ls -F -o --color %l | grep ^-',
556 556 # ls symbolic links
557 557 'lk ls -F -o --color %l | grep ^l',
558 558 # directories or links to directories,
559 559 'ldir ls -F -o --color %l | grep /$',
560 560 # things which are executable
561 561 'lx ls -F -o --color %l | grep ^-..x',
562 562 )
563 563 # The BSDs don't ship GNU ls, so they don't understand the
564 564 # --color switch out of the box
565 565 if 'bsd' in sys.platform:
566 566 ls_extra = ( # ls normal files only
567 567 'lf ls -lF | grep ^-',
568 568 # ls symbolic links
569 569 'lk ls -lF | grep ^l',
570 570 # directories or links to directories,
571 571 'ldir ls -lF | grep /$',
572 572 # things which are executable
573 573 'lx ls -lF | grep ^-..x',
574 574 )
575 575 auto_alias = auto_alias + ls_extra
576 576 elif os.name in ['nt','dos']:
577 577 auto_alias = ('ls dir /on',
578 578 'ddir dir /ad /on', 'ldir dir /ad /on',
579 579 'mkdir mkdir','rmdir rmdir','echo echo',
580 580 'ren ren','cls cls','copy copy')
581 581 else:
582 582 auto_alias = ()
583 583 self.auto_alias = [s.split(None,1) for s in auto_alias]
584 584
585 585 # Produce a public API instance
586 586 self.api = IPython.ipapi.IPApi(self)
587 587
588 588 # Initialize all user-visible namespaces
589 589 self.init_namespaces()
590 590
591 591 # Call the actual (public) initializer
592 592 self.init_auto_alias()
593 593
594 594 # track which builtins we add, so we can clean up later
595 595 self.builtins_added = {}
596 596 # This method will add the necessary builtins for operation, but
597 597 # tracking what it did via the builtins_added dict.
598 598
599 599 #TODO: remove this, redundant
600 600 self.add_builtins()
601 601 # end __init__
602 602
603 603 def var_expand(self,cmd,depth=0):
604 604 """Expand python variables in a string.
605 605
606 606 The depth argument indicates how many frames above the caller should
607 607 be walked to look for the local namespace where to expand variables.
608 608
609 609 The global namespace for expansion is always the user's interactive
610 610 namespace.
611 611 """
612 612
613 613 return str(ItplNS(cmd,
614 614 self.user_ns, # globals
615 615 # Skip our own frame in searching for locals:
616 616 sys._getframe(depth+1).f_locals # locals
617 617 ))
618 618
619 619 def pre_config_initialization(self):
620 620 """Pre-configuration init method
621 621
622 622 This is called before the configuration files are processed to
623 623 prepare the services the config files might need.
624 624
625 625 self.rc already has reasonable default values at this point.
626 626 """
627 627 rc = self.rc
628 628 try:
629 629 self.db = pickleshare.PickleShareDB(rc.ipythondir + "/db")
630 630 except exceptions.UnicodeDecodeError:
631 631 print "Your ipythondir can't be decoded to unicode!"
632 632 print "Please set HOME environment variable to something that"
633 633 print r"only has ASCII characters, e.g. c:\home"
634 634 print "Now it is",rc.ipythondir
635 635 sys.exit()
636 636 self.shadowhist = IPython.history.ShadowHist(self.db)
637 637
638 638 def post_config_initialization(self):
639 639 """Post configuration init method
640 640
641 641 This is called after the configuration files have been processed to
642 642 'finalize' the initialization."""
643 643
644 644 rc = self.rc
645 645
646 646 # Object inspector
647 647 self.inspector = OInspect.Inspector(OInspect.InspectColors,
648 648 PyColorize.ANSICodeColors,
649 649 'NoColor',
650 650 rc.object_info_string_level)
651 651
652 652 self.rl_next_input = None
653 653 self.rl_do_indent = False
654 654 # Load readline proper
655 655 if rc.readline:
656 656 self.init_readline()
657 657
658 658 # local shortcut, this is used a LOT
659 659 self.log = self.logger.log
660 660
661 661 # Initialize cache, set in/out prompts and printing system
662 662 self.outputcache = CachedOutput(self,
663 663 rc.cache_size,
664 664 rc.pprint,
665 665 input_sep = rc.separate_in,
666 666 output_sep = rc.separate_out,
667 667 output_sep2 = rc.separate_out2,
668 668 ps1 = rc.prompt_in1,
669 669 ps2 = rc.prompt_in2,
670 670 ps_out = rc.prompt_out,
671 671 pad_left = rc.prompts_pad_left)
672 672
673 673 # user may have over-ridden the default print hook:
674 674 try:
675 675 self.outputcache.__class__.display = self.hooks.display
676 676 except AttributeError:
677 677 pass
678 678
679 679 # I don't like assigning globally to sys, because it means when
680 680 # embedding instances, each embedded instance overrides the previous
681 681 # choice. But sys.displayhook seems to be called internally by exec,
682 682 # so I don't see a way around it. We first save the original and then
683 683 # overwrite it.
684 684 self.sys_displayhook = sys.displayhook
685 685 sys.displayhook = self.outputcache
686 686
687 687 # Do a proper resetting of doctest, including the necessary displayhook
688 688 # monkeypatching
689 689 try:
690 690 doctest_reload()
691 691 except ImportError:
692 692 warn("doctest module does not exist.")
693 693
694 694 # Set user colors (don't do it in the constructor above so that it
695 695 # doesn't crash if colors option is invalid)
696 696 self.magic_colors(rc.colors)
697 697
698 698 # Set calling of pdb on exceptions
699 699 self.call_pdb = rc.pdb
700 700
701 701 # Load user aliases
702 702 for alias in rc.alias:
703 703 self.magic_alias(alias)
704 704
705 705 self.hooks.late_startup_hook()
706 706
707 707 for cmd in self.rc.autoexec:
708 708 #print "autoexec>",cmd #dbg
709 709 self.api.runlines(cmd)
710 710
711 711 batchrun = False
712 712 for batchfile in [path(arg) for arg in self.rc.args
713 713 if arg.lower().endswith('.ipy')]:
714 714 if not batchfile.isfile():
715 715 print "No such batch file:", batchfile
716 716 continue
717 717 self.api.runlines(batchfile.text())
718 718 batchrun = True
719 719 # without -i option, exit after running the batch file
720 720 if batchrun and not self.rc.interact:
721 721 self.ask_exit()
722 722
723 723 def init_namespaces(self):
724 724 """Initialize all user-visible namespaces to their minimum defaults.
725 725
726 726 Certain history lists are also initialized here, as they effectively
727 727 act as user namespaces.
728 728
729 729 Note
730 730 ----
731 731 All data structures here are only filled in, they are NOT reset by this
732 732 method. If they were not empty before, data will simply be added to
733 733 therm.
734 734 """
735 735 # The user namespace MUST have a pointer to the shell itself.
736 736 self.user_ns[self.name] = self
737 737
738 738 # Store the public api instance
739 739 self.user_ns['_ip'] = self.api
740 740
741 741 # make global variables for user access to the histories
742 742 self.user_ns['_ih'] = self.input_hist
743 743 self.user_ns['_oh'] = self.output_hist
744 744 self.user_ns['_dh'] = self.dir_hist
745 745
746 746 # user aliases to input and output histories
747 747 self.user_ns['In'] = self.input_hist
748 748 self.user_ns['Out'] = self.output_hist
749 749
750 750 self.user_ns['_sh'] = IPython.shadowns
751 751
752 752 # Fill the history zero entry, user counter starts at 1
753 753 self.input_hist.append('\n')
754 754 self.input_hist_raw.append('\n')
755 755
756 756 def add_builtins(self):
757 757 """Store ipython references into the builtin namespace.
758 758
759 759 Some parts of ipython operate via builtins injected here, which hold a
760 760 reference to IPython itself."""
761 761
762 762 # TODO: deprecate all of these, they are unsafe
763 763 builtins_new = dict(__IPYTHON__ = self,
764 764 ip_set_hook = self.set_hook,
765 765 jobs = self.jobs,
766 766 ipmagic = wrap_deprecated(self.ipmagic,'_ip.magic()'),
767 767 ipalias = wrap_deprecated(self.ipalias),
768 768 ipsystem = wrap_deprecated(self.ipsystem,'_ip.system()'),
769 769 #_ip = self.api
770 770 )
771 771 for biname,bival in builtins_new.items():
772 772 try:
773 773 # store the orignal value so we can restore it
774 774 self.builtins_added[biname] = __builtin__.__dict__[biname]
775 775 except KeyError:
776 776 # or mark that it wasn't defined, and we'll just delete it at
777 777 # cleanup
778 778 self.builtins_added[biname] = Undefined
779 779 __builtin__.__dict__[biname] = bival
780 780
781 781 # Keep in the builtins a flag for when IPython is active. We set it
782 782 # with setdefault so that multiple nested IPythons don't clobber one
783 783 # another. Each will increase its value by one upon being activated,
784 784 # which also gives us a way to determine the nesting level.
785 785 __builtin__.__dict__.setdefault('__IPYTHON__active',0)
786 786
787 787 def clean_builtins(self):
788 788 """Remove any builtins which might have been added by add_builtins, or
789 789 restore overwritten ones to their previous values."""
790 790 for biname,bival in self.builtins_added.items():
791 791 if bival is Undefined:
792 792 del __builtin__.__dict__[biname]
793 793 else:
794 794 __builtin__.__dict__[biname] = bival
795 795 self.builtins_added.clear()
796 796
797 797 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
798 798 """set_hook(name,hook) -> sets an internal IPython hook.
799 799
800 800 IPython exposes some of its internal API as user-modifiable hooks. By
801 801 adding your function to one of these hooks, you can modify IPython's
802 802 behavior to call at runtime your own routines."""
803 803
804 804 # At some point in the future, this should validate the hook before it
805 805 # accepts it. Probably at least check that the hook takes the number
806 806 # of args it's supposed to.
807 807
808 808 f = new.instancemethod(hook,self,self.__class__)
809 809
810 810 # check if the hook is for strdispatcher first
811 811 if str_key is not None:
812 812 sdp = self.strdispatchers.get(name, StrDispatch())
813 813 sdp.add_s(str_key, f, priority )
814 814 self.strdispatchers[name] = sdp
815 815 return
816 816 if re_key is not None:
817 817 sdp = self.strdispatchers.get(name, StrDispatch())
818 818 sdp.add_re(re.compile(re_key), f, priority )
819 819 self.strdispatchers[name] = sdp
820 820 return
821 821
822 822 dp = getattr(self.hooks, name, None)
823 823 if name not in IPython.hooks.__all__:
824 824 print "Warning! Hook '%s' is not one of %s" % (name, IPython.hooks.__all__ )
825 825 if not dp:
826 826 dp = IPython.hooks.CommandChainDispatcher()
827 827
828 828 try:
829 829 dp.add(f,priority)
830 830 except AttributeError:
831 831 # it was not commandchain, plain old func - replace
832 832 dp = f
833 833
834 834 setattr(self.hooks,name, dp)
835 835
836 836
837 837 #setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__))
838 838
839 839 def set_crash_handler(self,crashHandler):
840 840 """Set the IPython crash handler.
841 841
842 842 This must be a callable with a signature suitable for use as
843 843 sys.excepthook."""
844 844
845 845 # Install the given crash handler as the Python exception hook
846 846 sys.excepthook = crashHandler
847 847
848 848 # The instance will store a pointer to this, so that runtime code
849 849 # (such as magics) can access it. This is because during the
850 850 # read-eval loop, it gets temporarily overwritten (to deal with GUI
851 851 # frameworks).
852 852 self.sys_excepthook = sys.excepthook
853 853
854 854
855 855 def set_custom_exc(self,exc_tuple,handler):
856 856 """set_custom_exc(exc_tuple,handler)
857 857
858 858 Set a custom exception handler, which will be called if any of the
859 859 exceptions in exc_tuple occur in the mainloop (specifically, in the
860 860 runcode() method.
861 861
862 862 Inputs:
863 863
864 864 - exc_tuple: a *tuple* of valid exceptions to call the defined
865 865 handler for. It is very important that you use a tuple, and NOT A
866 866 LIST here, because of the way Python's except statement works. If
867 867 you only want to trap a single exception, use a singleton tuple:
868 868
869 869 exc_tuple == (MyCustomException,)
870 870
871 871 - handler: this must be defined as a function with the following
872 872 basic interface: def my_handler(self,etype,value,tb).
873 873
874 874 This will be made into an instance method (via new.instancemethod)
875 875 of IPython itself, and it will be called if any of the exceptions
876 876 listed in the exc_tuple are caught. If the handler is None, an
877 877 internal basic one is used, which just prints basic info.
878 878
879 879 WARNING: by putting in your own exception handler into IPython's main
880 880 execution loop, you run a very good chance of nasty crashes. This
881 881 facility should only be used if you really know what you are doing."""
882 882
883 883 assert type(exc_tuple)==type(()) , \
884 884 "The custom exceptions must be given AS A TUPLE."
885 885
886 886 def dummy_handler(self,etype,value,tb):
887 887 print '*** Simple custom exception handler ***'
888 888 print 'Exception type :',etype
889 889 print 'Exception value:',value
890 890 print 'Traceback :',tb
891 891 print 'Source code :','\n'.join(self.buffer)
892 892
893 893 if handler is None: handler = dummy_handler
894 894
895 895 self.CustomTB = new.instancemethod(handler,self,self.__class__)
896 896 self.custom_exceptions = exc_tuple
897 897
898 898 def set_custom_completer(self,completer,pos=0):
899 899 """set_custom_completer(completer,pos=0)
900 900
901 901 Adds a new custom completer function.
902 902
903 903 The position argument (defaults to 0) is the index in the completers
904 904 list where you want the completer to be inserted."""
905 905
906 906 newcomp = new.instancemethod(completer,self.Completer,
907 907 self.Completer.__class__)
908 908 self.Completer.matchers.insert(pos,newcomp)
909 909
910 910 def set_completer(self):
911 911 """reset readline's completer to be our own."""
912 912 self.readline.set_completer(self.Completer.complete)
913 913
914 914 def _get_call_pdb(self):
915 915 return self._call_pdb
916 916
917 917 def _set_call_pdb(self,val):
918 918
919 919 if val not in (0,1,False,True):
920 920 raise ValueError,'new call_pdb value must be boolean'
921 921
922 922 # store value in instance
923 923 self._call_pdb = val
924 924
925 925 # notify the actual exception handlers
926 926 self.InteractiveTB.call_pdb = val
927 927 if self.isthreaded:
928 928 try:
929 929 self.sys_excepthook.call_pdb = val
930 930 except:
931 931 warn('Failed to activate pdb for threaded exception handler')
932 932
933 933 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
934 934 'Control auto-activation of pdb at exceptions')
935 935
936 936 # These special functions get installed in the builtin namespace, to
937 937 # provide programmatic (pure python) access to magics, aliases and system
938 938 # calls. This is important for logging, user scripting, and more.
939 939
940 940 # We are basically exposing, via normal python functions, the three
941 941 # mechanisms in which ipython offers special call modes (magics for
942 942 # internal control, aliases for direct system access via pre-selected
943 943 # names, and !cmd for calling arbitrary system commands).
944 944
945 945 def ipmagic(self,arg_s):
946 946 """Call a magic function by name.
947 947
948 948 Input: a string containing the name of the magic function to call and any
949 949 additional arguments to be passed to the magic.
950 950
951 951 ipmagic('name -opt foo bar') is equivalent to typing at the ipython
952 952 prompt:
953 953
954 954 In[1]: %name -opt foo bar
955 955
956 956 To call a magic without arguments, simply use ipmagic('name').
957 957
958 958 This provides a proper Python function to call IPython's magics in any
959 959 valid Python code you can type at the interpreter, including loops and
960 960 compound statements. It is added by IPython to the Python builtin
961 961 namespace upon initialization."""
962 962
963 963 args = arg_s.split(' ',1)
964 964 magic_name = args[0]
965 965 magic_name = magic_name.lstrip(self.ESC_MAGIC)
966 966
967 967 try:
968 968 magic_args = args[1]
969 969 except IndexError:
970 970 magic_args = ''
971 971 fn = getattr(self,'magic_'+magic_name,None)
972 972 if fn is None:
973 973 error("Magic function `%s` not found." % magic_name)
974 974 else:
975 975 magic_args = self.var_expand(magic_args,1)
976 976 return fn(magic_args)
977 977
978 978 def ipalias(self,arg_s):
979 979 """Call an alias by name.
980 980
981 981 Input: a string containing the name of the alias to call and any
982 982 additional arguments to be passed to the magic.
983 983
984 984 ipalias('name -opt foo bar') is equivalent to typing at the ipython
985 985 prompt:
986 986
987 987 In[1]: name -opt foo bar
988 988
989 989 To call an alias without arguments, simply use ipalias('name').
990 990
991 991 This provides a proper Python function to call IPython's aliases in any
992 992 valid Python code you can type at the interpreter, including loops and
993 993 compound statements. It is added by IPython to the Python builtin
994 994 namespace upon initialization."""
995 995
996 996 args = arg_s.split(' ',1)
997 997 alias_name = args[0]
998 998 try:
999 999 alias_args = args[1]
1000 1000 except IndexError:
1001 1001 alias_args = ''
1002 1002 if alias_name in self.alias_table:
1003 1003 self.call_alias(alias_name,alias_args)
1004 1004 else:
1005 1005 error("Alias `%s` not found." % alias_name)
1006 1006
1007 1007 def ipsystem(self,arg_s):
1008 1008 """Make a system call, using IPython."""
1009 1009
1010 1010 self.system(arg_s)
1011 1011
1012 1012 def complete(self,text):
1013 1013 """Return a sorted list of all possible completions on text.
1014 1014
1015 1015 Inputs:
1016 1016
1017 1017 - text: a string of text to be completed on.
1018 1018
1019 1019 This is a wrapper around the completion mechanism, similar to what
1020 1020 readline does at the command line when the TAB key is hit. By
1021 1021 exposing it as a method, it can be used by other non-readline
1022 1022 environments (such as GUIs) for text completion.
1023 1023
1024 1024 Simple usage example:
1025 1025
1026 1026 In [7]: x = 'hello'
1027 1027
1028 1028 In [8]: x
1029 1029 Out[8]: 'hello'
1030 1030
1031 1031 In [9]: print x
1032 1032 hello
1033 1033
1034 1034 In [10]: _ip.IP.complete('x.l')
1035 1035 Out[10]: ['x.ljust', 'x.lower', 'x.lstrip']
1036 1036 """
1037 1037
1038 1038 complete = self.Completer.complete
1039 1039 state = 0
1040 1040 # use a dict so we get unique keys, since ipyhton's multiple
1041 1041 # completers can return duplicates. When we make 2.4 a requirement,
1042 1042 # start using sets instead, which are faster.
1043 1043 comps = {}
1044 1044 while True:
1045 1045 newcomp = complete(text,state,line_buffer=text)
1046 1046 if newcomp is None:
1047 1047 break
1048 1048 comps[newcomp] = 1
1049 1049 state += 1
1050 1050 outcomps = comps.keys()
1051 1051 outcomps.sort()
1052 1052 #print "T:",text,"OC:",outcomps # dbg
1053 1053 #print "vars:",self.user_ns.keys()
1054 1054 return outcomps
1055 1055
1056 1056 def set_completer_frame(self, frame=None):
1057 1057 if frame:
1058 1058 self.Completer.namespace = frame.f_locals
1059 1059 self.Completer.global_namespace = frame.f_globals
1060 1060 else:
1061 1061 self.Completer.namespace = self.user_ns
1062 1062 self.Completer.global_namespace = self.user_global_ns
1063 1063
1064 1064 def init_auto_alias(self):
1065 1065 """Define some aliases automatically.
1066 1066
1067 1067 These are ALL parameter-less aliases"""
1068 1068
1069 1069 for alias,cmd in self.auto_alias:
1070 1070 self.getapi().defalias(alias,cmd)
1071 1071
1072 1072
1073 1073 def alias_table_validate(self,verbose=0):
1074 1074 """Update information about the alias table.
1075 1075
1076 1076 In particular, make sure no Python keywords/builtins are in it."""
1077 1077
1078 1078 no_alias = self.no_alias
1079 1079 for k in self.alias_table.keys():
1080 1080 if k in no_alias:
1081 1081 del self.alias_table[k]
1082 1082 if verbose:
1083 1083 print ("Deleting alias <%s>, it's a Python "
1084 1084 "keyword or builtin." % k)
1085 1085
1086 1086 def set_autoindent(self,value=None):
1087 1087 """Set the autoindent flag, checking for readline support.
1088 1088
1089 1089 If called with no arguments, it acts as a toggle."""
1090 1090
1091 1091 if not self.has_readline:
1092 1092 if os.name == 'posix':
1093 1093 warn("The auto-indent feature requires the readline library")
1094 1094 self.autoindent = 0
1095 1095 return
1096 1096 if value is None:
1097 1097 self.autoindent = not self.autoindent
1098 1098 else:
1099 1099 self.autoindent = value
1100 1100
1101 1101 def rc_set_toggle(self,rc_field,value=None):
1102 1102 """Set or toggle a field in IPython's rc config. structure.
1103 1103
1104 1104 If called with no arguments, it acts as a toggle.
1105 1105
1106 1106 If called with a non-existent field, the resulting AttributeError
1107 1107 exception will propagate out."""
1108 1108
1109 1109 rc_val = getattr(self.rc,rc_field)
1110 1110 if value is None:
1111 1111 value = not rc_val
1112 1112 setattr(self.rc,rc_field,value)
1113 1113
1114 1114 def user_setup(self,ipythondir,rc_suffix,mode='install'):
1115 1115 """Install the user configuration directory.
1116 1116
1117 1117 Can be called when running for the first time or to upgrade the user's
1118 1118 .ipython/ directory with the mode parameter. Valid modes are 'install'
1119 1119 and 'upgrade'."""
1120 1120
1121 1121 def wait():
1122 1122 try:
1123 1123 raw_input("Please press <RETURN> to start IPython.")
1124 1124 except EOFError:
1125 1125 print >> Term.cout
1126 1126 print '*'*70
1127 1127
1128 1128 cwd = os.getcwd() # remember where we started
1129 1129 glb = glob.glob
1130 1130 print '*'*70
1131 1131 if mode == 'install':
1132 1132 print \
1133 1133 """Welcome to IPython. I will try to create a personal configuration directory
1134 1134 where you can customize many aspects of IPython's functionality in:\n"""
1135 1135 else:
1136 1136 print 'I am going to upgrade your configuration in:'
1137 1137
1138 1138 print ipythondir
1139 1139
1140 1140 rcdirend = os.path.join('IPython','UserConfig')
1141 1141 cfg = lambda d: os.path.join(d,rcdirend)
1142 1142 try:
1143 1143 rcdir = filter(os.path.isdir,map(cfg,sys.path))[0]
1144 1144 print "Initializing from configuration",rcdir
1145 1145 except IndexError:
1146 1146 warning = """
1147 1147 Installation error. IPython's directory was not found.
1148 1148
1149 1149 Check the following:
1150 1150
1151 1151 The ipython/IPython directory should be in a directory belonging to your
1152 1152 PYTHONPATH environment variable (that is, it should be in a directory
1153 1153 belonging to sys.path). You can copy it explicitly there or just link to it.
1154 1154
1155 1155 IPython will create a minimal default configuration for you.
1156 1156
1157 1157 """
1158 1158 warn(warning)
1159 1159 wait()
1160 1160
1161 1161 if sys.platform =='win32':
1162 1162 inif = 'ipythonrc.ini'
1163 1163 else:
1164 1164 inif = 'ipythonrc'
1165 1165 minimal_setup = {'ipy_user_conf.py' : 'import ipy_defaults',
1166 1166 inif : '# intentionally left blank' }
1167 1167 os.makedirs(ipythondir, mode = 0777)
1168 1168 for f, cont in minimal_setup.items():
1169 1169 open(ipythondir + '/' + f,'w').write(cont)
1170 1170
1171 1171 return
1172 1172
1173 1173 if mode == 'install':
1174 1174 try:
1175 1175 shutil.copytree(rcdir,ipythondir)
1176 1176 os.chdir(ipythondir)
1177 1177 rc_files = glb("ipythonrc*")
1178 1178 for rc_file in rc_files:
1179 1179 os.rename(rc_file,rc_file+rc_suffix)
1180 1180 except:
1181 1181 warning = """
1182 1182
1183 1183 There was a problem with the installation:
1184 1184 %s
1185 1185 Try to correct it or contact the developers if you think it's a bug.
1186 1186 IPython will proceed with builtin defaults.""" % sys.exc_info()[1]
1187 1187 warn(warning)
1188 1188 wait()
1189 1189 return
1190 1190
1191 1191 elif mode == 'upgrade':
1192 1192 try:
1193 1193 os.chdir(ipythondir)
1194 1194 except:
1195 1195 print """
1196 1196 Can not upgrade: changing to directory %s failed. Details:
1197 1197 %s
1198 1198 """ % (ipythondir,sys.exc_info()[1])
1199 1199 wait()
1200 1200 return
1201 1201 else:
1202 1202 sources = glb(os.path.join(rcdir,'[A-Za-z]*'))
1203 1203 for new_full_path in sources:
1204 1204 new_filename = os.path.basename(new_full_path)
1205 1205 if new_filename.startswith('ipythonrc'):
1206 1206 new_filename = new_filename + rc_suffix
1207 1207 # The config directory should only contain files, skip any
1208 1208 # directories which may be there (like CVS)
1209 1209 if os.path.isdir(new_full_path):
1210 1210 continue
1211 1211 if os.path.exists(new_filename):
1212 1212 old_file = new_filename+'.old'
1213 1213 if os.path.exists(old_file):
1214 1214 os.remove(old_file)
1215 1215 os.rename(new_filename,old_file)
1216 1216 shutil.copy(new_full_path,new_filename)
1217 1217 else:
1218 1218 raise ValueError,'unrecognized mode for install:',`mode`
1219 1219
1220 1220 # Fix line-endings to those native to each platform in the config
1221 1221 # directory.
1222 1222 try:
1223 1223 os.chdir(ipythondir)
1224 1224 except:
1225 1225 print """
1226 1226 Problem: changing to directory %s failed.
1227 1227 Details:
1228 1228 %s
1229 1229
1230 1230 Some configuration files may have incorrect line endings. This should not
1231 1231 cause any problems during execution. """ % (ipythondir,sys.exc_info()[1])
1232 1232 wait()
1233 1233 else:
1234 1234 for fname in glb('ipythonrc*'):
1235 1235 try:
1236 1236 native_line_ends(fname,backup=0)
1237 1237 except IOError:
1238 1238 pass
1239 1239
1240 1240 if mode == 'install':
1241 1241 print """
1242 1242 Successful installation!
1243 1243
1244 1244 Please read the sections 'Initial Configuration' and 'Quick Tips' in the
1245 1245 IPython manual (there are both HTML and PDF versions supplied with the
1246 1246 distribution) to make sure that your system environment is properly configured
1247 1247 to take advantage of IPython's features.
1248 1248
1249 1249 Important note: the configuration system has changed! The old system is
1250 1250 still in place, but its setting may be partly overridden by the settings in
1251 1251 "~/.ipython/ipy_user_conf.py" config file. Please take a look at the file
1252 1252 if some of the new settings bother you.
1253 1253
1254 1254 """
1255 1255 else:
1256 1256 print """
1257 1257 Successful upgrade!
1258 1258
1259 1259 All files in your directory:
1260 1260 %(ipythondir)s
1261 1261 which would have been overwritten by the upgrade were backed up with a .old
1262 1262 extension. If you had made particular customizations in those files you may
1263 1263 want to merge them back into the new files.""" % locals()
1264 1264 wait()
1265 1265 os.chdir(cwd)
1266 1266 # end user_setup()
1267 1267
1268 1268 def atexit_operations(self):
1269 1269 """This will be executed at the time of exit.
1270 1270
1271 1271 Saving of persistent data should be performed here. """
1272 1272
1273 1273 #print '*** IPython exit cleanup ***' # dbg
1274 1274 # input history
1275 1275 self.savehist()
1276 1276
1277 1277 # Cleanup all tempfiles left around
1278 1278 for tfile in self.tempfiles:
1279 1279 try:
1280 1280 os.unlink(tfile)
1281 1281 except OSError:
1282 1282 pass
1283 1283
1284 1284 # Clear all user namespaces to release all references cleanly.
1285 1285 self.reset()
1286 1286
1287 1287 # Run user hooks
1288 1288 self.hooks.shutdown_hook()
1289 1289
1290 1290 def reset(self):
1291 1291 """Clear all internal namespaces.
1292 1292
1293 1293 Note that this is much more aggressive than %reset, since it clears
1294 1294 fully all namespaces, as well as all input/output lists.
1295 1295 """
1296 1296 for ns in self.ns_refs_table:
1297 1297 ns.clear()
1298 1298
1299 1299 # Clear input and output histories
1300 1300 self.input_hist[:] = []
1301 1301 self.input_hist_raw[:] = []
1302 1302 self.output_hist.clear()
1303 1303 # Restore the user namespaces to minimal usability
1304 1304 self.init_namespaces()
1305 1305
1306 1306 def savehist(self):
1307 1307 """Save input history to a file (via readline library)."""
1308 1308
1309 1309 if not self.has_readline:
1310 1310 return
1311 1311
1312 1312 try:
1313 1313 self.readline.write_history_file(self.histfile)
1314 1314 except:
1315 1315 print 'Unable to save IPython command history to file: ' + \
1316 1316 `self.histfile`
1317 1317
1318 1318 def reloadhist(self):
1319 1319 """Reload the input history from disk file."""
1320 1320
1321 1321 if self.has_readline:
1322 1322 try:
1323 1323 self.readline.clear_history()
1324 1324 self.readline.read_history_file(self.shell.histfile)
1325 1325 except AttributeError:
1326 1326 pass
1327 1327
1328 1328
1329 1329 def history_saving_wrapper(self, func):
1330 1330 """ Wrap func for readline history saving
1331 1331
1332 1332 Convert func into callable that saves & restores
1333 1333 history around the call """
1334 1334
1335 1335 if not self.has_readline:
1336 1336 return func
1337 1337
1338 1338 def wrapper():
1339 1339 self.savehist()
1340 1340 try:
1341 1341 func()
1342 1342 finally:
1343 1343 readline.read_history_file(self.histfile)
1344 1344 return wrapper
1345 1345
1346 1346 def pre_readline(self):
1347 1347 """readline hook to be used at the start of each line.
1348 1348
1349 1349 Currently it handles auto-indent only."""
1350 1350
1351 1351 #debugx('self.indent_current_nsp','pre_readline:')
1352 1352
1353 1353 if self.rl_do_indent:
1354 1354 self.readline.insert_text(self.indent_current_str())
1355 1355 if self.rl_next_input is not None:
1356 1356 self.readline.insert_text(self.rl_next_input)
1357 1357 self.rl_next_input = None
1358 1358
1359 1359 def init_readline(self):
1360 1360 """Command history completion/saving/reloading."""
1361 1361
1362 1362
1363 1363 import IPython.rlineimpl as readline
1364 1364
1365 1365 if not readline.have_readline:
1366 1366 self.has_readline = 0
1367 1367 self.readline = None
1368 1368 # no point in bugging windows users with this every time:
1369 1369 warn('Readline services not available on this platform.')
1370 1370 else:
1371 1371 sys.modules['readline'] = readline
1372 1372 import atexit
1373 1373 from IPython.completer import IPCompleter
1374 1374 self.Completer = IPCompleter(self,
1375 1375 self.user_ns,
1376 1376 self.user_global_ns,
1377 1377 self.rc.readline_omit__names,
1378 1378 self.alias_table)
1379 1379 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1380 1380 self.strdispatchers['complete_command'] = sdisp
1381 1381 self.Completer.custom_completers = sdisp
1382 1382 # Platform-specific configuration
1383 1383 if os.name == 'nt':
1384 1384 self.readline_startup_hook = readline.set_pre_input_hook
1385 1385 else:
1386 1386 self.readline_startup_hook = readline.set_startup_hook
1387 1387
1388 1388 # Load user's initrc file (readline config)
1389 1389 # Or if libedit is used, load editrc.
1390 1390 inputrc_name = os.environ.get('INPUTRC')
1391 1391 if inputrc_name is None:
1392 1392 home_dir = get_home_dir()
1393 1393 if home_dir is not None:
1394 1394 inputrc_name = '.inputrc'
1395 1395 if readline.uses_libedit:
1396 1396 inputrc_name = '.editrc'
1397 1397 inputrc_name = os.path.join(home_dir, inputrc_name)
1398 1398 if os.path.isfile(inputrc_name):
1399 1399 try:
1400 1400 readline.read_init_file(inputrc_name)
1401 1401 except:
1402 1402 warn('Problems reading readline initialization file <%s>'
1403 1403 % inputrc_name)
1404 1404
1405 1405 self.has_readline = 1
1406 1406 self.readline = readline
1407 1407 # save this in sys so embedded copies can restore it properly
1408 1408 sys.ipcompleter = self.Completer.complete
1409 1409 self.set_completer()
1410 1410
1411 1411 # Configure readline according to user's prefs
1412 1412 # This is only done if GNU readline is being used. If libedit
1413 1413 # is being used (as on Leopard) the readline config is
1414 1414 # not run as the syntax for libedit is different.
1415 1415 if not readline.uses_libedit:
1416 1416 for rlcommand in self.rc.readline_parse_and_bind:
1417 #print "loading rl:",rlcommand # dbg
1417 1418 readline.parse_and_bind(rlcommand)
1418 1419
1419 1420 # remove some chars from the delimiters list
1420 1421 delims = readline.get_completer_delims()
1421 1422 delims = delims.translate(string._idmap,
1422 1423 self.rc.readline_remove_delims)
1423 1424 readline.set_completer_delims(delims)
1424 1425 # otherwise we end up with a monster history after a while:
1425 1426 readline.set_history_length(1000)
1426 1427 try:
1427 1428 #print '*** Reading readline history' # dbg
1428 1429 readline.read_history_file(self.histfile)
1429 1430 except IOError:
1430 1431 pass # It doesn't exist yet.
1431 1432
1432 1433 atexit.register(self.atexit_operations)
1433 1434 del atexit
1434 1435
1435 1436 # Configure auto-indent for all platforms
1436 1437 self.set_autoindent(self.rc.autoindent)
1437 1438
1438 1439 def ask_yes_no(self,prompt,default=True):
1439 1440 if self.rc.quiet:
1440 1441 return True
1441 1442 return ask_yes_no(prompt,default)
1442 1443
1443 1444 def cache_main_mod(self,mod):
1444 1445 """Cache a main module.
1445 1446
1446 1447 When scripts are executed via %run, we must keep a reference to their
1447 1448 __main__ module (a FakeModule instance) around so that Python doesn't
1448 1449 clear it, rendering objects defined therein useless.
1449 1450
1450 1451 This method keeps said reference in a private dict, keyed by the
1451 1452 absolute path of the module object (which corresponds to the script
1452 1453 path). This way, for multiple executions of the same script we only
1453 1454 keep one copy of __main__ (the last one), thus preventing memory leaks
1454 1455 from old references while allowing the objects from the last execution
1455 1456 to be accessible.
1456 1457
1457 1458 Parameters
1458 1459 ----------
1459 1460 mod : a module object
1460 1461
1461 1462 Examples
1462 1463 --------
1463 1464
1464 1465 In [10]: import IPython
1465 1466
1466 1467 In [11]: _ip.IP.cache_main_mod(IPython)
1467 1468
1468 1469 In [12]: IPython.__file__ in _ip.IP._user_main_modules
1469 1470 Out[12]: True
1470 1471 """
1471 1472 self._user_main_modules[os.path.abspath(mod.__file__) ] = mod
1472 1473
1473 1474 def clear_main_mod_cache(self):
1474 1475 """Clear the cache of main modules.
1475 1476
1476 1477 Mainly for use by utilities like %reset.
1477 1478
1478 1479 Examples
1479 1480 --------
1480 1481
1481 1482 In [15]: import IPython
1482 1483
1483 1484 In [16]: _ip.IP.cache_main_mod(IPython)
1484 1485
1485 1486 In [17]: len(_ip.IP._user_main_modules) > 0
1486 1487 Out[17]: True
1487 1488
1488 1489 In [18]: _ip.IP.clear_main_mod_cache()
1489 1490
1490 1491 In [19]: len(_ip.IP._user_main_modules) == 0
1491 1492 Out[19]: True
1492 1493 """
1493 1494 self._user_main_modules.clear()
1494 1495
1495 1496 def _should_recompile(self,e):
1496 1497 """Utility routine for edit_syntax_error"""
1497 1498
1498 1499 if e.filename in ('<ipython console>','<input>','<string>',
1499 1500 '<console>','<BackgroundJob compilation>',
1500 1501 None):
1501 1502
1502 1503 return False
1503 1504 try:
1504 1505 if (self.rc.autoedit_syntax and
1505 1506 not self.ask_yes_no('Return to editor to correct syntax error? '
1506 1507 '[Y/n] ','y')):
1507 1508 return False
1508 1509 except EOFError:
1509 1510 return False
1510 1511
1511 1512 def int0(x):
1512 1513 try:
1513 1514 return int(x)
1514 1515 except TypeError:
1515 1516 return 0
1516 1517 # always pass integer line and offset values to editor hook
1517 1518 try:
1518 1519 self.hooks.fix_error_editor(e.filename,
1519 1520 int0(e.lineno),int0(e.offset),e.msg)
1520 1521 except IPython.ipapi.TryNext:
1521 1522 warn('Could not open editor')
1522 1523 return False
1523 1524 return True
1524 1525
1525 1526 def edit_syntax_error(self):
1526 1527 """The bottom half of the syntax error handler called in the main loop.
1527 1528
1528 1529 Loop until syntax error is fixed or user cancels.
1529 1530 """
1530 1531
1531 1532 while self.SyntaxTB.last_syntax_error:
1532 1533 # copy and clear last_syntax_error
1533 1534 err = self.SyntaxTB.clear_err_state()
1534 1535 if not self._should_recompile(err):
1535 1536 return
1536 1537 try:
1537 1538 # may set last_syntax_error again if a SyntaxError is raised
1538 1539 self.safe_execfile(err.filename,self.user_ns)
1539 1540 except:
1540 1541 self.showtraceback()
1541 1542 else:
1542 1543 try:
1543 1544 f = file(err.filename)
1544 1545 try:
1545 1546 sys.displayhook(f.read())
1546 1547 finally:
1547 1548 f.close()
1548 1549 except:
1549 1550 self.showtraceback()
1550 1551
1551 1552 def showsyntaxerror(self, filename=None):
1552 1553 """Display the syntax error that just occurred.
1553 1554
1554 1555 This doesn't display a stack trace because there isn't one.
1555 1556
1556 1557 If a filename is given, it is stuffed in the exception instead
1557 1558 of what was there before (because Python's parser always uses
1558 1559 "<string>" when reading from a string).
1559 1560 """
1560 1561 etype, value, last_traceback = sys.exc_info()
1561 1562
1562 1563 # See note about these variables in showtraceback() below
1563 1564 sys.last_type = etype
1564 1565 sys.last_value = value
1565 1566 sys.last_traceback = last_traceback
1566 1567
1567 1568 if filename and etype is SyntaxError:
1568 1569 # Work hard to stuff the correct filename in the exception
1569 1570 try:
1570 1571 msg, (dummy_filename, lineno, offset, line) = value
1571 1572 except:
1572 1573 # Not the format we expect; leave it alone
1573 1574 pass
1574 1575 else:
1575 1576 # Stuff in the right filename
1576 1577 try:
1577 1578 # Assume SyntaxError is a class exception
1578 1579 value = SyntaxError(msg, (filename, lineno, offset, line))
1579 1580 except:
1580 1581 # If that failed, assume SyntaxError is a string
1581 1582 value = msg, (filename, lineno, offset, line)
1582 1583 self.SyntaxTB(etype,value,[])
1583 1584
1584 1585 def debugger(self,force=False):
1585 1586 """Call the pydb/pdb debugger.
1586 1587
1587 1588 Keywords:
1588 1589
1589 1590 - force(False): by default, this routine checks the instance call_pdb
1590 1591 flag and does not actually invoke the debugger if the flag is false.
1591 1592 The 'force' option forces the debugger to activate even if the flag
1592 1593 is false.
1593 1594 """
1594 1595
1595 1596 if not (force or self.call_pdb):
1596 1597 return
1597 1598
1598 1599 if not hasattr(sys,'last_traceback'):
1599 1600 error('No traceback has been produced, nothing to debug.')
1600 1601 return
1601 1602
1602 1603 # use pydb if available
1603 1604 if Debugger.has_pydb:
1604 1605 from pydb import pm
1605 1606 else:
1606 1607 # fallback to our internal debugger
1607 1608 pm = lambda : self.InteractiveTB.debugger(force=True)
1608 1609 self.history_saving_wrapper(pm)()
1609 1610
1610 1611 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None):
1611 1612 """Display the exception that just occurred.
1612 1613
1613 1614 If nothing is known about the exception, this is the method which
1614 1615 should be used throughout the code for presenting user tracebacks,
1615 1616 rather than directly invoking the InteractiveTB object.
1616 1617
1617 1618 A specific showsyntaxerror() also exists, but this method can take
1618 1619 care of calling it if needed, so unless you are explicitly catching a
1619 1620 SyntaxError exception, don't try to analyze the stack manually and
1620 1621 simply call this method."""
1621 1622
1622 1623
1623 1624 # Though this won't be called by syntax errors in the input line,
1624 1625 # there may be SyntaxError cases whith imported code.
1625 1626
1626 1627 try:
1627 1628 if exc_tuple is None:
1628 1629 etype, value, tb = sys.exc_info()
1629 1630 else:
1630 1631 etype, value, tb = exc_tuple
1631 1632
1632 1633 if etype is SyntaxError:
1633 1634 self.showsyntaxerror(filename)
1634 1635 elif etype is IPython.ipapi.UsageError:
1635 1636 print "UsageError:", value
1636 1637 else:
1637 1638 # WARNING: these variables are somewhat deprecated and not
1638 1639 # necessarily safe to use in a threaded environment, but tools
1639 1640 # like pdb depend on their existence, so let's set them. If we
1640 1641 # find problems in the field, we'll need to revisit their use.
1641 1642 sys.last_type = etype
1642 1643 sys.last_value = value
1643 1644 sys.last_traceback = tb
1644 1645
1645 1646 if etype in self.custom_exceptions:
1646 1647 self.CustomTB(etype,value,tb)
1647 1648 else:
1648 1649 self.InteractiveTB(etype,value,tb,tb_offset=tb_offset)
1649 1650 if self.InteractiveTB.call_pdb and self.has_readline:
1650 1651 # pdb mucks up readline, fix it back
1651 1652 self.set_completer()
1652 1653 except KeyboardInterrupt:
1653 1654 self.write("\nKeyboardInterrupt\n")
1654 1655
1655 1656 def mainloop(self,banner=None):
1656 1657 """Creates the local namespace and starts the mainloop.
1657 1658
1658 1659 If an optional banner argument is given, it will override the
1659 1660 internally created default banner."""
1660 1661
1661 1662 if self.rc.c: # Emulate Python's -c option
1662 1663 self.exec_init_cmd()
1663 1664 if banner is None:
1664 1665 if not self.rc.banner:
1665 1666 banner = ''
1666 1667 # banner is string? Use it directly!
1667 1668 elif isinstance(self.rc.banner,basestring):
1668 1669 banner = self.rc.banner
1669 1670 else:
1670 1671 banner = self.BANNER+self.banner2
1671 1672
1672 1673 # if you run stuff with -c <cmd>, raw hist is not updated
1673 1674 # ensure that it's in sync
1674 1675 if len(self.input_hist) != len (self.input_hist_raw):
1675 1676 self.input_hist_raw = InputList(self.input_hist)
1676 1677
1677 1678 while 1:
1678 1679 try:
1679 1680 self.interact(banner)
1680 1681 #self.interact_with_readline()
1681 1682
1682 1683 # XXX for testing of a readline-decoupled repl loop, call
1683 1684 # interact_with_readline above
1684 1685
1685 1686 break
1686 1687 except KeyboardInterrupt:
1687 1688 # this should not be necessary, but KeyboardInterrupt
1688 1689 # handling seems rather unpredictable...
1689 1690 self.write("\nKeyboardInterrupt in interact()\n")
1690 1691
1691 1692 def exec_init_cmd(self):
1692 1693 """Execute a command given at the command line.
1693 1694
1694 1695 This emulates Python's -c option."""
1695 1696
1696 1697 #sys.argv = ['-c']
1697 1698 self.push(self.prefilter(self.rc.c, False))
1698 1699 if not self.rc.interact:
1699 1700 self.ask_exit()
1700 1701
1701 1702 def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0):
1702 1703 """Embeds IPython into a running python program.
1703 1704
1704 1705 Input:
1705 1706
1706 1707 - header: An optional header message can be specified.
1707 1708
1708 1709 - local_ns, global_ns: working namespaces. If given as None, the
1709 1710 IPython-initialized one is updated with __main__.__dict__, so that
1710 1711 program variables become visible but user-specific configuration
1711 1712 remains possible.
1712 1713
1713 1714 - stack_depth: specifies how many levels in the stack to go to
1714 1715 looking for namespaces (when local_ns and global_ns are None). This
1715 1716 allows an intermediate caller to make sure that this function gets
1716 1717 the namespace from the intended level in the stack. By default (0)
1717 1718 it will get its locals and globals from the immediate caller.
1718 1719
1719 1720 Warning: it's possible to use this in a program which is being run by
1720 1721 IPython itself (via %run), but some funny things will happen (a few
1721 1722 globals get overwritten). In the future this will be cleaned up, as
1722 1723 there is no fundamental reason why it can't work perfectly."""
1723 1724
1724 1725 # Get locals and globals from caller
1725 1726 if local_ns is None or global_ns is None:
1726 1727 call_frame = sys._getframe(stack_depth).f_back
1727 1728
1728 1729 if local_ns is None:
1729 1730 local_ns = call_frame.f_locals
1730 1731 if global_ns is None:
1731 1732 global_ns = call_frame.f_globals
1732 1733
1733 1734 # Update namespaces and fire up interpreter
1734 1735
1735 1736 # The global one is easy, we can just throw it in
1736 1737 self.user_global_ns = global_ns
1737 1738
1738 1739 # but the user/local one is tricky: ipython needs it to store internal
1739 1740 # data, but we also need the locals. We'll copy locals in the user
1740 1741 # one, but will track what got copied so we can delete them at exit.
1741 1742 # This is so that a later embedded call doesn't see locals from a
1742 1743 # previous call (which most likely existed in a separate scope).
1743 1744 local_varnames = local_ns.keys()
1744 1745 self.user_ns.update(local_ns)
1745 1746 #self.user_ns['local_ns'] = local_ns # dbg
1746 1747
1747 1748 # Patch for global embedding to make sure that things don't overwrite
1748 1749 # user globals accidentally. Thanks to Richard <rxe@renre-europe.com>
1749 1750 # FIXME. Test this a bit more carefully (the if.. is new)
1750 1751 if local_ns is None and global_ns is None:
1751 1752 self.user_global_ns.update(__main__.__dict__)
1752 1753
1753 1754 # make sure the tab-completer has the correct frame information, so it
1754 1755 # actually completes using the frame's locals/globals
1755 1756 self.set_completer_frame()
1756 1757
1757 1758 # before activating the interactive mode, we need to make sure that
1758 1759 # all names in the builtin namespace needed by ipython point to
1759 1760 # ourselves, and not to other instances.
1760 1761 self.add_builtins()
1761 1762
1762 1763 self.interact(header)
1763 1764
1764 1765 # now, purge out the user namespace from anything we might have added
1765 1766 # from the caller's local namespace
1766 1767 delvar = self.user_ns.pop
1767 1768 for var in local_varnames:
1768 1769 delvar(var,None)
1769 1770 # and clean builtins we may have overridden
1770 1771 self.clean_builtins()
1771 1772
1772 1773 def interact_prompt(self):
1773 1774 """ Print the prompt (in read-eval-print loop)
1774 1775
1775 1776 Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
1776 1777 used in standard IPython flow.
1777 1778 """
1778 1779 if self.more:
1779 1780 try:
1780 1781 prompt = self.hooks.generate_prompt(True)
1781 1782 except:
1782 1783 self.showtraceback()
1783 1784 if self.autoindent:
1784 1785 self.rl_do_indent = True
1785 1786
1786 1787 else:
1787 1788 try:
1788 1789 prompt = self.hooks.generate_prompt(False)
1789 1790 except:
1790 1791 self.showtraceback()
1791 1792 self.write(prompt)
1792 1793
1793 1794 def interact_handle_input(self,line):
1794 1795 """ Handle the input line (in read-eval-print loop)
1795 1796
1796 1797 Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
1797 1798 used in standard IPython flow.
1798 1799 """
1799 1800 if line.lstrip() == line:
1800 1801 self.shadowhist.add(line.strip())
1801 1802 lineout = self.prefilter(line,self.more)
1802 1803
1803 1804 if line.strip():
1804 1805 if self.more:
1805 1806 self.input_hist_raw[-1] += '%s\n' % line
1806 1807 else:
1807 1808 self.input_hist_raw.append('%s\n' % line)
1808 1809
1809 1810
1810 1811 self.more = self.push(lineout)
1811 1812 if (self.SyntaxTB.last_syntax_error and
1812 1813 self.rc.autoedit_syntax):
1813 1814 self.edit_syntax_error()
1814 1815
1815 1816 def interact_with_readline(self):
1816 1817 """ Demo of using interact_handle_input, interact_prompt
1817 1818
1818 1819 This is the main read-eval-print loop. If you need to implement your own (e.g. for GUI),
1819 1820 it should work like this.
1820 1821 """
1821 1822 self.readline_startup_hook(self.pre_readline)
1822 1823 while not self.exit_now:
1823 1824 self.interact_prompt()
1824 1825 if self.more:
1825 1826 self.rl_do_indent = True
1826 1827 else:
1827 1828 self.rl_do_indent = False
1828 1829 line = raw_input_original().decode(self.stdin_encoding)
1829 1830 self.interact_handle_input(line)
1830 1831
1831 1832
1832 1833 def interact(self, banner=None):
1833 1834 """Closely emulate the interactive Python console.
1834 1835
1835 1836 The optional banner argument specify the banner to print
1836 1837 before the first interaction; by default it prints a banner
1837 1838 similar to the one printed by the real Python interpreter,
1838 1839 followed by the current class name in parentheses (so as not
1839 1840 to confuse this with the real interpreter -- since it's so
1840 1841 close!).
1841 1842
1842 1843 """
1843 1844
1844 1845 if self.exit_now:
1845 1846 # batch run -> do not interact
1846 1847 return
1847 1848 cprt = 'Type "copyright", "credits" or "license" for more information.'
1848 1849 if banner is None:
1849 1850 self.write("Python %s on %s\n%s\n(%s)\n" %
1850 1851 (sys.version, sys.platform, cprt,
1851 1852 self.__class__.__name__))
1852 1853 else:
1853 1854 self.write(banner)
1854 1855
1855 1856 more = 0
1856 1857
1857 1858 # Mark activity in the builtins
1858 1859 __builtin__.__dict__['__IPYTHON__active'] += 1
1859 1860
1860 1861 if self.has_readline:
1861 1862 self.readline_startup_hook(self.pre_readline)
1862 1863 # exit_now is set by a call to %Exit or %Quit, through the
1863 1864 # ask_exit callback.
1864 1865
1865 1866 while not self.exit_now:
1866 1867 self.hooks.pre_prompt_hook()
1867 1868 if more:
1868 1869 try:
1869 1870 prompt = self.hooks.generate_prompt(True)
1870 1871 except:
1871 1872 self.showtraceback()
1872 1873 if self.autoindent:
1873 1874 self.rl_do_indent = True
1874 1875
1875 1876 else:
1876 1877 try:
1877 1878 prompt = self.hooks.generate_prompt(False)
1878 1879 except:
1879 1880 self.showtraceback()
1880 1881 try:
1881 1882 line = self.raw_input(prompt,more)
1882 1883 if self.exit_now:
1883 1884 # quick exit on sys.std[in|out] close
1884 1885 break
1885 1886 if self.autoindent:
1886 1887 self.rl_do_indent = False
1887 1888
1888 1889 except KeyboardInterrupt:
1889 1890 #double-guard against keyboardinterrupts during kbdint handling
1890 1891 try:
1891 1892 self.write('\nKeyboardInterrupt\n')
1892 1893 self.resetbuffer()
1893 1894 # keep cache in sync with the prompt counter:
1894 1895 self.outputcache.prompt_count -= 1
1895 1896
1896 1897 if self.autoindent:
1897 1898 self.indent_current_nsp = 0
1898 1899 more = 0
1899 1900 except KeyboardInterrupt:
1900 1901 pass
1901 1902 except EOFError:
1902 1903 if self.autoindent:
1903 1904 self.rl_do_indent = False
1904 1905 self.readline_startup_hook(None)
1905 1906 self.write('\n')
1906 1907 self.exit()
1907 1908 except bdb.BdbQuit:
1908 1909 warn('The Python debugger has exited with a BdbQuit exception.\n'
1909 1910 'Because of how pdb handles the stack, it is impossible\n'
1910 1911 'for IPython to properly format this particular exception.\n'
1911 1912 'IPython will resume normal operation.')
1912 1913 except:
1913 1914 # exceptions here are VERY RARE, but they can be triggered
1914 1915 # asynchronously by signal handlers, for example.
1915 1916 self.showtraceback()
1916 1917 else:
1917 1918 more = self.push(line)
1918 1919 if (self.SyntaxTB.last_syntax_error and
1919 1920 self.rc.autoedit_syntax):
1920 1921 self.edit_syntax_error()
1921 1922
1922 1923 # We are off again...
1923 1924 __builtin__.__dict__['__IPYTHON__active'] -= 1
1924 1925
1925 1926 def excepthook(self, etype, value, tb):
1926 1927 """One more defense for GUI apps that call sys.excepthook.
1927 1928
1928 1929 GUI frameworks like wxPython trap exceptions and call
1929 1930 sys.excepthook themselves. I guess this is a feature that
1930 1931 enables them to keep running after exceptions that would
1931 1932 otherwise kill their mainloop. This is a bother for IPython
1932 1933 which excepts to catch all of the program exceptions with a try:
1933 1934 except: statement.
1934 1935
1935 1936 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1936 1937 any app directly invokes sys.excepthook, it will look to the user like
1937 1938 IPython crashed. In order to work around this, we can disable the
1938 1939 CrashHandler and replace it with this excepthook instead, which prints a
1939 1940 regular traceback using our InteractiveTB. In this fashion, apps which
1940 1941 call sys.excepthook will generate a regular-looking exception from
1941 1942 IPython, and the CrashHandler will only be triggered by real IPython
1942 1943 crashes.
1943 1944
1944 1945 This hook should be used sparingly, only in places which are not likely
1945 1946 to be true IPython errors.
1946 1947 """
1947 1948 self.showtraceback((etype,value,tb),tb_offset=0)
1948 1949
1949 1950 def expand_aliases(self,fn,rest):
1950 1951 """ Expand multiple levels of aliases:
1951 1952
1952 1953 if:
1953 1954
1954 1955 alias foo bar /tmp
1955 1956 alias baz foo
1956 1957
1957 1958 then:
1958 1959
1959 1960 baz huhhahhei -> bar /tmp huhhahhei
1960 1961
1961 1962 """
1962 1963 line = fn + " " + rest
1963 1964
1964 1965 done = set()
1965 1966 while 1:
1966 1967 pre,fn,rest = prefilter.splitUserInput(line,
1967 1968 prefilter.shell_line_split)
1968 1969 if fn in self.alias_table:
1969 1970 if fn in done:
1970 1971 warn("Cyclic alias definition, repeated '%s'" % fn)
1971 1972 return ""
1972 1973 done.add(fn)
1973 1974
1974 1975 l2 = self.transform_alias(fn,rest)
1975 1976 # dir -> dir
1976 1977 # print "alias",line, "->",l2 #dbg
1977 1978 if l2 == line:
1978 1979 break
1979 1980 # ls -> ls -F should not recurse forever
1980 1981 if l2.split(None,1)[0] == line.split(None,1)[0]:
1981 1982 line = l2
1982 1983 break
1983 1984
1984 1985 line=l2
1985 1986
1986 1987
1987 1988 # print "al expand to",line #dbg
1988 1989 else:
1989 1990 break
1990 1991
1991 1992 return line
1992 1993
1993 1994 def transform_alias(self, alias,rest=''):
1994 1995 """ Transform alias to system command string.
1995 1996 """
1996 1997 trg = self.alias_table[alias]
1997 1998
1998 1999 nargs,cmd = trg
1999 2000 # print trg #dbg
2000 2001 if ' ' in cmd and os.path.isfile(cmd):
2001 2002 cmd = '"%s"' % cmd
2002 2003
2003 2004 # Expand the %l special to be the user's input line
2004 2005 if cmd.find('%l') >= 0:
2005 2006 cmd = cmd.replace('%l',rest)
2006 2007 rest = ''
2007 2008 if nargs==0:
2008 2009 # Simple, argument-less aliases
2009 2010 cmd = '%s %s' % (cmd,rest)
2010 2011 else:
2011 2012 # Handle aliases with positional arguments
2012 2013 args = rest.split(None,nargs)
2013 2014 if len(args)< nargs:
2014 2015 error('Alias <%s> requires %s arguments, %s given.' %
2015 2016 (alias,nargs,len(args)))
2016 2017 return None
2017 2018 cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
2018 2019 # Now call the macro, evaluating in the user's namespace
2019 2020 #print 'new command: <%r>' % cmd # dbg
2020 2021 return cmd
2021 2022
2022 2023 def call_alias(self,alias,rest=''):
2023 2024 """Call an alias given its name and the rest of the line.
2024 2025
2025 2026 This is only used to provide backwards compatibility for users of
2026 2027 ipalias(), use of which is not recommended for anymore."""
2027 2028
2028 2029 # Now call the macro, evaluating in the user's namespace
2029 2030 cmd = self.transform_alias(alias, rest)
2030 2031 try:
2031 2032 self.system(cmd)
2032 2033 except:
2033 2034 self.showtraceback()
2034 2035
2035 2036 def indent_current_str(self):
2036 2037 """return the current level of indentation as a string"""
2037 2038 return self.indent_current_nsp * ' '
2038 2039
2039 2040 def autoindent_update(self,line):
2040 2041 """Keep track of the indent level."""
2041 2042
2042 2043 #debugx('line')
2043 2044 #debugx('self.indent_current_nsp')
2044 2045 if self.autoindent:
2045 2046 if line:
2046 2047 inisp = num_ini_spaces(line)
2047 2048 if inisp < self.indent_current_nsp:
2048 2049 self.indent_current_nsp = inisp
2049 2050
2050 2051 if line[-1] == ':':
2051 2052 self.indent_current_nsp += 4
2052 2053 elif dedent_re.match(line):
2053 2054 self.indent_current_nsp -= 4
2054 2055 else:
2055 2056 self.indent_current_nsp = 0
2056 2057
2057 2058 def runlines(self,lines):
2058 2059 """Run a string of one or more lines of source.
2059 2060
2060 2061 This method is capable of running a string containing multiple source
2061 2062 lines, as if they had been entered at the IPython prompt. Since it
2062 2063 exposes IPython's processing machinery, the given strings can contain
2063 2064 magic calls (%magic), special shell access (!cmd), etc."""
2064 2065
2065 2066 # We must start with a clean buffer, in case this is run from an
2066 2067 # interactive IPython session (via a magic, for example).
2067 2068 self.resetbuffer()
2068 2069 lines = lines.split('\n')
2069 2070 more = 0
2070 2071
2071 2072 for line in lines:
2072 2073 # skip blank lines so we don't mess up the prompt counter, but do
2073 2074 # NOT skip even a blank line if we are in a code block (more is
2074 2075 # true)
2075 2076
2076 2077 if line or more:
2077 2078 # push to raw history, so hist line numbers stay in sync
2078 2079 self.input_hist_raw.append("# " + line + "\n")
2079 2080 more = self.push(self.prefilter(line,more))
2080 2081 # IPython's runsource returns None if there was an error
2081 2082 # compiling the code. This allows us to stop processing right
2082 2083 # away, so the user gets the error message at the right place.
2083 2084 if more is None:
2084 2085 break
2085 2086 else:
2086 2087 self.input_hist_raw.append("\n")
2087 2088 # final newline in case the input didn't have it, so that the code
2088 2089 # actually does get executed
2089 2090 if more:
2090 2091 self.push('\n')
2091 2092
2092 2093 def runsource(self, source, filename='<input>', symbol='single'):
2093 2094 """Compile and run some source in the interpreter.
2094 2095
2095 2096 Arguments are as for compile_command().
2096 2097
2097 2098 One several things can happen:
2098 2099
2099 2100 1) The input is incorrect; compile_command() raised an
2100 2101 exception (SyntaxError or OverflowError). A syntax traceback
2101 2102 will be printed by calling the showsyntaxerror() method.
2102 2103
2103 2104 2) The input is incomplete, and more input is required;
2104 2105 compile_command() returned None. Nothing happens.
2105 2106
2106 2107 3) The input is complete; compile_command() returned a code
2107 2108 object. The code is executed by calling self.runcode() (which
2108 2109 also handles run-time exceptions, except for SystemExit).
2109 2110
2110 2111 The return value is:
2111 2112
2112 2113 - True in case 2
2113 2114
2114 2115 - False in the other cases, unless an exception is raised, where
2115 2116 None is returned instead. This can be used by external callers to
2116 2117 know whether to continue feeding input or not.
2117 2118
2118 2119 The return value can be used to decide whether to use sys.ps1 or
2119 2120 sys.ps2 to prompt the next line."""
2120 2121
2121 2122 # if the source code has leading blanks, add 'if 1:\n' to it
2122 2123 # this allows execution of indented pasted code. It is tempting
2123 2124 # to add '\n' at the end of source to run commands like ' a=1'
2124 2125 # directly, but this fails for more complicated scenarios
2125 2126 source=source.encode(self.stdin_encoding)
2126 2127 if source[:1] in [' ', '\t']:
2127 2128 source = 'if 1:\n%s' % source
2128 2129
2129 2130 try:
2130 2131 code = self.compile(source,filename,symbol)
2131 2132 except (OverflowError, SyntaxError, ValueError, TypeError):
2132 2133 # Case 1
2133 2134 self.showsyntaxerror(filename)
2134 2135 return None
2135 2136
2136 2137 if code is None:
2137 2138 # Case 2
2138 2139 return True
2139 2140
2140 2141 # Case 3
2141 2142 # We store the code object so that threaded shells and
2142 2143 # custom exception handlers can access all this info if needed.
2143 2144 # The source corresponding to this can be obtained from the
2144 2145 # buffer attribute as '\n'.join(self.buffer).
2145 2146 self.code_to_run = code
2146 2147 # now actually execute the code object
2147 2148 if self.runcode(code) == 0:
2148 2149 return False
2149 2150 else:
2150 2151 return None
2151 2152
2152 2153 def runcode(self,code_obj):
2153 2154 """Execute a code object.
2154 2155
2155 2156 When an exception occurs, self.showtraceback() is called to display a
2156 2157 traceback.
2157 2158
2158 2159 Return value: a flag indicating whether the code to be run completed
2159 2160 successfully:
2160 2161
2161 2162 - 0: successful execution.
2162 2163 - 1: an error occurred.
2163 2164 """
2164 2165
2165 2166 # Set our own excepthook in case the user code tries to call it
2166 2167 # directly, so that the IPython crash handler doesn't get triggered
2167 2168 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
2168 2169
2169 2170 # we save the original sys.excepthook in the instance, in case config
2170 2171 # code (such as magics) needs access to it.
2171 2172 self.sys_excepthook = old_excepthook
2172 2173 outflag = 1 # happens in more places, so it's easier as default
2173 2174 try:
2174 2175 try:
2175 2176 self.hooks.pre_runcode_hook()
2176 2177 exec code_obj in self.user_global_ns, self.user_ns
2177 2178 finally:
2178 2179 # Reset our crash handler in place
2179 2180 sys.excepthook = old_excepthook
2180 2181 except SystemExit:
2181 2182 self.resetbuffer()
2182 2183 self.showtraceback()
2183 2184 warn("Type %exit or %quit to exit IPython "
2184 2185 "(%Exit or %Quit do so unconditionally).",level=1)
2185 2186 except self.custom_exceptions:
2186 2187 etype,value,tb = sys.exc_info()
2187 2188 self.CustomTB(etype,value,tb)
2188 2189 except:
2189 2190 self.showtraceback()
2190 2191 else:
2191 2192 outflag = 0
2192 2193 if softspace(sys.stdout, 0):
2193 2194 print
2194 2195 # Flush out code object which has been run (and source)
2195 2196 self.code_to_run = None
2196 2197 return outflag
2197 2198
2198 2199 def push(self, line):
2199 2200 """Push a line to the interpreter.
2200 2201
2201 2202 The line should not have a trailing newline; it may have
2202 2203 internal newlines. The line is appended to a buffer and the
2203 2204 interpreter's runsource() method is called with the
2204 2205 concatenated contents of the buffer as source. If this
2205 2206 indicates that the command was executed or invalid, the buffer
2206 2207 is reset; otherwise, the command is incomplete, and the buffer
2207 2208 is left as it was after the line was appended. The return
2208 2209 value is 1 if more input is required, 0 if the line was dealt
2209 2210 with in some way (this is the same as runsource()).
2210 2211 """
2211 2212
2212 2213 # autoindent management should be done here, and not in the
2213 2214 # interactive loop, since that one is only seen by keyboard input. We
2214 2215 # need this done correctly even for code run via runlines (which uses
2215 2216 # push).
2216 2217
2217 2218 #print 'push line: <%s>' % line # dbg
2218 2219 for subline in line.splitlines():
2219 2220 self.autoindent_update(subline)
2220 2221 self.buffer.append(line)
2221 2222 more = self.runsource('\n'.join(self.buffer), self.filename)
2222 2223 if not more:
2223 2224 self.resetbuffer()
2224 2225 return more
2225 2226
2226 2227 def split_user_input(self, line):
2227 2228 # This is really a hold-over to support ipapi and some extensions
2228 2229 return prefilter.splitUserInput(line)
2229 2230
2230 2231 def resetbuffer(self):
2231 2232 """Reset the input buffer."""
2232 2233 self.buffer[:] = []
2233 2234
2234 2235 def raw_input(self,prompt='',continue_prompt=False):
2235 2236 """Write a prompt and read a line.
2236 2237
2237 2238 The returned line does not include the trailing newline.
2238 2239 When the user enters the EOF key sequence, EOFError is raised.
2239 2240
2240 2241 Optional inputs:
2241 2242
2242 2243 - prompt(''): a string to be printed to prompt the user.
2243 2244
2244 2245 - continue_prompt(False): whether this line is the first one or a
2245 2246 continuation in a sequence of inputs.
2246 2247 """
2247 2248
2248 2249 # Code run by the user may have modified the readline completer state.
2249 2250 # We must ensure that our completer is back in place.
2250 2251 if self.has_readline:
2251 2252 self.set_completer()
2252 2253
2253 2254 try:
2254 2255 line = raw_input_original(prompt).decode(self.stdin_encoding)
2255 2256 except ValueError:
2256 2257 warn("\n********\nYou or a %run:ed script called sys.stdin.close()"
2257 2258 " or sys.stdout.close()!\nExiting IPython!")
2258 2259 self.ask_exit()
2259 2260 return ""
2260 2261
2261 2262 # Try to be reasonably smart about not re-indenting pasted input more
2262 2263 # than necessary. We do this by trimming out the auto-indent initial
2263 2264 # spaces, if the user's actual input started itself with whitespace.
2264 2265 #debugx('self.buffer[-1]')
2265 2266
2266 2267 if self.autoindent:
2267 2268 if num_ini_spaces(line) > self.indent_current_nsp:
2268 2269 line = line[self.indent_current_nsp:]
2269 2270 self.indent_current_nsp = 0
2270 2271
2271 2272 # store the unfiltered input before the user has any chance to modify
2272 2273 # it.
2273 2274 if line.strip():
2274 2275 if continue_prompt:
2275 2276 self.input_hist_raw[-1] += '%s\n' % line
2276 2277 if self.has_readline: # and some config option is set?
2277 2278 try:
2278 2279 histlen = self.readline.get_current_history_length()
2279 2280 if histlen > 1:
2280 2281 newhist = self.input_hist_raw[-1].rstrip()
2281 2282 self.readline.remove_history_item(histlen-1)
2282 2283 self.readline.replace_history_item(histlen-2,
2283 2284 newhist.encode(self.stdin_encoding))
2284 2285 except AttributeError:
2285 2286 pass # re{move,place}_history_item are new in 2.4.
2286 2287 else:
2287 2288 self.input_hist_raw.append('%s\n' % line)
2288 2289 # only entries starting at first column go to shadow history
2289 2290 if line.lstrip() == line:
2290 2291 self.shadowhist.add(line.strip())
2291 2292 elif not continue_prompt:
2292 2293 self.input_hist_raw.append('\n')
2293 2294 try:
2294 2295 lineout = self.prefilter(line,continue_prompt)
2295 2296 except:
2296 2297 # blanket except, in case a user-defined prefilter crashes, so it
2297 2298 # can't take all of ipython with it.
2298 2299 self.showtraceback()
2299 2300 return ''
2300 2301 else:
2301 2302 return lineout
2302 2303
2303 2304 def _prefilter(self, line, continue_prompt):
2304 2305 """Calls different preprocessors, depending on the form of line."""
2305 2306
2306 2307 # All handlers *must* return a value, even if it's blank ('').
2307 2308
2308 2309 # Lines are NOT logged here. Handlers should process the line as
2309 2310 # needed, update the cache AND log it (so that the input cache array
2310 2311 # stays synced).
2311 2312
2312 2313 #.....................................................................
2313 2314 # Code begins
2314 2315
2315 2316 #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg
2316 2317
2317 2318 # save the line away in case we crash, so the post-mortem handler can
2318 2319 # record it
2319 2320 self._last_input_line = line
2320 2321
2321 2322 #print '***line: <%s>' % line # dbg
2322 2323
2323 2324 if not line:
2324 2325 # Return immediately on purely empty lines, so that if the user
2325 2326 # previously typed some whitespace that started a continuation
2326 2327 # prompt, he can break out of that loop with just an empty line.
2327 2328 # This is how the default python prompt works.
2328 2329
2329 2330 # Only return if the accumulated input buffer was just whitespace!
2330 2331 if ''.join(self.buffer).isspace():
2331 2332 self.buffer[:] = []
2332 2333 return ''
2333 2334
2334 2335 line_info = prefilter.LineInfo(line, continue_prompt)
2335 2336
2336 2337 # the input history needs to track even empty lines
2337 2338 stripped = line.strip()
2338 2339
2339 2340 if not stripped:
2340 2341 if not continue_prompt:
2341 2342 self.outputcache.prompt_count -= 1
2342 2343 return self.handle_normal(line_info)
2343 2344
2344 2345 # print '***cont',continue_prompt # dbg
2345 2346 # special handlers are only allowed for single line statements
2346 2347 if continue_prompt and not self.rc.multi_line_specials:
2347 2348 return self.handle_normal(line_info)
2348 2349
2349 2350
2350 2351 # See whether any pre-existing handler can take care of it
2351 2352 rewritten = self.hooks.input_prefilter(stripped)
2352 2353 if rewritten != stripped: # ok, some prefilter did something
2353 2354 rewritten = line_info.pre + rewritten # add indentation
2354 2355 return self.handle_normal(prefilter.LineInfo(rewritten,
2355 2356 continue_prompt))
2356 2357
2357 2358 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
2358 2359
2359 2360 return prefilter.prefilter(line_info, self)
2360 2361
2361 2362
2362 2363 def _prefilter_dumb(self, line, continue_prompt):
2363 2364 """simple prefilter function, for debugging"""
2364 2365 return self.handle_normal(line,continue_prompt)
2365 2366
2366 2367
2367 2368 def multiline_prefilter(self, line, continue_prompt):
2368 2369 """ Run _prefilter for each line of input
2369 2370
2370 2371 Covers cases where there are multiple lines in the user entry,
2371 2372 which is the case when the user goes back to a multiline history
2372 2373 entry and presses enter.
2373 2374
2374 2375 """
2375 2376 out = []
2376 2377 for l in line.rstrip('\n').split('\n'):
2377 2378 out.append(self._prefilter(l, continue_prompt))
2378 2379 return '\n'.join(out)
2379 2380
2380 2381 # Set the default prefilter() function (this can be user-overridden)
2381 2382 prefilter = multiline_prefilter
2382 2383
2383 2384 def handle_normal(self,line_info):
2384 2385 """Handle normal input lines. Use as a template for handlers."""
2385 2386
2386 2387 # With autoindent on, we need some way to exit the input loop, and I
2387 2388 # don't want to force the user to have to backspace all the way to
2388 2389 # clear the line. The rule will be in this case, that either two
2389 2390 # lines of pure whitespace in a row, or a line of pure whitespace but
2390 2391 # of a size different to the indent level, will exit the input loop.
2391 2392 line = line_info.line
2392 2393 continue_prompt = line_info.continue_prompt
2393 2394
2394 2395 if (continue_prompt and self.autoindent and line.isspace() and
2395 2396 (0 < abs(len(line) - self.indent_current_nsp) <= 2 or
2396 2397 (self.buffer[-1]).isspace() )):
2397 2398 line = ''
2398 2399
2399 2400 self.log(line,line,continue_prompt)
2400 2401 return line
2401 2402
2402 2403 def handle_alias(self,line_info):
2403 2404 """Handle alias input lines. """
2404 2405 tgt = self.alias_table[line_info.iFun]
2405 2406 # print "=>",tgt #dbg
2406 2407 if callable(tgt):
2407 2408 if '$' in line_info.line:
2408 2409 call_meth = '(_ip, _ip.itpl(%s))'
2409 2410 else:
2410 2411 call_meth = '(_ip,%s)'
2411 2412 line_out = ("%s_sh.%s" + call_meth) % (line_info.preWhitespace,
2412 2413 line_info.iFun,
2413 2414 make_quoted_expr(line_info.line))
2414 2415 else:
2415 2416 transformed = self.expand_aliases(line_info.iFun,line_info.theRest)
2416 2417
2417 2418 # pre is needed, because it carries the leading whitespace. Otherwise
2418 2419 # aliases won't work in indented sections.
2419 2420 line_out = '%s_ip.system(%s)' % (line_info.preWhitespace,
2420 2421 make_quoted_expr( transformed ))
2421 2422
2422 2423 self.log(line_info.line,line_out,line_info.continue_prompt)
2423 2424 #print 'line out:',line_out # dbg
2424 2425 return line_out
2425 2426
2426 2427 def handle_shell_escape(self, line_info):
2427 2428 """Execute the line in a shell, empty return value"""
2428 2429 #print 'line in :', `line` # dbg
2429 2430 line = line_info.line
2430 2431 if line.lstrip().startswith('!!'):
2431 2432 # rewrite LineInfo's line, iFun and theRest to properly hold the
2432 2433 # call to %sx and the actual command to be executed, so
2433 2434 # handle_magic can work correctly. Note that this works even if
2434 2435 # the line is indented, so it handles multi_line_specials
2435 2436 # properly.
2436 2437 new_rest = line.lstrip()[2:]
2437 2438 line_info.line = '%ssx %s' % (self.ESC_MAGIC,new_rest)
2438 2439 line_info.iFun = 'sx'
2439 2440 line_info.theRest = new_rest
2440 2441 return self.handle_magic(line_info)
2441 2442 else:
2442 2443 cmd = line.lstrip().lstrip('!')
2443 2444 line_out = '%s_ip.system(%s)' % (line_info.preWhitespace,
2444 2445 make_quoted_expr(cmd))
2445 2446 # update cache/log and return
2446 2447 self.log(line,line_out,line_info.continue_prompt)
2447 2448 return line_out
2448 2449
2449 2450 def handle_magic(self, line_info):
2450 2451 """Execute magic functions."""
2451 2452 iFun = line_info.iFun
2452 2453 theRest = line_info.theRest
2453 2454 cmd = '%s_ip.magic(%s)' % (line_info.preWhitespace,
2454 2455 make_quoted_expr(iFun + " " + theRest))
2455 2456 self.log(line_info.line,cmd,line_info.continue_prompt)
2456 2457 #print 'in handle_magic, cmd=<%s>' % cmd # dbg
2457 2458 return cmd
2458 2459
2459 2460 def handle_auto(self, line_info):
2460 2461 """Hande lines which can be auto-executed, quoting if requested."""
2461 2462
2462 2463 line = line_info.line
2463 2464 iFun = line_info.iFun
2464 2465 theRest = line_info.theRest
2465 2466 pre = line_info.pre
2466 2467 continue_prompt = line_info.continue_prompt
2467 2468 obj = line_info.ofind(self)['obj']
2468 2469
2469 2470 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
2470 2471
2471 2472 # This should only be active for single-line input!
2472 2473 if continue_prompt:
2473 2474 self.log(line,line,continue_prompt)
2474 2475 return line
2475 2476
2476 2477 force_auto = isinstance(obj, IPython.ipapi.IPyAutocall)
2477 2478 auto_rewrite = True
2478 2479
2479 2480 if pre == self.ESC_QUOTE:
2480 2481 # Auto-quote splitting on whitespace
2481 2482 newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) )
2482 2483 elif pre == self.ESC_QUOTE2:
2483 2484 # Auto-quote whole string
2484 2485 newcmd = '%s("%s")' % (iFun,theRest)
2485 2486 elif pre == self.ESC_PAREN:
2486 2487 newcmd = '%s(%s)' % (iFun,",".join(theRest.split()))
2487 2488 else:
2488 2489 # Auto-paren.
2489 2490 # We only apply it to argument-less calls if the autocall
2490 2491 # parameter is set to 2. We only need to check that autocall is <
2491 2492 # 2, since this function isn't called unless it's at least 1.
2492 2493 if not theRest and (self.rc.autocall < 2) and not force_auto:
2493 2494 newcmd = '%s %s' % (iFun,theRest)
2494 2495 auto_rewrite = False
2495 2496 else:
2496 2497 if not force_auto and theRest.startswith('['):
2497 2498 if hasattr(obj,'__getitem__'):
2498 2499 # Don't autocall in this case: item access for an object
2499 2500 # which is BOTH callable and implements __getitem__.
2500 2501 newcmd = '%s %s' % (iFun,theRest)
2501 2502 auto_rewrite = False
2502 2503 else:
2503 2504 # if the object doesn't support [] access, go ahead and
2504 2505 # autocall
2505 2506 newcmd = '%s(%s)' % (iFun.rstrip(),theRest)
2506 2507 elif theRest.endswith(';'):
2507 2508 newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1])
2508 2509 else:
2509 2510 newcmd = '%s(%s)' % (iFun.rstrip(), theRest)
2510 2511
2511 2512 if auto_rewrite:
2512 2513 rw = self.outputcache.prompt1.auto_rewrite() + newcmd
2513 2514
2514 2515 try:
2515 2516 # plain ascii works better w/ pyreadline, on some machines, so
2516 2517 # we use it and only print uncolored rewrite if we have unicode
2517 2518 rw = str(rw)
2518 2519 print >>Term.cout, rw
2519 2520 except UnicodeEncodeError:
2520 2521 print "-------------->" + newcmd
2521 2522
2522 2523 # log what is now valid Python, not the actual user input (without the
2523 2524 # final newline)
2524 2525 self.log(line,newcmd,continue_prompt)
2525 2526 return newcmd
2526 2527
2527 2528 def handle_help(self, line_info):
2528 2529 """Try to get some help for the object.
2529 2530
2530 2531 obj? or ?obj -> basic information.
2531 2532 obj?? or ??obj -> more details.
2532 2533 """
2533 2534
2534 2535 line = line_info.line
2535 2536 # We need to make sure that we don't process lines which would be
2536 2537 # otherwise valid python, such as "x=1 # what?"
2537 2538 try:
2538 2539 codeop.compile_command(line)
2539 2540 except SyntaxError:
2540 2541 # We should only handle as help stuff which is NOT valid syntax
2541 2542 if line[0]==self.ESC_HELP:
2542 2543 line = line[1:]
2543 2544 elif line[-1]==self.ESC_HELP:
2544 2545 line = line[:-1]
2545 2546 self.log(line,'#?'+line,line_info.continue_prompt)
2546 2547 if line:
2547 2548 #print 'line:<%r>' % line # dbg
2548 2549 self.magic_pinfo(line)
2549 2550 else:
2550 2551 page(self.usage,screen_lines=self.rc.screen_length)
2551 2552 return '' # Empty string is needed here!
2552 2553 except:
2553 2554 # Pass any other exceptions through to the normal handler
2554 2555 return self.handle_normal(line_info)
2555 2556 else:
2556 2557 # If the code compiles ok, we should handle it normally
2557 2558 return self.handle_normal(line_info)
2558 2559
2559 2560 def getapi(self):
2560 2561 """ Get an IPApi object for this shell instance
2561 2562
2562 2563 Getting an IPApi object is always preferable to accessing the shell
2563 2564 directly, but this holds true especially for extensions.
2564 2565
2565 2566 It should always be possible to implement an extension with IPApi
2566 2567 alone. If not, contact maintainer to request an addition.
2567 2568
2568 2569 """
2569 2570 return self.api
2570 2571
2571 2572 def handle_emacs(self, line_info):
2572 2573 """Handle input lines marked by python-mode."""
2573 2574
2574 2575 # Currently, nothing is done. Later more functionality can be added
2575 2576 # here if needed.
2576 2577
2577 2578 # The input cache shouldn't be updated
2578 2579 return line_info.line
2579 2580
2580 2581
2581 2582 def mktempfile(self,data=None):
2582 2583 """Make a new tempfile and return its filename.
2583 2584
2584 2585 This makes a call to tempfile.mktemp, but it registers the created
2585 2586 filename internally so ipython cleans it up at exit time.
2586 2587
2587 2588 Optional inputs:
2588 2589
2589 2590 - data(None): if data is given, it gets written out to the temp file
2590 2591 immediately, and the file is closed again."""
2591 2592
2592 2593 filename = tempfile.mktemp('.py','ipython_edit_')
2593 2594 self.tempfiles.append(filename)
2594 2595
2595 2596 if data:
2596 2597 tmp_file = open(filename,'w')
2597 2598 tmp_file.write(data)
2598 2599 tmp_file.close()
2599 2600 return filename
2600 2601
2601 2602 def write(self,data):
2602 2603 """Write a string to the default output"""
2603 2604 Term.cout.write(data)
2604 2605
2605 2606 def write_err(self,data):
2606 2607 """Write a string to the default error output"""
2607 2608 Term.cerr.write(data)
2608 2609
2609 2610 def ask_exit(self):
2610 2611 """ Call for exiting. Can be overiden and used as a callback. """
2611 2612 self.exit_now = True
2612 2613
2613 2614 def exit(self):
2614 2615 """Handle interactive exit.
2615 2616
2616 2617 This method calls the ask_exit callback."""
2617 2618
2618 2619 if self.rc.confirm_exit:
2619 2620 if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'):
2620 2621 self.ask_exit()
2621 2622 else:
2622 2623 self.ask_exit()
2623 2624
2624 2625 def safe_execfile(self,fname,*where,**kw):
2625 2626 """A safe version of the builtin execfile().
2626 2627
2627 2628 This version will never throw an exception, and knows how to handle
2628 2629 ipython logs as well.
2629 2630
2630 2631 :Parameters:
2631 2632 fname : string
2632 2633 Name of the file to be executed.
2633 2634
2634 2635 where : tuple
2635 2636 One or two namespaces, passed to execfile() as (globals,locals).
2636 2637 If only one is given, it is passed as both.
2637 2638
2638 2639 :Keywords:
2639 2640 islog : boolean (False)
2640 2641
2641 2642 quiet : boolean (True)
2642 2643
2643 2644 exit_ignore : boolean (False)
2644 2645 """
2645 2646
2646 2647 def syspath_cleanup():
2647 2648 """Internal cleanup routine for sys.path."""
2648 2649 if add_dname:
2649 2650 try:
2650 2651 sys.path.remove(dname)
2651 2652 except ValueError:
2652 2653 # For some reason the user has already removed it, ignore.
2653 2654 pass
2654 2655
2655 2656 fname = os.path.expanduser(fname)
2656 2657
2657 2658 # Find things also in current directory. This is needed to mimic the
2658 2659 # behavior of running a script from the system command line, where
2659 2660 # Python inserts the script's directory into sys.path
2660 2661 dname = os.path.dirname(os.path.abspath(fname))
2661 2662 add_dname = False
2662 2663 if dname not in sys.path:
2663 2664 sys.path.insert(0,dname)
2664 2665 add_dname = True
2665 2666
2666 2667 try:
2667 2668 xfile = open(fname)
2668 2669 except:
2669 2670 print >> Term.cerr, \
2670 2671 'Could not open file <%s> for safe execution.' % fname
2671 2672 syspath_cleanup()
2672 2673 return None
2673 2674
2674 2675 kw.setdefault('islog',0)
2675 2676 kw.setdefault('quiet',1)
2676 2677 kw.setdefault('exit_ignore',0)
2677 2678
2678 2679 first = xfile.readline()
2679 2680 loghead = str(self.loghead_tpl).split('\n',1)[0].strip()
2680 2681 xfile.close()
2681 2682 # line by line execution
2682 2683 if first.startswith(loghead) or kw['islog']:
2683 2684 print 'Loading log file <%s> one line at a time...' % fname
2684 2685 if kw['quiet']:
2685 2686 stdout_save = sys.stdout
2686 2687 sys.stdout = StringIO.StringIO()
2687 2688 try:
2688 2689 globs,locs = where[0:2]
2689 2690 except:
2690 2691 try:
2691 2692 globs = locs = where[0]
2692 2693 except:
2693 2694 globs = locs = globals()
2694 2695 badblocks = []
2695 2696
2696 2697 # we also need to identify indented blocks of code when replaying
2697 2698 # logs and put them together before passing them to an exec
2698 2699 # statement. This takes a bit of regexp and look-ahead work in the
2699 2700 # file. It's easiest if we swallow the whole thing in memory
2700 2701 # first, and manually walk through the lines list moving the
2701 2702 # counter ourselves.
2702 2703 indent_re = re.compile('\s+\S')
2703 2704 xfile = open(fname)
2704 2705 filelines = xfile.readlines()
2705 2706 xfile.close()
2706 2707 nlines = len(filelines)
2707 2708 lnum = 0
2708 2709 while lnum < nlines:
2709 2710 line = filelines[lnum]
2710 2711 lnum += 1
2711 2712 # don't re-insert logger status info into cache
2712 2713 if line.startswith('#log#'):
2713 2714 continue
2714 2715 else:
2715 2716 # build a block of code (maybe a single line) for execution
2716 2717 block = line
2717 2718 try:
2718 2719 next = filelines[lnum] # lnum has already incremented
2719 2720 except:
2720 2721 next = None
2721 2722 while next and indent_re.match(next):
2722 2723 block += next
2723 2724 lnum += 1
2724 2725 try:
2725 2726 next = filelines[lnum]
2726 2727 except:
2727 2728 next = None
2728 2729 # now execute the block of one or more lines
2729 2730 try:
2730 2731 exec block in globs,locs
2731 2732 except SystemExit:
2732 2733 pass
2733 2734 except:
2734 2735 badblocks.append(block.rstrip())
2735 2736 if kw['quiet']: # restore stdout
2736 2737 sys.stdout.close()
2737 2738 sys.stdout = stdout_save
2738 2739 print 'Finished replaying log file <%s>' % fname
2739 2740 if badblocks:
2740 2741 print >> sys.stderr, ('\nThe following lines/blocks in file '
2741 2742 '<%s> reported errors:' % fname)
2742 2743
2743 2744 for badline in badblocks:
2744 2745 print >> sys.stderr, badline
2745 2746 else: # regular file execution
2746 2747 try:
2747 2748 if sys.platform == 'win32' and sys.version_info < (2,5,1):
2748 2749 # Work around a bug in Python for Windows. The bug was
2749 2750 # fixed in in Python 2.5 r54159 and 54158, but that's still
2750 2751 # SVN Python as of March/07. For details, see:
2751 2752 # http://projects.scipy.org/ipython/ipython/ticket/123
2752 2753 try:
2753 2754 globs,locs = where[0:2]
2754 2755 except:
2755 2756 try:
2756 2757 globs = locs = where[0]
2757 2758 except:
2758 2759 globs = locs = globals()
2759 2760 exec file(fname) in globs,locs
2760 2761 else:
2761 2762 execfile(fname,*where)
2762 2763 except SyntaxError:
2763 2764 self.showsyntaxerror()
2764 2765 warn('Failure executing file: <%s>' % fname)
2765 2766 except SystemExit,status:
2766 2767 # Code that correctly sets the exit status flag to success (0)
2767 2768 # shouldn't be bothered with a traceback. Note that a plain
2768 2769 # sys.exit() does NOT set the message to 0 (it's empty) so that
2769 2770 # will still get a traceback. Note that the structure of the
2770 2771 # SystemExit exception changed between Python 2.4 and 2.5, so
2771 2772 # the checks must be done in a version-dependent way.
2772 2773 show = False
2773 2774
2774 2775 if sys.version_info[:2] > (2,5):
2775 2776 if status.message!=0 and not kw['exit_ignore']:
2776 2777 show = True
2777 2778 else:
2778 2779 if status.code and not kw['exit_ignore']:
2779 2780 show = True
2780 2781 if show:
2781 2782 self.showtraceback()
2782 2783 warn('Failure executing file: <%s>' % fname)
2783 2784 except:
2784 2785 self.showtraceback()
2785 2786 warn('Failure executing file: <%s>' % fname)
2786 2787
2787 2788 syspath_cleanup()
2788 2789
2789 2790 #************************* end of file <iplib.py> *****************************
@@ -1,780 +1,775 b''
1 1 # -*- coding: utf-8 -*-
2 2 """
3 3 IPython -- An enhanced Interactive Python
4 4
5 5 Requires Python 2.1 or better.
6 6
7 7 This file contains the main make_IPython() starter function.
8 8 """
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 IPython import Release
18 18 __author__ = '%s <%s>' % Release.authors['Fernando']
19 19 __license__ = Release.license
20 20 __version__ = Release.version
21 21
22 22 try:
23 23 credits._Printer__data = """
24 24 Python: %s
25 25
26 26 IPython: Fernando Perez, Janko Hauser, Nathan Gray, and many users.
27 27 See http://ipython.scipy.org for more information.""" \
28 28 % credits._Printer__data
29 29
30 30 copyright._Printer__data += """
31 31
32 32 Copyright (c) 2001-2004 Fernando Perez, Janko Hauser, Nathan Gray.
33 33 All Rights Reserved."""
34 34 except NameError:
35 35 # Can happen if ipython was started with 'python -S', so that site.py is
36 36 # not loaded
37 37 pass
38 38
39 39 #****************************************************************************
40 40 # Required modules
41 41
42 42 # From the standard library
43 43 import __main__
44 44 import __builtin__
45 45 import os
46 46 import re
47 47 import sys
48 48 import types
49 49 from pprint import pprint,pformat
50 50
51 51 # Our own
52 52 from IPython import DPyGetOpt
53 53 from IPython.ipstruct import Struct
54 54 from IPython.OutputTrap import OutputTrap
55 55 from IPython.ConfigLoader import ConfigLoader
56 56 from IPython.iplib import InteractiveShell
57 57 from IPython.usage import cmd_line_usage,interactive_usage
58 58 from IPython.genutils import *
59 59
60 60 def force_import(modname):
61 61 if modname in sys.modules:
62 62 print "reload",modname
63 63 reload(sys.modules[modname])
64 64 else:
65 65 __import__(modname)
66 66
67 67
68 68 #-----------------------------------------------------------------------------
69 69 def make_IPython(argv=None,user_ns=None,user_global_ns=None,debug=1,
70 70 rc_override=None,shell_class=InteractiveShell,
71 71 embedded=False,**kw):
72 72 """This is a dump of IPython into a single function.
73 73
74 74 Later it will have to be broken up in a sensible manner.
75 75
76 76 Arguments:
77 77
78 78 - argv: a list similar to sys.argv[1:]. It should NOT contain the desired
79 79 script name, b/c DPyGetOpt strips the first argument only for the real
80 80 sys.argv.
81 81
82 82 - user_ns: a dict to be used as the user's namespace."""
83 83
84 84 #----------------------------------------------------------------------
85 85 # Defaults and initialization
86 86
87 87 # For developer debugging, deactivates crash handler and uses pdb.
88 88 DEVDEBUG = False
89 89
90 90 if argv is None:
91 91 argv = sys.argv
92 92
93 93 # __IP is the main global that lives throughout and represents the whole
94 94 # application. If the user redefines it, all bets are off as to what
95 95 # happens.
96 96
97 97 # __IP is the name of he global which the caller will have accessible as
98 98 # __IP.name. We set its name via the first parameter passed to
99 99 # InteractiveShell:
100 100
101 101 IP = shell_class('__IP',user_ns=user_ns,user_global_ns=user_global_ns,
102 102 embedded=embedded,**kw)
103 103
104 104 # Put 'help' in the user namespace
105 105 try:
106 106 from site import _Helper
107 107 IP.user_ns['help'] = _Helper()
108 108 except ImportError:
109 109 warn('help() not available - check site.py')
110 110
111 111 if DEVDEBUG:
112 112 # For developer debugging only (global flag)
113 113 from IPython import ultraTB
114 114 sys.excepthook = ultraTB.VerboseTB(call_pdb=1)
115 115
116 116 IP.BANNER_PARTS = ['Python %s\n'
117 117 'Type "copyright", "credits" or "license" '
118 118 'for more information.\n'
119 119 % (sys.version.split('\n')[0],),
120 120 "IPython %s -- An enhanced Interactive Python."
121 121 % (__version__,),
122 122 """\
123 123 ? -> Introduction and overview of IPython's features.
124 124 %quickref -> Quick reference.
125 125 help -> Python's own help system.
126 126 object? -> Details about 'object'. ?object also works, ?? prints more.
127 127 """ ]
128 128
129 129 IP.usage = interactive_usage
130 130
131 # Platform-dependent suffix and directory names. We use _ipython instead
132 # of .ipython under win32 b/c there's software that breaks with .named
133 # directories on that platform.
131 # Platform-dependent suffix.
134 132 if os.name == 'posix':
135 133 rc_suffix = ''
136 ipdir_def = '.ipython'
137 134 else:
138 135 rc_suffix = '.ini'
139 ipdir_def = '_ipython'
140 136
141 137 # default directory for configuration
142 ipythondir_def = os.path.abspath(os.environ.get('IPYTHONDIR',
143 os.path.join(IP.home_dir,ipdir_def)))
144
138 ipythondir_def = get_ipython_dir()
139
145 140 sys.path.insert(0, '') # add . to sys.path. Fix from Prabhu Ramachandran
146 141
147 142 # we need the directory where IPython itself is installed
148 143 import IPython
149 144 IPython_dir = os.path.dirname(IPython.__file__)
150 145 del IPython
151 146
152 147 #-------------------------------------------------------------------------
153 148 # Command line handling
154 149
155 150 # Valid command line options (uses DPyGetOpt syntax, like Perl's
156 151 # GetOpt::Long)
157 152
158 153 # Any key not listed here gets deleted even if in the file (like session
159 154 # or profile). That's deliberate, to maintain the rc namespace clean.
160 155
161 156 # Each set of options appears twice: under _conv only the names are
162 157 # listed, indicating which type they must be converted to when reading the
163 158 # ipythonrc file. And under DPyGetOpt they are listed with the regular
164 159 # DPyGetOpt syntax (=s,=i,:f,etc).
165 160
166 161 # Make sure there's a space before each end of line (they get auto-joined!)
167 162 cmdline_opts = ('autocall=i autoindent! automagic! banner! cache_size|cs=i '
168 163 'c=s classic|cl color_info! colors=s confirm_exit! '
169 164 'debug! deep_reload! editor=s log|l messages! nosep '
170 165 'object_info_string_level=i pdb! '
171 166 'pprint! prompt_in1|pi1=s prompt_in2|pi2=s prompt_out|po=s '
172 167 'pydb! '
173 168 'pylab_import_all! '
174 169 'quick screen_length|sl=i prompts_pad_left=i '
175 170 'logfile|lf=s logplay|lp=s profile|p=s '
176 171 'readline! readline_merge_completions! '
177 172 'readline_omit__names! '
178 173 'rcfile=s separate_in|si=s separate_out|so=s '
179 174 'separate_out2|so2=s xmode=s wildcards_case_sensitive! '
180 175 'magic_docstrings system_verbose! '
181 176 'multi_line_specials! '
182 177 'term_title! wxversion=s '
183 178 'autoedit_syntax!')
184 179
185 180 # Options that can *only* appear at the cmd line (not in rcfiles).
186 181
187 182 cmdline_only = ('help interact|i ipythondir=s Version upgrade '
188 183 'gthread! qthread! q4thread! wthread! tkthread! pylab! tk! '
189 184 # 'twisted!' # disabled for now.
190 185 )
191 186
192 187 # Build the actual name list to be used by DPyGetOpt
193 188 opts_names = qw(cmdline_opts) + qw(cmdline_only)
194 189
195 190 # Set sensible command line defaults.
196 191 # This should have everything from cmdline_opts and cmdline_only
197 192 opts_def = Struct(autocall = 1,
198 193 autoedit_syntax = 0,
199 194 autoindent = 0,
200 195 automagic = 1,
201 196 autoexec = [],
202 197 banner = 1,
203 198 c = '',
204 199 cache_size = 1000,
205 200 classic = 0,
206 201 color_info = 0,
207 202 colors = 'NoColor',
208 203 confirm_exit = 1,
209 204 debug = 0,
210 205 deep_reload = 0,
211 206 editor = '0',
212 207 gthread = 0,
213 208 help = 0,
214 209 interact = 0,
215 210 ipythondir = ipythondir_def,
216 211 log = 0,
217 212 logfile = '',
218 213 logplay = '',
219 214 messages = 1,
220 215 multi_line_specials = 1,
221 216 nosep = 0,
222 217 object_info_string_level = 0,
223 218 pdb = 0,
224 219 pprint = 0,
225 220 profile = '',
226 221 prompt_in1 = 'In [\\#]: ',
227 222 prompt_in2 = ' .\\D.: ',
228 223 prompt_out = 'Out[\\#]: ',
229 224 prompts_pad_left = 1,
230 225 pydb = 0,
231 226 pylab = 0,
232 227 pylab_import_all = 1,
233 228 q4thread = 0,
234 229 qthread = 0,
235 230 quick = 0,
236 231 quiet = 0,
237 232 rcfile = 'ipythonrc' + rc_suffix,
238 233 readline = 1,
239 234 readline_merge_completions = 1,
240 235 readline_omit__names = 0,
241 236 screen_length = 0,
242 237 separate_in = '\n',
243 238 separate_out = '\n',
244 239 separate_out2 = '',
245 240 system_header = 'IPython system call: ',
246 241 system_verbose = 0,
247 242 term_title = 1,
248 243 tk = 0,
249 244 #twisted= 0, # disabled for now
250 245 upgrade = 0,
251 246 Version = 0,
252 247 wildcards_case_sensitive = 1,
253 248 wthread = 0,
254 249 wxversion = '0',
255 250 xmode = 'Context',
256 251 magic_docstrings = 0, # undocumented, for doc generation
257 252 )
258 253
259 254 # Things that will *only* appear in rcfiles (not at the command line).
260 255 # Make sure there's a space before each end of line (they get auto-joined!)
261 256 rcfile_opts = { qwflat: 'include import_mod import_all execfile ',
262 257 qw_lol: 'import_some ',
263 258 # for things with embedded whitespace:
264 259 list_strings:'execute alias readline_parse_and_bind ',
265 260 # Regular strings need no conversion:
266 261 None:'readline_remove_delims ',
267 262 }
268 263 # Default values for these
269 264 rc_def = Struct(include = [],
270 265 import_mod = [],
271 266 import_all = [],
272 267 import_some = [[]],
273 268 execute = [],
274 269 execfile = [],
275 270 alias = [],
276 271 readline_parse_and_bind = [],
277 272 readline_remove_delims = '',
278 273 )
279 274
280 275 # Build the type conversion dictionary from the above tables:
281 276 typeconv = rcfile_opts.copy()
282 277 typeconv.update(optstr2types(cmdline_opts))
283 278
284 279 # FIXME: the None key appears in both, put that back together by hand. Ugly!
285 280 typeconv[None] += ' ' + rcfile_opts[None]
286 281
287 282 # Remove quotes at ends of all strings (used to protect spaces)
288 283 typeconv[unquote_ends] = typeconv[None]
289 284 del typeconv[None]
290 285
291 286 # Build the list we'll use to make all config decisions with defaults:
292 287 opts_all = opts_def.copy()
293 288 opts_all.update(rc_def)
294 289
295 290 # Build conflict resolver for recursive loading of config files:
296 291 # - preserve means the outermost file maintains the value, it is not
297 292 # overwritten if an included file has the same key.
298 293 # - add_flip applies + to the two values, so it better make sense to add
299 294 # those types of keys. But it flips them first so that things loaded
300 295 # deeper in the inclusion chain have lower precedence.
301 296 conflict = {'preserve': ' '.join([ typeconv[int],
302 297 typeconv[unquote_ends] ]),
303 298 'add_flip': ' '.join([ typeconv[qwflat],
304 299 typeconv[qw_lol],
305 300 typeconv[list_strings] ])
306 301 }
307 302
308 303 # Now actually process the command line
309 304 getopt = DPyGetOpt.DPyGetOpt()
310 305 getopt.setIgnoreCase(0)
311 306
312 307 getopt.parseConfiguration(opts_names)
313 308
314 309 try:
315 310 getopt.processArguments(argv)
316 311 except DPyGetOpt.ArgumentError, exc:
317 312 print cmd_line_usage
318 313 warn('\nError in Arguments: "%s"' % exc)
319 314 sys.exit(1)
320 315
321 316 # convert the options dict to a struct for much lighter syntax later
322 317 opts = Struct(getopt.optionValues)
323 318 args = getopt.freeValues
324 319
325 320 # this is the struct (which has default values at this point) with which
326 321 # we make all decisions:
327 322 opts_all.update(opts)
328 323
329 324 # Options that force an immediate exit
330 325 if opts_all.help:
331 326 page(cmd_line_usage)
332 327 sys.exit()
333 328
334 329 if opts_all.Version:
335 330 print __version__
336 331 sys.exit()
337 332
338 333 if opts_all.magic_docstrings:
339 334 IP.magic_magic('-latex')
340 335 sys.exit()
341 336
342 337 # add personal ipythondir to sys.path so that users can put things in
343 338 # there for customization
344 339 sys.path.append(os.path.abspath(opts_all.ipythondir))
345 340
346 341 # Create user config directory if it doesn't exist. This must be done
347 342 # *after* getting the cmd line options.
348 343 if not os.path.isdir(opts_all.ipythondir):
349 344 IP.user_setup(opts_all.ipythondir,rc_suffix,'install')
350 345
351 346 # upgrade user config files while preserving a copy of the originals
352 347 if opts_all.upgrade:
353 348 IP.user_setup(opts_all.ipythondir,rc_suffix,'upgrade')
354 349
355 350 # check mutually exclusive options in the *original* command line
356 351 mutex_opts(opts,[qw('log logfile'),qw('rcfile profile'),
357 352 qw('classic profile'),qw('classic rcfile')])
358 353
359 354 #---------------------------------------------------------------------------
360 355 # Log replay
361 356
362 357 # if -logplay, we need to 'become' the other session. That basically means
363 358 # replacing the current command line environment with that of the old
364 359 # session and moving on.
365 360
366 361 # this is needed so that later we know we're in session reload mode, as
367 362 # opts_all will get overwritten:
368 363 load_logplay = 0
369 364
370 365 if opts_all.logplay:
371 366 load_logplay = opts_all.logplay
372 367 opts_debug_save = opts_all.debug
373 368 try:
374 369 logplay = open(opts_all.logplay)
375 370 except IOError:
376 371 if opts_all.debug: IP.InteractiveTB()
377 372 warn('Could not open logplay file '+`opts_all.logplay`)
378 373 # restore state as if nothing had happened and move on, but make
379 374 # sure that later we don't try to actually load the session file
380 375 logplay = None
381 376 load_logplay = 0
382 377 del opts_all.logplay
383 378 else:
384 379 try:
385 380 logplay.readline()
386 381 logplay.readline();
387 382 # this reloads that session's command line
388 383 cmd = logplay.readline()[6:]
389 384 exec cmd
390 385 # restore the true debug flag given so that the process of
391 386 # session loading itself can be monitored.
392 387 opts.debug = opts_debug_save
393 388 # save the logplay flag so later we don't overwrite the log
394 389 opts.logplay = load_logplay
395 390 # now we must update our own structure with defaults
396 391 opts_all.update(opts)
397 392 # now load args
398 393 cmd = logplay.readline()[6:]
399 394 exec cmd
400 395 logplay.close()
401 396 except:
402 397 logplay.close()
403 398 if opts_all.debug: IP.InteractiveTB()
404 399 warn("Logplay file lacking full configuration information.\n"
405 400 "I'll try to read it, but some things may not work.")
406 401
407 402 #-------------------------------------------------------------------------
408 403 # set up output traps: catch all output from files, being run, modules
409 404 # loaded, etc. Then give it to the user in a clean form at the end.
410 405
411 406 msg_out = 'Output messages. '
412 407 msg_err = 'Error messages. '
413 408 msg_sep = '\n'
414 409 msg = Struct(config = OutputTrap('Configuration Loader',msg_out,
415 410 msg_err,msg_sep,debug,
416 411 quiet_out=1),
417 412 user_exec = OutputTrap('User File Execution',msg_out,
418 413 msg_err,msg_sep,debug),
419 414 logplay = OutputTrap('Log Loader',msg_out,
420 415 msg_err,msg_sep,debug),
421 416 summary = ''
422 417 )
423 418
424 419 #-------------------------------------------------------------------------
425 420 # Process user ipythonrc-type configuration files
426 421
427 422 # turn on output trapping and log to msg.config
428 423 # remember that with debug on, trapping is actually disabled
429 424 msg.config.trap_all()
430 425
431 426 # look for rcfile in current or default directory
432 427 try:
433 428 opts_all.rcfile = filefind(opts_all.rcfile,opts_all.ipythondir)
434 429 except IOError:
435 430 if opts_all.debug: IP.InteractiveTB()
436 431 warn('Configuration file %s not found. Ignoring request.'
437 432 % (opts_all.rcfile) )
438 433
439 434 # 'profiles' are a shorthand notation for config filenames
440 435 profile_handled_by_legacy = False
441 436 if opts_all.profile:
442 437
443 438 try:
444 439 opts_all.rcfile = filefind('ipythonrc-' + opts_all.profile
445 440 + rc_suffix,
446 441 opts_all.ipythondir)
447 442 profile_handled_by_legacy = True
448 443 except IOError:
449 444 if opts_all.debug: IP.InteractiveTB()
450 445 opts.profile = '' # remove profile from options if invalid
451 446 # We won't warn anymore, primary method is ipy_profile_PROFNAME
452 447 # which does trigger a warning.
453 448
454 449 # load the config file
455 450 rcfiledata = None
456 451 if opts_all.quick:
457 452 print 'Launching IPython in quick mode. No config file read.'
458 453 elif opts_all.rcfile:
459 454 try:
460 455 cfg_loader = ConfigLoader(conflict)
461 456 rcfiledata = cfg_loader.load(opts_all.rcfile,typeconv,
462 457 'include',opts_all.ipythondir,
463 458 purge = 1,
464 459 unique = conflict['preserve'])
465 460 except:
466 461 IP.InteractiveTB()
467 462 warn('Problems loading configuration file '+
468 463 `opts_all.rcfile`+
469 464 '\nStarting with default -bare bones- configuration.')
470 465 else:
471 466 warn('No valid configuration file found in either currrent directory\n'+
472 467 'or in the IPython config. directory: '+`opts_all.ipythondir`+
473 468 '\nProceeding with internal defaults.')
474 469
475 470 #------------------------------------------------------------------------
476 471 # Set exception handlers in mode requested by user.
477 472 otrap = OutputTrap(trap_out=1) # trap messages from magic_xmode
478 473 IP.magic_xmode(opts_all.xmode)
479 474 otrap.release_out()
480 475
481 476 #------------------------------------------------------------------------
482 477 # Execute user config
483 478
484 479 # Create a valid config structure with the right precedence order:
485 480 # defaults < rcfile < command line. This needs to be in the instance, so
486 481 # that method calls below that rely on it find it.
487 482 IP.rc = rc_def.copy()
488 483
489 484 # Work with a local alias inside this routine to avoid unnecessary
490 485 # attribute lookups.
491 486 IP_rc = IP.rc
492 487
493 488 IP_rc.update(opts_def)
494 489 if rcfiledata:
495 490 # now we can update
496 491 IP_rc.update(rcfiledata)
497 492 IP_rc.update(opts)
498 493 IP_rc.update(rc_override)
499 494
500 495 # Store the original cmd line for reference:
501 496 IP_rc.opts = opts
502 497 IP_rc.args = args
503 498
504 499 # create a *runtime* Struct like rc for holding parameters which may be
505 500 # created and/or modified by runtime user extensions.
506 501 IP.runtime_rc = Struct()
507 502
508 503 # from this point on, all config should be handled through IP_rc,
509 504 # opts* shouldn't be used anymore.
510 505
511 506
512 507 # update IP_rc with some special things that need manual
513 508 # tweaks. Basically options which affect other options. I guess this
514 509 # should just be written so that options are fully orthogonal and we
515 510 # wouldn't worry about this stuff!
516 511
517 512 if IP_rc.classic:
518 513 IP_rc.quick = 1
519 514 IP_rc.cache_size = 0
520 515 IP_rc.pprint = 0
521 516 IP_rc.prompt_in1 = '>>> '
522 517 IP_rc.prompt_in2 = '... '
523 518 IP_rc.prompt_out = ''
524 519 IP_rc.separate_in = IP_rc.separate_out = IP_rc.separate_out2 = '0'
525 520 IP_rc.colors = 'NoColor'
526 521 IP_rc.xmode = 'Plain'
527 522
528 523 IP.pre_config_initialization()
529 524 # configure readline
530 525
531 526 # update exception handlers with rc file status
532 527 otrap.trap_out() # I don't want these messages ever.
533 528 IP.magic_xmode(IP_rc.xmode)
534 529 otrap.release_out()
535 530
536 531 # activate logging if requested and not reloading a log
537 532 if IP_rc.logplay:
538 533 IP.magic_logstart(IP_rc.logplay + ' append')
539 534 elif IP_rc.logfile:
540 535 IP.magic_logstart(IP_rc.logfile)
541 536 elif IP_rc.log:
542 537 IP.magic_logstart()
543 538
544 539 # find user editor so that it we don't have to look it up constantly
545 540 if IP_rc.editor.strip()=='0':
546 541 try:
547 542 ed = os.environ['EDITOR']
548 543 except KeyError:
549 544 if os.name == 'posix':
550 545 ed = 'vi' # the only one guaranteed to be there!
551 546 else:
552 547 ed = 'notepad' # same in Windows!
553 548 IP_rc.editor = ed
554 549
555 550 # Keep track of whether this is an embedded instance or not (useful for
556 551 # post-mortems).
557 552 IP_rc.embedded = IP.embedded
558 553
559 554 # Recursive reload
560 555 try:
561 556 from IPython import deep_reload
562 557 if IP_rc.deep_reload:
563 558 __builtin__.reload = deep_reload.reload
564 559 else:
565 560 __builtin__.dreload = deep_reload.reload
566 561 del deep_reload
567 562 except ImportError:
568 563 pass
569 564
570 565 # Save the current state of our namespace so that the interactive shell
571 566 # can later know which variables have been created by us from config files
572 567 # and loading. This way, loading a file (in any way) is treated just like
573 568 # defining things on the command line, and %who works as expected.
574 569
575 570 # DON'T do anything that affects the namespace beyond this point!
576 571 IP.internal_ns.update(__main__.__dict__)
577 572
578 573 #IP.internal_ns.update(locals()) # so our stuff doesn't show up in %who
579 574
580 575 # Now run through the different sections of the users's config
581 576 if IP_rc.debug:
582 577 print 'Trying to execute the following configuration structure:'
583 578 print '(Things listed first are deeper in the inclusion tree and get'
584 579 print 'loaded first).\n'
585 580 pprint(IP_rc.__dict__)
586 581
587 582 for mod in IP_rc.import_mod:
588 583 try:
589 584 exec 'import '+mod in IP.user_ns
590 585 except :
591 586 IP.InteractiveTB()
592 587 import_fail_info(mod)
593 588
594 589 for mod_fn in IP_rc.import_some:
595 590 if not mod_fn == []:
596 591 mod,fn = mod_fn[0],','.join(mod_fn[1:])
597 592 try:
598 593 exec 'from '+mod+' import '+fn in IP.user_ns
599 594 except :
600 595 IP.InteractiveTB()
601 596 import_fail_info(mod,fn)
602 597
603 598 for mod in IP_rc.import_all:
604 599 try:
605 600 exec 'from '+mod+' import *' in IP.user_ns
606 601 except :
607 602 IP.InteractiveTB()
608 603 import_fail_info(mod)
609 604
610 605 for code in IP_rc.execute:
611 606 try:
612 607 exec code in IP.user_ns
613 608 except:
614 609 IP.InteractiveTB()
615 610 warn('Failure executing code: ' + `code`)
616 611
617 612 # Execute the files the user wants in ipythonrc
618 613 for file in IP_rc.execfile:
619 614 try:
620 615 file = filefind(file,sys.path+[IPython_dir])
621 616 except IOError:
622 617 warn(itpl('File $file not found. Skipping it.'))
623 618 else:
624 619 IP.safe_execfile(os.path.expanduser(file),IP.user_ns)
625 620
626 621 # finally, try importing ipy_*_conf for final configuration
627 622 try:
628 623 import ipy_system_conf
629 624 except ImportError:
630 625 if opts_all.debug: IP.InteractiveTB()
631 626 warn("Could not import 'ipy_system_conf'")
632 627 except:
633 628 IP.InteractiveTB()
634 629 import_fail_info('ipy_system_conf')
635 630
636 631 # only import prof module if ipythonrc-PROF was not found
637 632 if opts_all.profile and not profile_handled_by_legacy:
638 633 profmodname = 'ipy_profile_' + opts_all.profile
639 634 try:
640 635
641 636 force_import(profmodname)
642 637 except:
643 638 IP.InteractiveTB()
644 639 print "Error importing",profmodname,"- perhaps you should run %upgrade?"
645 640 import_fail_info(profmodname)
646 641 else:
647 642 opts.profile = opts_all.profile
648 643 else:
649 644 force_import('ipy_profile_none')
650 645 try:
651 646
652 647 force_import('ipy_user_conf')
653 648
654 649 except:
655 650 conf = opts_all.ipythondir + "/ipy_user_conf.py"
656 651 IP.InteractiveTB()
657 652 if not os.path.isfile(conf):
658 653 warn(conf + ' does not exist, please run %upgrade!')
659 654
660 655 import_fail_info("ipy_user_conf")
661 656
662 657 # Define the history file for saving commands in between sessions
663 658 try:
664 659 histfname = 'history-%s' % opts.profile
665 660 except AttributeError:
666 661 histfname = 'history'
667 662 IP.histfile = os.path.join(opts_all.ipythondir,histfname)
668 663
669 664 # finally, push the argv to options again to ensure highest priority
670 665 IP_rc.update(opts)
671 666
672 667 # release stdout and stderr and save config log into a global summary
673 668 msg.config.release_all()
674 669 if IP_rc.messages:
675 670 msg.summary += msg.config.summary_all()
676 671
677 672 #------------------------------------------------------------------------
678 673 # Setup interactive session
679 674
680 675 # Now we should be fully configured. We can then execute files or load
681 676 # things only needed for interactive use. Then we'll open the shell.
682 677
683 678 # Take a snapshot of the user namespace before opening the shell. That way
684 679 # we'll be able to identify which things were interactively defined and
685 680 # which were defined through config files.
686 681 IP.user_config_ns.update(IP.user_ns)
687 682
688 683 # Force reading a file as if it were a session log. Slower but safer.
689 684 if load_logplay:
690 685 print 'Replaying log...'
691 686 try:
692 687 if IP_rc.debug:
693 688 logplay_quiet = 0
694 689 else:
695 690 logplay_quiet = 1
696 691
697 692 msg.logplay.trap_all()
698 693 IP.safe_execfile(load_logplay,IP.user_ns,
699 694 islog = 1, quiet = logplay_quiet)
700 695 msg.logplay.release_all()
701 696 if IP_rc.messages:
702 697 msg.summary += msg.logplay.summary_all()
703 698 except:
704 699 warn('Problems replaying logfile %s.' % load_logplay)
705 700 IP.InteractiveTB()
706 701
707 702 # Load remaining files in command line
708 703 msg.user_exec.trap_all()
709 704
710 705 # Do NOT execute files named in the command line as scripts to be loaded
711 706 # by embedded instances. Doing so has the potential for an infinite
712 707 # recursion if there are exceptions thrown in the process.
713 708
714 709 # XXX FIXME: the execution of user files should be moved out to after
715 710 # ipython is fully initialized, just as if they were run via %run at the
716 711 # ipython prompt. This would also give them the benefit of ipython's
717 712 # nice tracebacks.
718 713
719 714 if (not embedded and IP_rc.args and
720 715 not IP_rc.args[0].lower().endswith('.ipy')):
721 716 name_save = IP.user_ns['__name__']
722 717 IP.user_ns['__name__'] = '__main__'
723 718 # Set our own excepthook in case the user code tries to call it
724 719 # directly. This prevents triggering the IPython crash handler.
725 720 old_excepthook,sys.excepthook = sys.excepthook, IP.excepthook
726 721
727 722 save_argv = sys.argv[1:] # save it for later restoring
728 723
729 724 sys.argv = args
730 725
731 726 try:
732 727 IP.safe_execfile(args[0], IP.user_ns)
733 728 finally:
734 729 # Reset our crash handler in place
735 730 sys.excepthook = old_excepthook
736 731 sys.argv[:] = save_argv
737 732 IP.user_ns['__name__'] = name_save
738 733
739 734 msg.user_exec.release_all()
740 735
741 736 if IP_rc.messages:
742 737 msg.summary += msg.user_exec.summary_all()
743 738
744 739 # since we can't specify a null string on the cmd line, 0 is the equivalent:
745 740 if IP_rc.nosep:
746 741 IP_rc.separate_in = IP_rc.separate_out = IP_rc.separate_out2 = '0'
747 742 if IP_rc.separate_in == '0': IP_rc.separate_in = ''
748 743 if IP_rc.separate_out == '0': IP_rc.separate_out = ''
749 744 if IP_rc.separate_out2 == '0': IP_rc.separate_out2 = ''
750 745 IP_rc.separate_in = IP_rc.separate_in.replace('\\n','\n')
751 746 IP_rc.separate_out = IP_rc.separate_out.replace('\\n','\n')
752 747 IP_rc.separate_out2 = IP_rc.separate_out2.replace('\\n','\n')
753 748
754 749 # Determine how many lines at the bottom of the screen are needed for
755 750 # showing prompts, so we can know wheter long strings are to be printed or
756 751 # paged:
757 752 num_lines_bot = IP_rc.separate_in.count('\n')+1
758 753 IP_rc.screen_length = IP_rc.screen_length - num_lines_bot
759 754
760 755 # configure startup banner
761 756 if IP_rc.c: # regular python doesn't print the banner with -c
762 757 IP_rc.banner = 0
763 758 if IP_rc.banner:
764 759 BANN_P = IP.BANNER_PARTS
765 760 else:
766 761 BANN_P = []
767 762
768 763 if IP_rc.profile: BANN_P.append('IPython profile: %s\n' % IP_rc.profile)
769 764
770 765 # add message log (possibly empty)
771 766 if msg.summary: BANN_P.append(msg.summary)
772 767 # Final banner is a string
773 768 IP.BANNER = '\n'.join(BANN_P)
774 769
775 770 # Finalize the IPython instance. This assumes the rc structure is fully
776 771 # in place.
777 772 IP.post_config_initialization()
778 773
779 774 return IP
780 775 #************************ end of file <ipmaker.py> **************************
@@ -1,244 +1,254 b''
1 1 """Decorators for labeling test objects.
2 2
3 3 Decorators that merely return a modified version of the original function
4 4 object are straightforward. Decorators that return a new function object need
5 5 to use nose.tools.make_decorator(original_function)(decorator) in returning the
6 6 decorator, in order to preserve metadata such as function name, setup and
7 7 teardown functions and so on - see nose.tools for more information.
8 8
9 9 This module provides a set of useful decorators meant to be ready to use in
10 10 your own tests. See the bottom of the file for the ready-made ones, and if you
11 11 find yourself writing a new one that may be of generic use, add it here.
12 12
13 13 NOTE: This file contains IPython-specific decorators and imports the
14 14 numpy.testing.decorators file, which we've copied verbatim. Any of our own
15 15 code will be added at the bottom if we end up extending this.
16 16 """
17 17
18 18 # Stdlib imports
19 19 import inspect
20 20 import sys
21 21
22 22 # Third-party imports
23 23
24 24 # This is Michele Simionato's decorator module, also kept verbatim.
25 25 from decorator_msim import decorator, update_wrapper
26 26
27 27 # Grab the numpy-specific decorators which we keep in a file that we
28 28 # occasionally update from upstream: decorators_numpy.py is an IDENTICAL copy
29 29 # of numpy.testing.decorators.
30 30 from decorators_numpy import *
31 31
32 32 ##############################################################################
33 33 # Local code begins
34 34
35 35 # Utility functions
36 36
37 37 def apply_wrapper(wrapper,func):
38 38 """Apply a wrapper to a function for decoration.
39 39
40 40 This mixes Michele Simionato's decorator tool with nose's make_decorator,
41 41 to apply a wrapper in a decorator so that all nose attributes, as well as
42 42 function signature and other properties, survive the decoration cleanly.
43 43 This will ensure that wrapped functions can still be well introspected via
44 44 IPython, for example.
45 45 """
46 46 import nose.tools
47 47
48 48 return decorator(wrapper,nose.tools.make_decorator(func)(wrapper))
49 49
50 50
51 51 def make_label_dec(label,ds=None):
52 52 """Factory function to create a decorator that applies one or more labels.
53 53
54 54 :Parameters:
55 55 label : string or sequence
56 56 One or more labels that will be applied by the decorator to the functions
57 57 it decorates. Labels are attributes of the decorated function with their
58 58 value set to True.
59 59
60 60 :Keywords:
61 61 ds : string
62 62 An optional docstring for the resulting decorator. If not given, a
63 63 default docstring is auto-generated.
64 64
65 65 :Returns:
66 66 A decorator.
67 67
68 68 :Examples:
69 69
70 70 A simple labeling decorator:
71 71 >>> slow = make_label_dec('slow')
72 72 >>> print slow.__doc__
73 73 Labels a test as 'slow'.
74 74
75 75 And one that uses multiple labels and a custom docstring:
76 76 >>> rare = make_label_dec(['slow','hard'],
77 77 ... "Mix labels 'slow' and 'hard' for rare tests.")
78 78 >>> print rare.__doc__
79 79 Mix labels 'slow' and 'hard' for rare tests.
80 80
81 81 Now, let's test using this one:
82 82 >>> @rare
83 83 ... def f(): pass
84 84 ...
85 85 >>>
86 86 >>> f.slow
87 87 True
88 88 >>> f.hard
89 89 True
90 90 """
91 91
92 92 if isinstance(label,basestring):
93 93 labels = [label]
94 94 else:
95 95 labels = label
96 96
97 97 # Validate that the given label(s) are OK for use in setattr() by doing a
98 98 # dry run on a dummy function.
99 99 tmp = lambda : None
100 100 for label in labels:
101 101 setattr(tmp,label,True)
102 102
103 103 # This is the actual decorator we'll return
104 104 def decor(f):
105 105 for label in labels:
106 106 setattr(f,label,True)
107 107 return f
108 108
109 109 # Apply the user's docstring, or autogenerate a basic one
110 110 if ds is None:
111 111 ds = "Labels a test as %r." % label
112 112 decor.__doc__ = ds
113 113
114 114 return decor
115 115
116 116
117 117 # Inspired by numpy's skipif, but uses the full apply_wrapper utility to
118 118 # preserve function metadata better and allows the skip condition to be a
119 119 # callable.
120 120 def skipif(skip_condition, msg=None):
121 121 ''' Make function raise SkipTest exception if skip_condition is true
122 122
123 123 Parameters
124 124 ----------
125 125 skip_condition : bool or callable.
126 126 Flag to determine whether to skip test. If the condition is a
127 127 callable, it is used at runtime to dynamically make the decision. This
128 128 is useful for tests that may require costly imports, to delay the cost
129 129 until the test suite is actually executed.
130 130 msg : string
131 131 Message to give on raising a SkipTest exception
132 132
133 133 Returns
134 134 -------
135 135 decorator : function
136 136 Decorator, which, when applied to a function, causes SkipTest
137 137 to be raised when the skip_condition was True, and the function
138 138 to be called normally otherwise.
139 139
140 140 Notes
141 141 -----
142 142 You will see from the code that we had to further decorate the
143 143 decorator with the nose.tools.make_decorator function in order to
144 144 transmit function name, and various other metadata.
145 145 '''
146 146
147 147 def skip_decorator(f):
148 148 # Local import to avoid a hard nose dependency and only incur the
149 149 # import time overhead at actual test-time.
150 150 import nose
151 151
152 152 # Allow for both boolean or callable skip conditions.
153 153 if callable(skip_condition):
154 154 skip_val = lambda : skip_condition()
155 155 else:
156 156 skip_val = lambda : skip_condition
157 157
158 158 def get_msg(func,msg=None):
159 159 """Skip message with information about function being skipped."""
160 160 if msg is None: out = 'Test skipped due to test condition.'
161 161 else: out = msg
162 162 return "Skipping test: %s. %s" % (func.__name__,out)
163 163
164 164 # We need to define *two* skippers because Python doesn't allow both
165 165 # return with value and yield inside the same function.
166 166 def skipper_func(*args, **kwargs):
167 167 """Skipper for normal test functions."""
168 168 if skip_val():
169 169 raise nose.SkipTest(get_msg(f,msg))
170 170 else:
171 171 return f(*args, **kwargs)
172 172
173 173 def skipper_gen(*args, **kwargs):
174 174 """Skipper for test generators."""
175 175 if skip_val():
176 176 raise nose.SkipTest(get_msg(f,msg))
177 177 else:
178 178 for x in f(*args, **kwargs):
179 179 yield x
180 180
181 181 # Choose the right skipper to use when building the actual generator.
182 182 if nose.util.isgenerator(f):
183 183 skipper = skipper_gen
184 184 else:
185 185 skipper = skipper_func
186 186
187 187 return nose.tools.make_decorator(f)(skipper)
188 188
189 189 return skip_decorator
190 190
191 191 # A version with the condition set to true, common case just to attacha message
192 192 # to a skip decorator
193 193 def skip(msg=None):
194 194 """Decorator factory - mark a test function for skipping from test suite.
195 195
196 196 :Parameters:
197 197 msg : string
198 198 Optional message to be added.
199 199
200 200 :Returns:
201 201 decorator : function
202 202 Decorator, which, when applied to a function, causes SkipTest
203 203 to be raised, with the optional message added.
204 204 """
205 205
206 206 return skipif(True,msg)
207 207
208 208
209 209 #-----------------------------------------------------------------------------
210 210 # Utility functions for decorators
211 211 def numpy_not_available():
212 212 """Can numpy be imported? Returns true if numpy does NOT import.
213 213
214 214 This is used to make a decorator to skip tests that require numpy to be
215 215 available, but delay the 'import numpy' to test execution time.
216 216 """
217 217 try:
218 218 import numpy
219 219 np_not_avail = False
220 220 except ImportError:
221 221 np_not_avail = True
222 222
223 223 return np_not_avail
224 224
225 225 #-----------------------------------------------------------------------------
226 226 # Decorators for public use
227 227
228 228 skip_doctest = make_label_dec('skip_doctest',
229 229 """Decorator - mark a function or method for skipping its doctest.
230 230
231 231 This decorator allows you to mark a function whose docstring you wish to
232 232 omit from testing, while preserving the docstring for introspection, help,
233 233 etc.""")
234 234
235 235 # Decorators to skip certain tests on specific platforms.
236 skip_win32 = skipif(sys.platform=='win32',
236 skip_win32 = skipif(sys.platform == 'win32',
237 237 "This test does not run under Windows")
238 skip_linux = skipif(sys.platform=='linux2',"This test does not run under Linux")
239 skip_osx = skipif(sys.platform=='darwin',"This test does not run under OS X")
238 skip_linux = skipif(sys.platform == 'linux2',
239 "This test does not run under Linux")
240 skip_osx = skipif(sys.platform == 'darwin',"This test does not run under OS X")
240 241
241 242
243 # Decorators to skip tests if not on specific platforms.
244 skip_if_not_win32 = skipif(sys.platform != 'win32',
245 "This test only runs under Windows")
246 skip_if_not_linux = skipif(sys.platform != 'linux2',
247 "This test only runs under Linux")
248 skip_if_not_osx = skipif(sys.platform != 'darwin',
249 "This test only runs under OSX")
250
251 # Other skip decorators
242 252 skipif_not_numpy = skipif(numpy_not_available,"This test requires numpy")
243 253
244 254 skipknownfailure = skip('This test is known to fail')
@@ -1,32 +1,291 b''
1 1 # encoding: utf-8
2 2
3 3 """Tests for genutils.py"""
4 4
5 5 __docformat__ = "restructuredtext en"
6 6
7 7 #-----------------------------------------------------------------------------
8 8 # Copyright (C) 2008 The IPython Development Team
9 9 #
10 10 # Distributed under the terms of the BSD License. The full license is in
11 11 # the file COPYING, distributed as part of this software.
12 12 #-----------------------------------------------------------------------------
13 13
14 14 #-----------------------------------------------------------------------------
15 15 # Imports
16 16 #-----------------------------------------------------------------------------
17 17
18 # stdlib
19 import os
20 import shutil
21 import sys
22 import tempfile
23
24 from os.path import join, abspath, split
25
26 # third-party
27 import nose.tools as nt
28
29 from nose import with_setup
30 from nose.tools import raises
31
32 # Our own
33 import IPython
18 34 from IPython import genutils
35 from IPython.testing.decorators import skipif, skip_if_not_win32
36
37 # Platform-dependent imports
38 try:
39 import _winreg as wreg
40 except ImportError:
41 #Fake _winreg module on none windows platforms
42 import new
43 sys.modules["_winreg"] = new.module("_winreg")
44 import _winreg as wreg
45 #Add entries that needs to be stubbed by the testing code
46 (wreg.OpenKey, wreg.QueryValueEx,) = (None, None)
47
48 #-----------------------------------------------------------------------------
49 # Globals
50 #-----------------------------------------------------------------------------
51 env = os.environ
52 TEST_FILE_PATH = split(abspath(__file__))[0]
53 TMP_TEST_DIR = tempfile.mkdtemp()
54 HOME_TEST_DIR = join(TMP_TEST_DIR, "home_test_dir")
55 IP_TEST_DIR = join(HOME_TEST_DIR,'_ipython')
56 #
57 # Setup/teardown functions/decorators
58 #
59
60 def setup():
61 """Setup testenvironment for the module:
62
63 - Adds dummy home dir tree
64 """
65 # Do not mask exceptions here. In particular, catching WindowsError is a
66 # problem because that exception is only defined on Windows...
67 os.makedirs(IP_TEST_DIR)
68
69 def teardown():
70 """Teardown testenvironment for the module:
71
72 - Remove dummy home dir tree
73 """
74 # Note: we remove the parent test dir, which is the root of all test
75 # subdirs we may have created. Use shutil instead of os.removedirs, so
76 # that non-empty directories are all recursively removed.
77 shutil.rmtree(TMP_TEST_DIR)
78
79
80 def setup_environment():
81 """Setup testenvironment for some functions that are tested
82 in this module. In particular this functions stores attributes
83 and other things that we need to stub in some test functions.
84 This needs to be done on a function level and not module level because
85 each testfunction needs a pristine environment.
86 """
87 global oldstuff, platformstuff
88 oldstuff = (env.copy(), os.name, genutils.get_home_dir, IPython.__file__,)
89
90 if os.name == 'nt':
91 platformstuff = (wreg.OpenKey, wreg.QueryValueEx,)
92
93 if 'IPYTHONDIR' in env:
94 del env['IPYTHONDIR']
95
96 def teardown_environment():
97 """Restore things that were remebered by the setup_environment function
98 """
99 (oldenv, os.name, genutils.get_home_dir, IPython.__file__,) = oldstuff
100 for key in env.keys():
101 if key not in oldenv:
102 del env[key]
103 env.update(oldenv)
104 if hasattr(sys, 'frozen'):
105 del sys.frozen
106 if os.name == 'nt':
107 (wreg.OpenKey, wreg.QueryValueEx,) = platformstuff
108
109 # Build decorator that uses the setup_environment/setup_environment
110 with_enivronment = with_setup(setup_environment, teardown_environment)
111
112
113 #
114 # Tests for get_home_dir
115 #
116
117 @skip_if_not_win32
118 @with_enivronment
119 def test_get_home_dir_1():
120 """Testcase for py2exe logic, un-compressed lib
121 """
122 sys.frozen = True
123
124 #fake filename for IPython.__init__
125 IPython.__file__ = abspath(join(HOME_TEST_DIR, "Lib/IPython/__init__.py"))
126
127 home_dir = genutils.get_home_dir()
128 nt.assert_equal(home_dir, abspath(HOME_TEST_DIR))
129
130 @skip_if_not_win32
131 @with_enivronment
132 def test_get_home_dir_2():
133 """Testcase for py2exe logic, compressed lib
134 """
135 sys.frozen = True
136 #fake filename for IPython.__init__
137 IPython.__file__ = abspath(join(HOME_TEST_DIR, "Library.zip/IPython/__init__.py")).lower()
138
139 home_dir = genutils.get_home_dir()
140 nt.assert_equal(home_dir, abspath(HOME_TEST_DIR).lower())
141
142 @with_enivronment
143 def test_get_home_dir_3():
144 """Testcase $HOME is set, then use its value as home directory."""
145 env["HOME"] = HOME_TEST_DIR
146 home_dir = genutils.get_home_dir()
147 nt.assert_equal(home_dir, env["HOME"])
148
149 @with_enivronment
150 def test_get_home_dir_4():
151 """Testcase $HOME is not set, os=='poix'.
152 This should fail with HomeDirError"""
153
154 os.name = 'posix'
155 if 'HOME' in env: del env['HOME']
156 nt.assert_raises(genutils.HomeDirError, genutils.get_home_dir)
157
158 @skip_if_not_win32
159 @with_enivronment
160 def test_get_home_dir_5():
161 """Testcase $HOME is not set, os=='nt'
162 env['HOMEDRIVE'],env['HOMEPATH'] points to path."""
163
164 os.name = 'nt'
165 if 'HOME' in env: del env['HOME']
166 env['HOMEDRIVE'], env['HOMEPATH'] = os.path.splitdrive(HOME_TEST_DIR)
19 167
168 home_dir = genutils.get_home_dir()
169 nt.assert_equal(home_dir, abspath(HOME_TEST_DIR))
170
171 @skip_if_not_win32
172 @with_enivronment
173 def test_get_home_dir_6():
174 """Testcase $HOME is not set, os=='nt'
175 env['HOMEDRIVE'],env['HOMEPATH'] do not point to path.
176 env['USERPROFILE'] points to path
177 """
178
179 os.name = 'nt'
180 if 'HOME' in env: del env['HOME']
181 env['HOMEDRIVE'], env['HOMEPATH'] = os.path.abspath(TEST_FILE_PATH), "DOES NOT EXIST"
182 env["USERPROFILE"] = abspath(HOME_TEST_DIR)
183
184 home_dir = genutils.get_home_dir()
185 nt.assert_equal(home_dir, abspath(HOME_TEST_DIR))
186
187 # Should we stub wreg fully so we can run the test on all platforms?
188 @skip_if_not_win32
189 @with_enivronment
190 def test_get_home_dir_7():
191 """Testcase $HOME is not set, os=='nt'
192 env['HOMEDRIVE'],env['HOMEPATH'], env['USERPROFILE'] missing
193 """
194 os.name = 'nt'
195 if 'HOME' in env: del env['HOME']
196 if 'HOMEDRIVE' in env: del env['HOMEDRIVE']
197
198 #Stub windows registry functions
199 def OpenKey(x, y):
200 class key:
201 def Close(self):
202 pass
203 return key()
204 def QueryValueEx(x, y):
205 return [abspath(HOME_TEST_DIR)]
206
207 wreg.OpenKey = OpenKey
208 wreg.QueryValueEx = QueryValueEx
20 209
21 def test_get_home_dir():
22 """Make sure we can get the home directory."""
23 210 home_dir = genutils.get_home_dir()
211 nt.assert_equal(home_dir, abspath(HOME_TEST_DIR))
212
213
214 #
215 # Tests for get_ipython_dir
216 #
217
218 @with_enivronment
219 def test_get_ipython_dir_1():
220 """test_get_ipython_dir_1, Testcase to see if we can call get_ipython_dir without Exceptions."""
221 env['IPYTHONDIR'] = "someplace/.ipython"
222 ipdir = genutils.get_ipython_dir()
223 nt.assert_equal(ipdir, os.path.abspath("someplace/.ipython"))
24 224
25 def test_get_ipython_dir():
26 """Make sure we can get the ipython directory."""
225
226 @with_enivronment
227 def test_get_ipython_dir_2():
228 """test_get_ipython_dir_2, Testcase to see if we can call get_ipython_dir without Exceptions."""
229 genutils.get_home_dir = lambda : "someplace"
230 os.name = "posix"
231 ipdir = genutils.get_ipython_dir()
232 nt.assert_equal(ipdir, os.path.abspath(os.path.join("someplace", ".ipython")))
233
234 @with_enivronment
235 def test_get_ipython_dir_3():
236 """test_get_ipython_dir_3, Testcase to see if we can call get_ipython_dir without Exceptions."""
237 genutils.get_home_dir = lambda : "someplace"
238 os.name = "nt"
27 239 ipdir = genutils.get_ipython_dir()
240 nt.assert_equal(ipdir, os.path.abspath(os.path.join("someplace", "_ipython")))
241
242
243 #
244 # Tests for get_security_dir
245 #
28 246
247 @with_enivronment
29 248 def test_get_security_dir():
30 """Make sure we can get the ipython/security directory."""
249 """Testcase to see if we can call get_security_dir without Exceptions."""
31 250 sdir = genutils.get_security_dir()
32 No newline at end of file
251
252
253 #
254 # Tests for popkey
255 #
256
257 def test_popkey_1():
258 """test_popkey_1, Basic usage test of popkey
259 """
260 dct = dict(a=1, b=2, c=3)
261 nt.assert_equal(genutils.popkey(dct, "a"), 1)
262 nt.assert_equal(dct, dict(b=2, c=3))
263 nt.assert_equal(genutils.popkey(dct, "b"), 2)
264 nt.assert_equal(dct, dict(c=3))
265 nt.assert_equal(genutils.popkey(dct, "c"), 3)
266 nt.assert_equal(dct, dict())
267
268 def test_popkey_2():
269 """test_popkey_2, Test to see that popkey of non occuring keys
270 generates a KeyError exception
271 """
272 dct = dict(a=1, b=2, c=3)
273 nt.assert_raises(KeyError, genutils.popkey, dct, "d")
274
275 def test_popkey_3():
276 """test_popkey_3, Tests to see that popkey calls returns the correct value
277 and that the key/value was removed from the dict.
278 """
279 dct = dict(a=1, b=2, c=3)
280 nt.assert_equal(genutils.popkey(dct, "A", 13), 13)
281 nt.assert_equal(dct, dict(a=1, b=2, c=3))
282 nt.assert_equal(genutils.popkey(dct, "B", 14), 14)
283 nt.assert_equal(dct, dict(a=1, b=2, c=3))
284 nt.assert_equal(genutils.popkey(dct, "C", 15), 15)
285 nt.assert_equal(dct, dict(a=1, b=2, c=3))
286 nt.assert_equal(genutils.popkey(dct, "a"), 1)
287 nt.assert_equal(dct, dict(b=2, c=3))
288 nt.assert_equal(genutils.popkey(dct, "b"), 2)
289 nt.assert_equal(dct, dict(c=3))
290 nt.assert_equal(genutils.popkey(dct, "c"), 3)
291 nt.assert_equal(dct, dict())
@@ -1,345 +1,358 b''
1 1 .. _development:
2 2
3 3 ==============================
4 4 IPython development guidelines
5 5 ==============================
6 6
7 7
8 8 Overview
9 9 ========
10 10
11 11 This document describes IPython from the perspective of developers. Most
12 12 importantly, it gives information for people who want to contribute to the
13 13 development of IPython. So if you want to help out, read on!
14 14
15 15 How to contribute to IPython
16 16 ============================
17 17
18 18 IPython development is done using Bazaar [Bazaar]_ and Launchpad [Launchpad]_.
19 19 This makes it easy for people to contribute to the development of IPython.
20 20 Here is a sketch of how to get going.
21 21
22 22 Install Bazaar and create a Launchpad account
23 23 ---------------------------------------------
24 24
25 25 First make sure you have installed Bazaar (see their `website
26 26 <http://bazaar-vcs.org/>`_). To see that Bazaar is installed and knows about
27 27 you, try the following::
28 28
29 29 $ bzr whoami
30 30 Joe Coder <jcoder@gmail.com>
31 31
32 32 This should display your name and email. Next, you will want to create an
33 33 account on the `Launchpad website <http://www.launchpad.net>`_ and setup your
34 34 ssh keys. For more information of setting up your ssh keys, see `this link
35 35 <https://help.launchpad.net/YourAccount/CreatingAnSSHKeyPair>`_.
36 36
37 37 Get the main IPython branch from Launchpad
38 38 ------------------------------------------
39 39
40 40 Now, you can get a copy of the main IPython development branch (we call this
41 41 the "trunk")::
42 42
43 43 $ bzr branch lp:ipython
44 44
45 45 Create a working branch
46 46 -----------------------
47 47
48 48 When working on IPython, you won't actually make edits directly to the
49 49 :file:`lp:ipython` branch. Instead, you will create a separate branch for your
50 50 changes. For now, let's assume you want to do your work in a branch named
51 51 "ipython-mybranch". Create this branch by doing::
52 52
53 53 $ bzr branch ipython ipython-mybranch
54 54
55 55 When you actually create a branch, you will want to give it a name that
56 56 reflects the nature of the work that you will be doing in it, like
57 57 "install-docs-update".
58 58
59 59 Make edits in your working branch
60 60 ---------------------------------
61 61
62 62 Now you are ready to actually make edits in your :file:`ipython-mybranch`
63 63 branch. Before doing this, it is helpful to install this branch so you can
64 64 test your changes as you work. This is easiest if you have setuptools
65 65 installed. Then, just do::
66 66
67 67 $ cd ipython-mybranch
68 68 $ python setupegg.py develop
69 69
70 70 Now, make some changes. After a while, you will want to commit your changes.
71 71 This let's Bazaar know that you like the changes you have made and gives you
72 72 an opportunity to keep a nice record of what you have done. This looks like
73 73 this::
74 74
75 75 $ ...do work in ipython-mybranch...
76 76 $ bzr commit -m "the commit message goes here"
77 77
78 78 Please note that since we now don't use an old-style linear ChangeLog (that
79 79 tends to cause problems with distributed version control systems), you should
80 80 ensure that your log messages are reasonably detailed. Use a docstring-like
81 81 approach in the commit messages (including the second line being left
82 82 *blank*)::
83 83
84 84 Single line summary of changes being committed.
85 85
86 86 * more details when warranted ...
87 87 * including crediting outside contributors if they sent the
88 88 code/bug/idea!
89 89
90 90 As you work, you will repeat this edit/commit cycle many times. If you work on
91 91 your branch for a long time, you will also want to get the latest changes from
92 92 the :file:`lp:ipython` branch. This can be done with the following sequence of
93 93 commands::
94 94
95 95 $ ls
96 96 ipython
97 97 ipython-mybranch
98 98
99 99 $ cd ipython
100 100 $ bzr pull
101 101 $ cd ../ipython-mybranch
102 102 $ bzr merge ../ipython
103 103 $ bzr commit -m "Merging changes from trunk"
104 104
105 105 Along the way, you should also run the IPython test suite. You can do this using the :command:`iptest` command::
106 106
107 107 $ cd
108 108 $ iptest
109 109
110 110 The :command:`iptest` command will also pick up and run any tests you have written.
111 111
112 112 Post your branch and request a code review
113 113 ------------------------------------------
114 114
115 115 Once you are done with your edits, you should post your branch on Launchpad so
116 116 that other IPython developers can review the changes and help you merge your
117 117 changes into the main development branch. To post your branch on Launchpad,
118 118 do::
119 119
120 120 $ cd ipython-mybranch
121 121 $ bzr push lp:~yourusername/ipython/ipython-mybranch
122 122
123 123 Then, go to the `IPython Launchpad site <www.launchpad.net/ipython>`_, and you
124 124 should see your branch under the "Code" tab. If you click on your branch, you
125 125 can provide a short description of the branch as well as mark its status. Most
126 126 importantly, you should click the link that reads "Propose for merging into
127 127 another branch". What does this do?
128 128
129 129 This let's the other IPython developers know that your branch is ready to be
130 130 reviewed and merged into the main development branch. During this review
131 131 process, other developers will give you feedback and help you get your code
132 132 ready to be merged. What types of things will we be looking for:
133 133
134 134 * All code is documented.
135 135 * All code has tests.
136 136 * The entire IPython test suite passes.
137 137
138 138 Once your changes have been reviewed and approved, someone will merge them
139 139 into the main development branch.
140 140
141 141 Documentation
142 142 =============
143 143
144 144 Standalone documentation
145 145 ------------------------
146 146
147 147 All standalone documentation should be written in plain text (``.txt``) files
148 148 using reStructuredText [reStructuredText]_ for markup and formatting. All such
149 149 documentation should be placed in directory :file:`docs/source` of the IPython
150 150 source tree. The documentation in this location will serve as the main source
151 151 for IPython documentation and all existing documentation should be converted
152 152 to this format.
153 153
154 154 To build the final documentation, we use Sphinx [Sphinx]_. Once you have Sphinx installed, you can build the html docs yourself by doing::
155 155
156 156 $ cd ipython-mybranch/docs
157 157 $ make html
158 158
159 159 Docstring format
160 160 ----------------
161 161
162 162 Good docstrings are very important. All new code should have docstrings that
163 163 are formatted using reStructuredText for markup and formatting, since it is
164 164 understood by a wide variety of tools. Details about using reStructuredText
165 165 for docstrings can be found `here
166 166 <http://epydoc.sourceforge.net/manual-othermarkup.html>`_.
167 167
168 168 Additional PEPs of interest regarding documentation of code:
169 169
170 170 * `Docstring Conventions <http://www.python.org/peps/pep-0257.html>`_
171 171 * `Docstring Processing System Framework <http://www.python.org/peps/pep-0256.html>`_
172 172 * `Docutils Design Specification <http://www.python.org/peps/pep-0258.html>`_
173 173
174 174
175 175 Coding conventions
176 176 ==================
177 177
178 178 General
179 179 -------
180 180
181 181 In general, we'll try to follow the standard Python style conventions as
182 182 described here:
183 183
184 184 * `Style Guide for Python Code <http://www.python.org/peps/pep-0008.html>`_
185 185
186 186
187 187 Other comments:
188 188
189 189 * In a large file, top level classes and functions should be
190 190 separated by 2-3 lines to make it easier to separate them visually.
191 191 * Use 4 spaces for indentation.
192 192 * Keep the ordering of methods the same in classes that have the same
193 193 methods. This is particularly true for classes that implement an interface.
194 194
195 195 Naming conventions
196 196 ------------------
197 197
198 198 In terms of naming conventions, we'll follow the guidelines from the `Style
199 199 Guide for Python Code`_.
200 200
201 201 For all new IPython code (and much existing code is being refactored), we'll
202 202 use:
203 203
204 204 * All ``lowercase`` module names.
205 205
206 206 * ``CamelCase`` for class names.
207 207
208 208 * ``lowercase_with_underscores`` for methods, functions, variables and
209 209 attributes.
210 210
211 211 There are, however, some important exceptions to these rules. In some cases,
212 212 IPython code will interface with packages (Twisted, Wx, Qt) that use other
213 213 conventions. At some level this makes it impossible to adhere to our own
214 214 standards at all times. In particular, when subclassing classes that use other
215 215 naming conventions, you must follow their naming conventions. To deal with
216 216 cases like this, we propose the following policy:
217 217
218 218 * If you are subclassing a class that uses different conventions, use its
219 219 naming conventions throughout your subclass. Thus, if you are creating a
220 220 Twisted Protocol class, used Twisted's
221 221 ``namingSchemeForMethodsAndAttributes.``
222 222
223 223 * All IPython's official interfaces should use our conventions. In some cases
224 224 this will mean that you need to provide shadow names (first implement
225 225 ``fooBar`` and then ``foo_bar = fooBar``). We want to avoid this at all
226 226 costs, but it will probably be necessary at times. But, please use this
227 227 sparingly!
228 228
229 229 Implementation-specific *private* methods will use
230 230 ``_single_underscore_prefix``. Names with a leading double underscore will
231 231 *only* be used in special cases, as they makes subclassing difficult (such
232 232 names are not easily seen by child classes).
233 233
234 234 Occasionally some run-in lowercase names are used, but mostly for very short
235 235 names or where we are implementing methods very similar to existing ones in a
236 236 base class (like ``runlines()`` where ``runsource()`` and ``runcode()`` had
237 237 established precedent).
238 238
239 239 The old IPython codebase has a big mix of classes and modules prefixed with an
240 240 explicit ``IP``. In Python this is mostly unnecessary, redundant and frowned
241 241 upon, as namespaces offer cleaner prefixing. The only case where this approach
242 242 is justified is for classes which are expected to be imported into external
243 243 namespaces and a very generic name (like Shell) is too likely to clash with
244 244 something else. We'll need to revisit this issue as we clean up and refactor
245 245 the code, but in general we should remove as many unnecessary ``IP``/``ip``
246 246 prefixes as possible. However, if a prefix seems absolutely necessary the more
247 247 specific ``IPY`` or ``ipy`` are preferred.
248 248
249 249 .. _devel_testing:
250 250
251 251 Testing system
252 252 ==============
253 253
254 254 It is extremely important that all code contributed to IPython has tests.
255 255 Tests should be written as unittests, doctests or as entities that the Nose
256 256 [Nose]_ testing package will find. Regardless of how the tests are written, we
257 257 will use Nose for discovering and running the tests. Nose will be required to
258 258 run the IPython test suite, but will not be required to simply use IPython.
259 259
260 260 Tests of Twisted using code need to follow two additional guidelines:
261 261
262 262 1. Twisted using tests should be written by subclassing the :class:`TestCase`
263 263 class that comes with :mod:`twisted.trial.unittest`.
264 264
265 265 2. All :class:`Deferred` instances that are created in the test must be
266 266 properly chained and the final one *must* be the return value of the test
267 267 method.
268 268
269 269 When these two things are done, Nose will be able to run the tests and the
270 270 twisted reactor will be handled correctly.
271 271
272 272 Each subpackage in IPython should have its own :file:`tests` directory that
273 273 contains all of the tests for that subpackage. This allows each subpackage to
274 274 be self-contained. If a subpackage has any dependencies beyond the Python
275 275 standard library, the tests for that subpackage should be skipped if the
276 276 dependencies are not found. This is very important so users don't get tests
277 277 failing simply because they don't have dependencies.
278 278
279 279 To run the IPython test suite, use the :command:`iptest` command that is
280 280 installed with IPython::
281 281
282 282 $ iptest
283 283
284 284 This command runs Nose with the proper options and extensions.
285 285
286 286 A few tips for writing tests:
287 287
288 288 * You can use IPython examples in your docstrings, including all IPython
289 289 prompts. Rather than repeating it all here, see the files
290 290 :file:`dtexample.py` and :file:`test_ipdoctest.py` in the
291 291 :mod:`IPython.testing.plugin` module for examples of how you can use plain
292 292 Python or IPython prompts, and what to do with examples whose output could be
293 293 partly or completely random.
294 294
295 295 * Use the decorators shipped in the :mod:`IPython.testing` package to tag tests
296 296 that may be platform-specific or otherwise may have restrictions.
297 297
298 298 * If a test isn't safe to run inside the main nose process (e.g. because it
299 299 loads a GUI toolkit), consider running it in a subprocess and capturing its
300 300 output for evaluation and test decision later. Here is an example of how to
301 301 do it, by relying on the builtin ``_ip`` object that contains the public
302 302 IPython api as defined in :mod:`IPython.ipapi`::
303 303
304 304 def test_obj_del():
305 305 """Test that object's __del__ methods are called on exit."""
306 306 test_dir = os.path.dirname(__file__)
307 307 del_file = os.path.join(test_dir,'obj_del.py')
308 308 out = _ip.IP.getoutput('ipython %s' % del_file)
309 309 nt.assert_equals(out,'object A deleted')
310 310
311 311
312 312 * In a file named ``test_X``, functions whose only test is their docstring (as
313 313 a doctest) and which have no test functionality of their own, should be
314 314 called *doctest_foo* instead of *test_foo*, otherwise they get double-counted
315 315 (the empty function call is counted as a test, which just inflates tests
316 316 numbers artificially). This restriction does not apply to functions in files
317 317 with other names, due to how Nose discovers tests.
318 318
319 319 .. _devel_config:
320 320
321 321 Release checklist
322 322 =================
323 323
324 324 Most of the release process is automated by the :file:`release` script in the
325 325 :file:`tools` directory. This is just a handy reminder for the release manager.
326 326
327 327 #. Run the release script, which makes the tar.gz, eggs and Win32 .exe
328 328 installer. It posts them to the site and registers the release with PyPI.
329 329
330 330 #. Updating the website with announcements and links to the updated
331 331 changes.txt in html form. Remember to put a short note both on the news
332 332 page of the site and on Launcphad.
333 333
334 334 #. Drafting a short release announcement with i) highlights and ii) a link to
335 335 the html changes.txt.
336 336
337 337 #. Make sure that the released version of the docs is live on the site.
338 338
339 339 #. Celebrate!
340 340
341 Porting to 3.0
342 ==============
343 There are no definite plans for porting of IPython to python 3. The major
344 issue is the dependency on twisted framework for the networking/threading
345 stuff. It is possible that it the traditional IPython interactive console
346 could be ported more easily since it has no such dependency. Here are a few
347 things that will need to be considered when doing such a port especially
348 if we want to have a codebase that works directly on both 2.x and 3.x.
349
350 1. The syntax for exceptions changed (PEP 3110). The old
351 `except exc, var` changed to `except exc as var`. At last
352 count there was 78 occurences of this usage in the codebase
353
341 354 .. [Bazaar] Bazaar. http://bazaar-vcs.org/
342 355 .. [Launchpad] Launchpad. http://www.launchpad.net/ipython
343 356 .. [reStructuredText] reStructuredText. http://docutils.sourceforge.net/rst.html
344 357 .. [Sphinx] Sphinx. http://sphinx.pocoo.org/
345 358 .. [Nose] Nose: a discovery based unittest extension. http://code.google.com/p/python-nose/
General Comments 0
You need to be logged in to leave comments. Login now