##// END OF EJS Templates
- Fix unicode bug in %psearch reported by Stefan.
fperez -
Show More

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

@@ -1,3101 +1,3109 b''
1 1 # -*- coding: utf-8 -*-
2 2 """Magic functions for InteractiveShell.
3 3
4 $Id: Magic.py 2187 2007-03-30 04:56:40Z fperez $"""
4 $Id: Magic.py 2190 2007-03-30 18:35:46Z fperez $"""
5 5
6 6 #*****************************************************************************
7 7 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
8 8 # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu>
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 # Modules and globals
16 16
17 17 from IPython import Release
18 18 __author__ = '%s <%s>\n%s <%s>' % \
19 19 ( Release.authors['Janko'] + Release.authors['Fernando'] )
20 20 __license__ = Release.license
21 21
22 22 # Python standard modules
23 23 import __builtin__
24 24 import bdb
25 25 import inspect
26 26 import os
27 27 import pdb
28 28 import pydoc
29 29 import sys
30 30 import re
31 31 import tempfile
32 32 import time
33 33 import cPickle as pickle
34 34 import textwrap
35 35 from cStringIO import StringIO
36 36 from getopt import getopt,GetoptError
37 37 from pprint import pprint, pformat
38 38
39 39 # cProfile was added in Python2.5
40 40 try:
41 41 import cProfile as profile
42 42 import pstats
43 43 except ImportError:
44 44 # profile isn't bundled by default in Debian for license reasons
45 45 try:
46 46 import profile,pstats
47 47 except ImportError:
48 48 profile = pstats = None
49 49
50 50 # Homebrewed
51 51 import IPython
52 52 from IPython import Debugger, OInspect, wildcard
53 53 from IPython.FakeModule import FakeModule
54 54 from IPython.Itpl import Itpl, itpl, printpl,itplns
55 55 from IPython.PyColorize import Parser
56 56 from IPython.ipstruct import Struct
57 57 from IPython.macro import Macro
58 58 from IPython.genutils import *
59 59 from IPython import platutils
60 60
61 61 #***************************************************************************
62 62 # Utility functions
63 63 def on_off(tag):
64 64 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
65 65 return ['OFF','ON'][tag]
66 66
67 67 class Bunch: pass
68 68
69 69 #***************************************************************************
70 70 # Main class implementing Magic functionality
71 71 class Magic:
72 72 """Magic functions for InteractiveShell.
73 73
74 74 Shell functions which can be reached as %function_name. All magic
75 75 functions should accept a string, which they can parse for their own
76 76 needs. This can make some functions easier to type, eg `%cd ../`
77 77 vs. `%cd("../")`
78 78
79 79 ALL definitions MUST begin with the prefix magic_. The user won't need it
80 80 at the command line, but it is is needed in the definition. """
81 81
82 82 # class globals
83 83 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
84 84 'Automagic is ON, % prefix NOT needed for magic functions.']
85 85
86 86 #......................................................................
87 87 # some utility functions
88 88
89 89 def __init__(self,shell):
90 90
91 91 self.options_table = {}
92 92 if profile is None:
93 93 self.magic_prun = self.profile_missing_notice
94 94 self.shell = shell
95 95
96 96 # namespace for holding state we may need
97 97 self._magic_state = Bunch()
98 98
99 99 def profile_missing_notice(self, *args, **kwargs):
100 100 error("""\
101 101 The profile module could not be found. If you are a Debian user,
102 102 it has been removed from the standard Debian package because of its non-free
103 103 license. To use profiling, please install"python2.3-profiler" from non-free.""")
104 104
105 105 def default_option(self,fn,optstr):
106 106 """Make an entry in the options_table for fn, with value optstr"""
107 107
108 108 if fn not in self.lsmagic():
109 109 error("%s is not a magic function" % fn)
110 110 self.options_table[fn] = optstr
111 111
112 112 def lsmagic(self):
113 113 """Return a list of currently available magic functions.
114 114
115 115 Gives a list of the bare names after mangling (['ls','cd', ...], not
116 116 ['magic_ls','magic_cd',...]"""
117 117
118 118 # FIXME. This needs a cleanup, in the way the magics list is built.
119 119
120 120 # magics in class definition
121 121 class_magic = lambda fn: fn.startswith('magic_') and \
122 122 callable(Magic.__dict__[fn])
123 123 # in instance namespace (run-time user additions)
124 124 inst_magic = lambda fn: fn.startswith('magic_') and \
125 125 callable(self.__dict__[fn])
126 126 # and bound magics by user (so they can access self):
127 127 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
128 128 callable(self.__class__.__dict__[fn])
129 129 magics = filter(class_magic,Magic.__dict__.keys()) + \
130 130 filter(inst_magic,self.__dict__.keys()) + \
131 131 filter(inst_bound_magic,self.__class__.__dict__.keys())
132 132 out = []
133 133 for fn in magics:
134 134 out.append(fn.replace('magic_','',1))
135 135 out.sort()
136 136 return out
137 137
138 138 def extract_input_slices(self,slices,raw=False):
139 139 """Return as a string a set of input history slices.
140 140
141 141 Inputs:
142 142
143 143 - slices: the set of slices is given as a list of strings (like
144 144 ['1','4:8','9'], since this function is for use by magic functions
145 145 which get their arguments as strings.
146 146
147 147 Optional inputs:
148 148
149 149 - raw(False): by default, the processed input is used. If this is
150 150 true, the raw input history is used instead.
151 151
152 152 Note that slices can be called with two notations:
153 153
154 154 N:M -> standard python form, means including items N...(M-1).
155 155
156 156 N-M -> include items N..M (closed endpoint)."""
157 157
158 158 if raw:
159 159 hist = self.shell.input_hist_raw
160 160 else:
161 161 hist = self.shell.input_hist
162 162
163 163 cmds = []
164 164 for chunk in slices:
165 165 if ':' in chunk:
166 166 ini,fin = map(int,chunk.split(':'))
167 167 elif '-' in chunk:
168 168 ini,fin = map(int,chunk.split('-'))
169 169 fin += 1
170 170 else:
171 171 ini = int(chunk)
172 172 fin = ini+1
173 173 cmds.append(hist[ini:fin])
174 174 return cmds
175 175
176 176 def _ofind(self, oname, namespaces=None):
177 177 """Find an object in the available namespaces.
178 178
179 179 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
180 180
181 181 Has special code to detect magic functions.
182 182 """
183 183
184 184 oname = oname.strip()
185 185
186 186 alias_ns = None
187 187 if namespaces is None:
188 188 # Namespaces to search in:
189 189 # Put them in a list. The order is important so that we
190 190 # find things in the same order that Python finds them.
191 191 namespaces = [ ('Interactive', self.shell.user_ns),
192 192 ('IPython internal', self.shell.internal_ns),
193 193 ('Python builtin', __builtin__.__dict__),
194 194 ('Alias', self.shell.alias_table),
195 195 ]
196 196 alias_ns = self.shell.alias_table
197 197
198 198 # initialize results to 'null'
199 199 found = 0; obj = None; ospace = None; ds = None;
200 200 ismagic = 0; isalias = 0; parent = None
201 201
202 202 # Look for the given name by splitting it in parts. If the head is
203 203 # found, then we look for all the remaining parts as members, and only
204 204 # declare success if we can find them all.
205 205 oname_parts = oname.split('.')
206 206 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
207 207 for nsname,ns in namespaces:
208 208 try:
209 209 obj = ns[oname_head]
210 210 except KeyError:
211 211 continue
212 212 else:
213 213 #print 'oname_rest:', oname_rest # dbg
214 214 for part in oname_rest:
215 215 try:
216 216 parent = obj
217 217 obj = getattr(obj,part)
218 218 except:
219 219 # Blanket except b/c some badly implemented objects
220 220 # allow __getattr__ to raise exceptions other than
221 221 # AttributeError, which then crashes IPython.
222 222 break
223 223 else:
224 224 # If we finish the for loop (no break), we got all members
225 225 found = 1
226 226 ospace = nsname
227 227 if ns == alias_ns:
228 228 isalias = 1
229 229 break # namespace loop
230 230
231 231 # Try to see if it's magic
232 232 if not found:
233 233 if oname.startswith(self.shell.ESC_MAGIC):
234 234 oname = oname[1:]
235 235 obj = getattr(self,'magic_'+oname,None)
236 236 if obj is not None:
237 237 found = 1
238 238 ospace = 'IPython internal'
239 239 ismagic = 1
240 240
241 241 # Last try: special-case some literals like '', [], {}, etc:
242 242 if not found and oname_head in ["''",'""','[]','{}','()']:
243 243 obj = eval(oname_head)
244 244 found = 1
245 245 ospace = 'Interactive'
246 246
247 247 return {'found':found, 'obj':obj, 'namespace':ospace,
248 248 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
249 249
250 250 def arg_err(self,func):
251 251 """Print docstring if incorrect arguments were passed"""
252 252 print 'Error in arguments:'
253 253 print OInspect.getdoc(func)
254 254
255 255 def format_latex(self,strng):
256 256 """Format a string for latex inclusion."""
257 257
258 258 # Characters that need to be escaped for latex:
259 259 escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
260 260 # Magic command names as headers:
261 261 cmd_name_re = re.compile(r'^(%s.*?):' % self.shell.ESC_MAGIC,
262 262 re.MULTILINE)
263 263 # Magic commands
264 264 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % self.shell.ESC_MAGIC,
265 265 re.MULTILINE)
266 266 # Paragraph continue
267 267 par_re = re.compile(r'\\$',re.MULTILINE)
268 268
269 269 # The "\n" symbol
270 270 newline_re = re.compile(r'\\n')
271 271
272 272 # Now build the string for output:
273 273 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
274 274 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
275 275 strng)
276 276 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
277 277 strng = par_re.sub(r'\\\\',strng)
278 278 strng = escape_re.sub(r'\\\1',strng)
279 279 strng = newline_re.sub(r'\\textbackslash{}n',strng)
280 280 return strng
281 281
282 282 def format_screen(self,strng):
283 283 """Format a string for screen printing.
284 284
285 285 This removes some latex-type format codes."""
286 286 # Paragraph continue
287 287 par_re = re.compile(r'\\$',re.MULTILINE)
288 288 strng = par_re.sub('',strng)
289 289 return strng
290 290
291 291 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
292 292 """Parse options passed to an argument string.
293 293
294 294 The interface is similar to that of getopt(), but it returns back a
295 295 Struct with the options as keys and the stripped argument string still
296 296 as a string.
297 297
298 298 arg_str is quoted as a true sys.argv vector by using shlex.split.
299 299 This allows us to easily expand variables, glob files, quote
300 300 arguments, etc.
301 301
302 302 Options:
303 303 -mode: default 'string'. If given as 'list', the argument string is
304 304 returned as a list (split on whitespace) instead of a string.
305 305
306 306 -list_all: put all option values in lists. Normally only options
307 307 appearing more than once are put in a list.
308 308
309 309 -posix (True): whether to split the input line in POSIX mode or not,
310 310 as per the conventions outlined in the shlex module from the
311 311 standard library."""
312 312
313 313 # inject default options at the beginning of the input line
314 314 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
315 315 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
316 316
317 317 mode = kw.get('mode','string')
318 318 if mode not in ['string','list']:
319 319 raise ValueError,'incorrect mode given: %s' % mode
320 320 # Get options
321 321 list_all = kw.get('list_all',0)
322 322 posix = kw.get('posix',True)
323 323
324 324 # Check if we have more than one argument to warrant extra processing:
325 325 odict = {} # Dictionary with options
326 326 args = arg_str.split()
327 327 if len(args) >= 1:
328 328 # If the list of inputs only has 0 or 1 thing in it, there's no
329 329 # need to look for options
330 330 argv = arg_split(arg_str,posix)
331 331 # Do regular option processing
332 332 try:
333 333 opts,args = getopt(argv,opt_str,*long_opts)
334 334 except GetoptError,e:
335 335 raise GetoptError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
336 336 " ".join(long_opts)))
337 337 for o,a in opts:
338 338 if o.startswith('--'):
339 339 o = o[2:]
340 340 else:
341 341 o = o[1:]
342 342 try:
343 343 odict[o].append(a)
344 344 except AttributeError:
345 345 odict[o] = [odict[o],a]
346 346 except KeyError:
347 347 if list_all:
348 348 odict[o] = [a]
349 349 else:
350 350 odict[o] = a
351 351
352 352 # Prepare opts,args for return
353 353 opts = Struct(odict)
354 354 if mode == 'string':
355 355 args = ' '.join(args)
356 356
357 357 return opts,args
358 358
359 359 #......................................................................
360 360 # And now the actual magic functions
361 361
362 362 # Functions for IPython shell work (vars,funcs, config, etc)
363 363 def magic_lsmagic(self, parameter_s = ''):
364 364 """List currently available magic functions."""
365 365 mesc = self.shell.ESC_MAGIC
366 366 print 'Available magic functions:\n'+mesc+\
367 367 (' '+mesc).join(self.lsmagic())
368 368 print '\n' + Magic.auto_status[self.shell.rc.automagic]
369 369 return None
370 370
371 371 def magic_magic(self, parameter_s = ''):
372 372 """Print information about the magic function system."""
373 373
374 374 mode = ''
375 375 try:
376 376 if parameter_s.split()[0] == '-latex':
377 377 mode = 'latex'
378 378 if parameter_s.split()[0] == '-brief':
379 379 mode = 'brief'
380 380 except:
381 381 pass
382 382
383 383 magic_docs = []
384 384 for fname in self.lsmagic():
385 385 mname = 'magic_' + fname
386 386 for space in (Magic,self,self.__class__):
387 387 try:
388 388 fn = space.__dict__[mname]
389 389 except KeyError:
390 390 pass
391 391 else:
392 392 break
393 393 if mode == 'brief':
394 394 # only first line
395 395 fndoc = fn.__doc__.split('\n',1)[0]
396 396 else:
397 397 fndoc = fn.__doc__
398 398
399 399 magic_docs.append('%s%s:\n\t%s\n' %(self.shell.ESC_MAGIC,
400 400 fname,fndoc))
401 401 magic_docs = ''.join(magic_docs)
402 402
403 403 if mode == 'latex':
404 404 print self.format_latex(magic_docs)
405 405 return
406 406 else:
407 407 magic_docs = self.format_screen(magic_docs)
408 408 if mode == 'brief':
409 409 return magic_docs
410 410
411 411 outmsg = """
412 412 IPython's 'magic' functions
413 413 ===========================
414 414
415 415 The magic function system provides a series of functions which allow you to
416 416 control the behavior of IPython itself, plus a lot of system-type
417 417 features. All these functions are prefixed with a % character, but parameters
418 418 are given without parentheses or quotes.
419 419
420 420 NOTE: If you have 'automagic' enabled (via the command line option or with the
421 421 %automagic function), you don't need to type in the % explicitly. By default,
422 422 IPython ships with automagic on, so you should only rarely need the % escape.
423 423
424 424 Example: typing '%cd mydir' (without the quotes) changes you working directory
425 425 to 'mydir', if it exists.
426 426
427 427 You can define your own magic functions to extend the system. See the supplied
428 428 ipythonrc and example-magic.py files for details (in your ipython
429 429 configuration directory, typically $HOME/.ipython/).
430 430
431 431 You can also define your own aliased names for magic functions. In your
432 432 ipythonrc file, placing a line like:
433 433
434 434 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
435 435
436 436 will define %pf as a new name for %profile.
437 437
438 438 You can also call magics in code using the ipmagic() function, which IPython
439 439 automatically adds to the builtin namespace. Type 'ipmagic?' for details.
440 440
441 441 For a list of the available magic functions, use %lsmagic. For a description
442 442 of any of them, type %magic_name?, e.g. '%cd?'.
443 443
444 444 Currently the magic system has the following functions:\n"""
445 445
446 446 mesc = self.shell.ESC_MAGIC
447 447 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
448 448 "\n\n%s%s\n\n%s" % (outmsg,
449 449 magic_docs,mesc,mesc,
450 450 (' '+mesc).join(self.lsmagic()),
451 451 Magic.auto_status[self.shell.rc.automagic] ) )
452 452
453 453 page(outmsg,screen_lines=self.shell.rc.screen_length)
454 454
455 455 def magic_automagic(self, parameter_s = ''):
456 456 """Make magic functions callable without having to type the initial %.
457 457
458 458 Without argumentsl toggles on/off (when off, you must call it as
459 459 %automagic, of course). With arguments it sets the value, and you can
460 460 use any of (case insensitive):
461 461
462 462 - on,1,True: to activate
463 463
464 464 - off,0,False: to deactivate.
465 465
466 466 Note that magic functions have lowest priority, so if there's a
467 467 variable whose name collides with that of a magic fn, automagic won't
468 468 work for that function (you get the variable instead). However, if you
469 469 delete the variable (del var), the previously shadowed magic function
470 470 becomes visible to automagic again."""
471 471
472 472 rc = self.shell.rc
473 473 arg = parameter_s.lower()
474 474 if parameter_s in ('on','1','true'):
475 475 rc.automagic = True
476 476 elif parameter_s in ('off','0','false'):
477 477 rc.automagic = False
478 478 else:
479 479 rc.automagic = not rc.automagic
480 480 print '\n' + Magic.auto_status[rc.automagic]
481 481
482 482 def magic_autocall(self, parameter_s = ''):
483 483 """Make functions callable without having to type parentheses.
484 484
485 485 Usage:
486 486
487 487 %autocall [mode]
488 488
489 489 The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
490 490 value is toggled on and off (remembering the previous state)."""
491 491
492 492 rc = self.shell.rc
493 493
494 494 if parameter_s:
495 495 arg = int(parameter_s)
496 496 else:
497 497 arg = 'toggle'
498 498
499 499 if not arg in (0,1,2,'toggle'):
500 500 error('Valid modes: (0->Off, 1->Smart, 2->Full')
501 501 return
502 502
503 503 if arg in (0,1,2):
504 504 rc.autocall = arg
505 505 else: # toggle
506 506 if rc.autocall:
507 507 self._magic_state.autocall_save = rc.autocall
508 508 rc.autocall = 0
509 509 else:
510 510 try:
511 511 rc.autocall = self._magic_state.autocall_save
512 512 except AttributeError:
513 513 rc.autocall = self._magic_state.autocall_save = 1
514 514
515 515 print "Automatic calling is:",['OFF','Smart','Full'][rc.autocall]
516 516
517 517 def magic_autoindent(self, parameter_s = ''):
518 518 """Toggle autoindent on/off (if available)."""
519 519
520 520 self.shell.set_autoindent()
521 521 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
522 522
523 523 def magic_system_verbose(self, parameter_s = ''):
524 524 """Set verbose printing of system calls.
525 525
526 526 If called without an argument, act as a toggle"""
527 527
528 528 if parameter_s:
529 529 val = bool(eval(parameter_s))
530 530 else:
531 531 val = None
532 532
533 533 self.shell.rc_set_toggle('system_verbose',val)
534 534 print "System verbose printing is:",\
535 535 ['OFF','ON'][self.shell.rc.system_verbose]
536 536
537 537 def magic_history(self, parameter_s = ''):
538 538 """Print input history (_i<n> variables), with most recent last.
539 539
540 540 %history -> print at most 40 inputs (some may be multi-line)\\
541 541 %history n -> print at most n inputs\\
542 542 %history n1 n2 -> print inputs between n1 and n2 (n2 not included)\\
543 543
544 544 Each input's number <n> is shown, and is accessible as the
545 545 automatically generated variable _i<n>. Multi-line statements are
546 546 printed starting at a new line for easy copy/paste.
547 547
548 548
549 549 Options:
550 550
551 551 -n: do NOT print line numbers. This is useful if you want to get a
552 552 printout of many lines which can be directly pasted into a text
553 553 editor.
554 554
555 555 This feature is only available if numbered prompts are in use.
556 556
557 557 -r: print the 'raw' history. IPython filters your input and
558 558 converts it all into valid Python source before executing it (things
559 559 like magics or aliases are turned into function calls, for
560 560 example). With this option, you'll see the unfiltered history
561 561 instead of the filtered version: '%cd /' will be seen as '%cd /'
562 562 instead of '_ip.magic("%cd /")'.
563 563 """
564 564
565 565 shell = self.shell
566 566 if not shell.outputcache.do_full_cache:
567 567 print 'This feature is only available if numbered prompts are in use.'
568 568 return
569 569 opts,args = self.parse_options(parameter_s,'nr',mode='list')
570 570
571 571 if opts.has_key('r'):
572 572 input_hist = shell.input_hist_raw
573 573 else:
574 574 input_hist = shell.input_hist
575 575
576 576 default_length = 40
577 577 if len(args) == 0:
578 578 final = len(input_hist)
579 579 init = max(1,final-default_length)
580 580 elif len(args) == 1:
581 581 final = len(input_hist)
582 582 init = max(1,final-int(args[0]))
583 583 elif len(args) == 2:
584 584 init,final = map(int,args)
585 585 else:
586 586 warn('%hist takes 0, 1 or 2 arguments separated by spaces.')
587 587 print self.magic_hist.__doc__
588 588 return
589 589 width = len(str(final))
590 590 line_sep = ['','\n']
591 591 print_nums = not opts.has_key('n')
592 592 for in_num in range(init,final):
593 593 inline = input_hist[in_num]
594 594 multiline = int(inline.count('\n') > 1)
595 595 if print_nums:
596 596 print '%s:%s' % (str(in_num).ljust(width),line_sep[multiline]),
597 597 print inline,
598 598
599 599 def magic_hist(self, parameter_s=''):
600 600 """Alternate name for %history."""
601 601 return self.magic_history(parameter_s)
602 602
603 603 def magic_p(self, parameter_s=''):
604 604 """Just a short alias for Python's 'print'."""
605 605 exec 'print ' + parameter_s in self.shell.user_ns
606 606
607 607 def magic_r(self, parameter_s=''):
608 608 """Repeat previous input.
609 609
610 610 If given an argument, repeats the previous command which starts with
611 611 the same string, otherwise it just repeats the previous input.
612 612
613 613 Shell escaped commands (with ! as first character) are not recognized
614 614 by this system, only pure python code and magic commands.
615 615 """
616 616
617 617 start = parameter_s.strip()
618 618 esc_magic = self.shell.ESC_MAGIC
619 619 # Identify magic commands even if automagic is on (which means
620 620 # the in-memory version is different from that typed by the user).
621 621 if self.shell.rc.automagic:
622 622 start_magic = esc_magic+start
623 623 else:
624 624 start_magic = start
625 625 # Look through the input history in reverse
626 626 for n in range(len(self.shell.input_hist)-2,0,-1):
627 627 input = self.shell.input_hist[n]
628 628 # skip plain 'r' lines so we don't recurse to infinity
629 629 if input != '_ip.magic("r")\n' and \
630 630 (input.startswith(start) or input.startswith(start_magic)):
631 631 #print 'match',`input` # dbg
632 632 print 'Executing:',input,
633 633 self.shell.runlines(input)
634 634 return
635 635 print 'No previous input matching `%s` found.' % start
636 636
637 637 def magic_page(self, parameter_s=''):
638 638 """Pretty print the object and display it through a pager.
639 639
640 640 %page [options] OBJECT
641 641
642 642 If no object is given, use _ (last output).
643 643
644 644 Options:
645 645
646 646 -r: page str(object), don't pretty-print it."""
647 647
648 648 # After a function contributed by Olivier Aubert, slightly modified.
649 649
650 650 # Process options/args
651 651 opts,args = self.parse_options(parameter_s,'r')
652 652 raw = 'r' in opts
653 653
654 654 oname = args and args or '_'
655 655 info = self._ofind(oname)
656 656 if info['found']:
657 657 txt = (raw and str or pformat)( info['obj'] )
658 658 page(txt)
659 659 else:
660 660 print 'Object `%s` not found' % oname
661 661
662 662 def magic_profile(self, parameter_s=''):
663 663 """Print your currently active IPyhton profile."""
664 664 if self.shell.rc.profile:
665 665 printpl('Current IPython profile: $self.shell.rc.profile.')
666 666 else:
667 667 print 'No profile active.'
668 668
669 669 def _inspect(self,meth,oname,namespaces=None,**kw):
670 670 """Generic interface to the inspector system.
671 671
672 672 This function is meant to be called by pdef, pdoc & friends."""
673 673
674 #oname = oname.strip()
675 #print '1- oname: <%r>' % oname # dbg
674 676 try:
675 677 oname = oname.strip().encode('ascii')
678 #print '2- oname: <%r>' % oname # dbg
676 679 except UnicodeEncodeError:
677 680 print 'Python identifiers can only contain ascii characters.'
678 681 return 'not found'
679 682
680 683 info = Struct(self._ofind(oname, namespaces))
681 684
682 685 if info.found:
683 686 # Get the docstring of the class property if it exists.
684 687 path = oname.split('.')
685 688 root = '.'.join(path[:-1])
686 689 if info.parent is not None:
687 690 try:
688 691 target = getattr(info.parent, '__class__')
689 692 # The object belongs to a class instance.
690 693 try:
691 694 target = getattr(target, path[-1])
692 695 # The class defines the object.
693 696 if isinstance(target, property):
694 697 oname = root + '.__class__.' + path[-1]
695 698 info = Struct(self._ofind(oname))
696 699 except AttributeError: pass
697 700 except AttributeError: pass
698 701
699 702 pmethod = getattr(self.shell.inspector,meth)
700 703 formatter = info.ismagic and self.format_screen or None
701 704 if meth == 'pdoc':
702 705 pmethod(info.obj,oname,formatter)
703 706 elif meth == 'pinfo':
704 707 pmethod(info.obj,oname,formatter,info,**kw)
705 708 else:
706 709 pmethod(info.obj,oname)
707 710 else:
708 711 print 'Object `%s` not found.' % oname
709 712 return 'not found' # so callers can take other action
710 713
711 714 def magic_pdef(self, parameter_s='', namespaces=None):
712 715 """Print the definition header for any callable object.
713 716
714 717 If the object is a class, print the constructor information."""
715 718 self._inspect('pdef',parameter_s, namespaces)
716 719
717 720 def magic_pdoc(self, parameter_s='', namespaces=None):
718 721 """Print the docstring for an object.
719 722
720 723 If the given object is a class, it will print both the class and the
721 724 constructor docstrings."""
722 725 self._inspect('pdoc',parameter_s, namespaces)
723 726
724 727 def magic_psource(self, parameter_s='', namespaces=None):
725 728 """Print (or run through pager) the source code for an object."""
726 729 self._inspect('psource',parameter_s, namespaces)
727 730
728 731 def magic_pfile(self, parameter_s=''):
729 732 """Print (or run through pager) the file where an object is defined.
730 733
731 734 The file opens at the line where the object definition begins. IPython
732 735 will honor the environment variable PAGER if set, and otherwise will
733 736 do its best to print the file in a convenient form.
734 737
735 738 If the given argument is not an object currently defined, IPython will
736 739 try to interpret it as a filename (automatically adding a .py extension
737 740 if needed). You can thus use %pfile as a syntax highlighting code
738 741 viewer."""
739 742
740 743 # first interpret argument as an object name
741 744 out = self._inspect('pfile',parameter_s)
742 745 # if not, try the input as a filename
743 746 if out == 'not found':
744 747 try:
745 748 filename = get_py_filename(parameter_s)
746 749 except IOError,msg:
747 750 print msg
748 751 return
749 752 page(self.shell.inspector.format(file(filename).read()))
750 753
751 754 def magic_pinfo(self, parameter_s='', namespaces=None):
752 755 """Provide detailed information about an object.
753 756
754 757 '%pinfo object' is just a synonym for object? or ?object."""
755 758
756 759 #print 'pinfo par: <%s>' % parameter_s # dbg
757 760
758 761 # detail_level: 0 -> obj? , 1 -> obj??
759 762 detail_level = 0
760 763 # We need to detect if we got called as 'pinfo pinfo foo', which can
761 764 # happen if the user types 'pinfo foo?' at the cmd line.
762 765 pinfo,qmark1,oname,qmark2 = \
763 766 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
764 767 if pinfo or qmark1 or qmark2:
765 768 detail_level = 1
766 769 if "*" in oname:
767 770 self.magic_psearch(oname)
768 771 else:
769 772 self._inspect('pinfo', oname, detail_level=detail_level,
770 773 namespaces=namespaces)
771 774
772 775 def magic_psearch(self, parameter_s=''):
773 776 """Search for object in namespaces by wildcard.
774 777
775 778 %psearch [options] PATTERN [OBJECT TYPE]
776 779
777 780 Note: ? can be used as a synonym for %psearch, at the beginning or at
778 781 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
779 782 rest of the command line must be unchanged (options come first), so
780 783 for example the following forms are equivalent
781 784
782 785 %psearch -i a* function
783 786 -i a* function?
784 787 ?-i a* function
785 788
786 789 Arguments:
787 790
788 791 PATTERN
789 792
790 793 where PATTERN is a string containing * as a wildcard similar to its
791 794 use in a shell. The pattern is matched in all namespaces on the
792 795 search path. By default objects starting with a single _ are not
793 796 matched, many IPython generated objects have a single
794 797 underscore. The default is case insensitive matching. Matching is
795 798 also done on the attributes of objects and not only on the objects
796 799 in a module.
797 800
798 801 [OBJECT TYPE]
799 802
800 803 Is the name of a python type from the types module. The name is
801 804 given in lowercase without the ending type, ex. StringType is
802 805 written string. By adding a type here only objects matching the
803 806 given type are matched. Using all here makes the pattern match all
804 807 types (this is the default).
805 808
806 809 Options:
807 810
808 811 -a: makes the pattern match even objects whose names start with a
809 812 single underscore. These names are normally ommitted from the
810 813 search.
811 814
812 815 -i/-c: make the pattern case insensitive/sensitive. If neither of
813 816 these options is given, the default is read from your ipythonrc
814 817 file. The option name which sets this value is
815 818 'wildcards_case_sensitive'. If this option is not specified in your
816 819 ipythonrc file, IPython's internal default is to do a case sensitive
817 820 search.
818 821
819 822 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
820 823 specifiy can be searched in any of the following namespaces:
821 824 'builtin', 'user', 'user_global','internal', 'alias', where
822 825 'builtin' and 'user' are the search defaults. Note that you should
823 826 not use quotes when specifying namespaces.
824 827
825 828 'Builtin' contains the python module builtin, 'user' contains all
826 829 user data, 'alias' only contain the shell aliases and no python
827 830 objects, 'internal' contains objects used by IPython. The
828 831 'user_global' namespace is only used by embedded IPython instances,
829 832 and it contains module-level globals. You can add namespaces to the
830 833 search with -s or exclude them with -e (these options can be given
831 834 more than once).
832 835
833 836 Examples:
834 837
835 838 %psearch a* -> objects beginning with an a
836 839 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
837 840 %psearch a* function -> all functions beginning with an a
838 841 %psearch re.e* -> objects beginning with an e in module re
839 842 %psearch r*.e* -> objects that start with e in modules starting in r
840 843 %psearch r*.* string -> all strings in modules beginning with r
841 844
842 845 Case sensitve search:
843 846
844 847 %psearch -c a* list all object beginning with lower case a
845 848
846 849 Show objects beginning with a single _:
847 850
848 851 %psearch -a _* list objects beginning with a single underscore"""
852 try:
853 parameter_s = parameter_s.encode('ascii')
854 except UnicodeEncodeError:
855 print 'Python identifiers can only contain ascii characters.'
856 return
849 857
850 858 # default namespaces to be searched
851 859 def_search = ['user','builtin']
852 860
853 861 # Process options/args
854 862 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
855 863 opt = opts.get
856 864 shell = self.shell
857 865 psearch = shell.inspector.psearch
858
866
859 867 # select case options
860 868 if opts.has_key('i'):
861 869 ignore_case = True
862 870 elif opts.has_key('c'):
863 871 ignore_case = False
864 872 else:
865 873 ignore_case = not shell.rc.wildcards_case_sensitive
866 874
867 875 # Build list of namespaces to search from user options
868 876 def_search.extend(opt('s',[]))
869 877 ns_exclude = ns_exclude=opt('e',[])
870 878 ns_search = [nm for nm in def_search if nm not in ns_exclude]
871 879
872 880 # Call the actual search
873 881 try:
874 882 psearch(args,shell.ns_table,ns_search,
875 883 show_all=opt('a'),ignore_case=ignore_case)
876 884 except:
877 885 shell.showtraceback()
878 886
879 887 def magic_who_ls(self, parameter_s=''):
880 888 """Return a sorted list of all interactive variables.
881 889
882 890 If arguments are given, only variables of types matching these
883 891 arguments are returned."""
884 892
885 893 user_ns = self.shell.user_ns
886 894 internal_ns = self.shell.internal_ns
887 895 user_config_ns = self.shell.user_config_ns
888 896 out = []
889 897 typelist = parameter_s.split()
890 898
891 899 for i in user_ns:
892 900 if not (i.startswith('_') or i.startswith('_i')) \
893 901 and not (i in internal_ns or i in user_config_ns):
894 902 if typelist:
895 903 if type(user_ns[i]).__name__ in typelist:
896 904 out.append(i)
897 905 else:
898 906 out.append(i)
899 907 out.sort()
900 908 return out
901 909
902 910 def magic_who(self, parameter_s=''):
903 911 """Print all interactive variables, with some minimal formatting.
904 912
905 913 If any arguments are given, only variables whose type matches one of
906 914 these are printed. For example:
907 915
908 916 %who function str
909 917
910 918 will only list functions and strings, excluding all other types of
911 919 variables. To find the proper type names, simply use type(var) at a
912 920 command line to see how python prints type names. For example:
913 921
914 922 In [1]: type('hello')\\
915 923 Out[1]: <type 'str'>
916 924
917 925 indicates that the type name for strings is 'str'.
918 926
919 927 %who always excludes executed names loaded through your configuration
920 928 file and things which are internal to IPython.
921 929
922 930 This is deliberate, as typically you may load many modules and the
923 931 purpose of %who is to show you only what you've manually defined."""
924 932
925 933 varlist = self.magic_who_ls(parameter_s)
926 934 if not varlist:
927 935 print 'Interactive namespace is empty.'
928 936 return
929 937
930 938 # if we have variables, move on...
931 939
932 940 # stupid flushing problem: when prompts have no separators, stdout is
933 941 # getting lost. I'm starting to think this is a python bug. I'm having
934 942 # to force a flush with a print because even a sys.stdout.flush
935 943 # doesn't seem to do anything!
936 944
937 945 count = 0
938 946 for i in varlist:
939 947 print i+'\t',
940 948 count += 1
941 949 if count > 8:
942 950 count = 0
943 951 print
944 952 sys.stdout.flush() # FIXME. Why the hell isn't this flushing???
945 953
946 954 print # well, this does force a flush at the expense of an extra \n
947 955
948 956 def magic_whos(self, parameter_s=''):
949 957 """Like %who, but gives some extra information about each variable.
950 958
951 959 The same type filtering of %who can be applied here.
952 960
953 961 For all variables, the type is printed. Additionally it prints:
954 962
955 963 - For {},[],(): their length.
956 964
957 965 - For Numeric arrays, a summary with shape, number of elements,
958 966 typecode and size in memory.
959 967
960 968 - Everything else: a string representation, snipping their middle if
961 969 too long."""
962 970
963 971 varnames = self.magic_who_ls(parameter_s)
964 972 if not varnames:
965 973 print 'Interactive namespace is empty.'
966 974 return
967 975
968 976 # if we have variables, move on...
969 977
970 978 # for these types, show len() instead of data:
971 979 seq_types = [types.DictType,types.ListType,types.TupleType]
972 980
973 981 # for Numeric arrays, display summary info
974 982 try:
975 983 import Numeric
976 984 except ImportError:
977 985 array_type = None
978 986 else:
979 987 array_type = Numeric.ArrayType.__name__
980 988
981 989 # Find all variable names and types so we can figure out column sizes
982 990
983 991 def get_vars(i):
984 992 return self.shell.user_ns[i]
985 993
986 994 # some types are well known and can be shorter
987 995 abbrevs = {'IPython.macro.Macro' : 'Macro'}
988 996 def type_name(v):
989 997 tn = type(v).__name__
990 998 return abbrevs.get(tn,tn)
991 999
992 1000 varlist = map(get_vars,varnames)
993 1001
994 1002 typelist = []
995 1003 for vv in varlist:
996 1004 tt = type_name(vv)
997 1005
998 1006 if tt=='instance':
999 1007 typelist.append( abbrevs.get(str(vv.__class__),str(vv.__class__)))
1000 1008 else:
1001 1009 typelist.append(tt)
1002 1010
1003 1011 # column labels and # of spaces as separator
1004 1012 varlabel = 'Variable'
1005 1013 typelabel = 'Type'
1006 1014 datalabel = 'Data/Info'
1007 1015 colsep = 3
1008 1016 # variable format strings
1009 1017 vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
1010 1018 vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
1011 1019 aformat = "%s: %s elems, type `%s`, %s bytes"
1012 1020 # find the size of the columns to format the output nicely
1013 1021 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
1014 1022 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
1015 1023 # table header
1016 1024 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
1017 1025 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
1018 1026 # and the table itself
1019 1027 kb = 1024
1020 1028 Mb = 1048576 # kb**2
1021 1029 for vname,var,vtype in zip(varnames,varlist,typelist):
1022 1030 print itpl(vformat),
1023 1031 if vtype in seq_types:
1024 1032 print len(var)
1025 1033 elif vtype==array_type:
1026 1034 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
1027 1035 vsize = Numeric.size(var)
1028 1036 vbytes = vsize*var.itemsize()
1029 1037 if vbytes < 100000:
1030 1038 print aformat % (vshape,vsize,var.typecode(),vbytes)
1031 1039 else:
1032 1040 print aformat % (vshape,vsize,var.typecode(),vbytes),
1033 1041 if vbytes < Mb:
1034 1042 print '(%s kb)' % (vbytes/kb,)
1035 1043 else:
1036 1044 print '(%s Mb)' % (vbytes/Mb,)
1037 1045 else:
1038 1046 vstr = str(var).replace('\n','\\n')
1039 1047 if len(vstr) < 50:
1040 1048 print vstr
1041 1049 else:
1042 1050 printpl(vfmt_short)
1043 1051
1044 1052 def magic_reset(self, parameter_s=''):
1045 1053 """Resets the namespace by removing all names defined by the user.
1046 1054
1047 1055 Input/Output history are left around in case you need them."""
1048 1056
1049 1057 ans = self.shell.ask_yes_no(
1050 1058 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")
1051 1059 if not ans:
1052 1060 print 'Nothing done.'
1053 1061 return
1054 1062 user_ns = self.shell.user_ns
1055 1063 for i in self.magic_who_ls():
1056 1064 del(user_ns[i])
1057 1065
1058 1066 def magic_logstart(self,parameter_s=''):
1059 1067 """Start logging anywhere in a session.
1060 1068
1061 1069 %logstart [-o|-r|-t] [log_name [log_mode]]
1062 1070
1063 1071 If no name is given, it defaults to a file named 'ipython_log.py' in your
1064 1072 current directory, in 'rotate' mode (see below).
1065 1073
1066 1074 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
1067 1075 history up to that point and then continues logging.
1068 1076
1069 1077 %logstart takes a second optional parameter: logging mode. This can be one
1070 1078 of (note that the modes are given unquoted):\\
1071 1079 append: well, that says it.\\
1072 1080 backup: rename (if exists) to name~ and start name.\\
1073 1081 global: single logfile in your home dir, appended to.\\
1074 1082 over : overwrite existing log.\\
1075 1083 rotate: create rotating logs name.1~, name.2~, etc.
1076 1084
1077 1085 Options:
1078 1086
1079 1087 -o: log also IPython's output. In this mode, all commands which
1080 1088 generate an Out[NN] prompt are recorded to the logfile, right after
1081 1089 their corresponding input line. The output lines are always
1082 1090 prepended with a '#[Out]# ' marker, so that the log remains valid
1083 1091 Python code.
1084 1092
1085 1093 Since this marker is always the same, filtering only the output from
1086 1094 a log is very easy, using for example a simple awk call:
1087 1095
1088 1096 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
1089 1097
1090 1098 -r: log 'raw' input. Normally, IPython's logs contain the processed
1091 1099 input, so that user lines are logged in their final form, converted
1092 1100 into valid Python. For example, %Exit is logged as
1093 1101 '_ip.magic("Exit"). If the -r flag is given, all input is logged
1094 1102 exactly as typed, with no transformations applied.
1095 1103
1096 1104 -t: put timestamps before each input line logged (these are put in
1097 1105 comments)."""
1098 1106
1099 1107 opts,par = self.parse_options(parameter_s,'ort')
1100 1108 log_output = 'o' in opts
1101 1109 log_raw_input = 'r' in opts
1102 1110 timestamp = 't' in opts
1103 1111
1104 1112 rc = self.shell.rc
1105 1113 logger = self.shell.logger
1106 1114
1107 1115 # if no args are given, the defaults set in the logger constructor by
1108 1116 # ipytohn remain valid
1109 1117 if par:
1110 1118 try:
1111 1119 logfname,logmode = par.split()
1112 1120 except:
1113 1121 logfname = par
1114 1122 logmode = 'backup'
1115 1123 else:
1116 1124 logfname = logger.logfname
1117 1125 logmode = logger.logmode
1118 1126 # put logfname into rc struct as if it had been called on the command
1119 1127 # line, so it ends up saved in the log header Save it in case we need
1120 1128 # to restore it...
1121 1129 old_logfile = rc.opts.get('logfile','')
1122 1130 if logfname:
1123 1131 logfname = os.path.expanduser(logfname)
1124 1132 rc.opts.logfile = logfname
1125 1133 loghead = self.shell.loghead_tpl % (rc.opts,rc.args)
1126 1134 try:
1127 1135 started = logger.logstart(logfname,loghead,logmode,
1128 1136 log_output,timestamp,log_raw_input)
1129 1137 except:
1130 1138 rc.opts.logfile = old_logfile
1131 1139 warn("Couldn't start log: %s" % sys.exc_info()[1])
1132 1140 else:
1133 1141 # log input history up to this point, optionally interleaving
1134 1142 # output if requested
1135 1143
1136 1144 if timestamp:
1137 1145 # disable timestamping for the previous history, since we've
1138 1146 # lost those already (no time machine here).
1139 1147 logger.timestamp = False
1140 1148
1141 1149 if log_raw_input:
1142 1150 input_hist = self.shell.input_hist_raw
1143 1151 else:
1144 1152 input_hist = self.shell.input_hist
1145 1153
1146 1154 if log_output:
1147 1155 log_write = logger.log_write
1148 1156 output_hist = self.shell.output_hist
1149 1157 for n in range(1,len(input_hist)-1):
1150 1158 log_write(input_hist[n].rstrip())
1151 1159 if n in output_hist:
1152 1160 log_write(repr(output_hist[n]),'output')
1153 1161 else:
1154 1162 logger.log_write(input_hist[1:])
1155 1163 if timestamp:
1156 1164 # re-enable timestamping
1157 1165 logger.timestamp = True
1158 1166
1159 1167 print ('Activating auto-logging. '
1160 1168 'Current session state plus future input saved.')
1161 1169 logger.logstate()
1162 1170
1163 1171 def magic_logoff(self,parameter_s=''):
1164 1172 """Temporarily stop logging.
1165 1173
1166 1174 You must have previously started logging."""
1167 1175 self.shell.logger.switch_log(0)
1168 1176
1169 1177 def magic_logon(self,parameter_s=''):
1170 1178 """Restart logging.
1171 1179
1172 1180 This function is for restarting logging which you've temporarily
1173 1181 stopped with %logoff. For starting logging for the first time, you
1174 1182 must use the %logstart function, which allows you to specify an
1175 1183 optional log filename."""
1176 1184
1177 1185 self.shell.logger.switch_log(1)
1178 1186
1179 1187 def magic_logstate(self,parameter_s=''):
1180 1188 """Print the status of the logging system."""
1181 1189
1182 1190 self.shell.logger.logstate()
1183 1191
1184 1192 def magic_pdb(self, parameter_s=''):
1185 1193 """Control the automatic calling of the pdb interactive debugger.
1186 1194
1187 1195 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1188 1196 argument it works as a toggle.
1189 1197
1190 1198 When an exception is triggered, IPython can optionally call the
1191 1199 interactive pdb debugger after the traceback printout. %pdb toggles
1192 1200 this feature on and off.
1193 1201
1194 1202 The initial state of this feature is set in your ipythonrc
1195 1203 configuration file (the variable is called 'pdb').
1196 1204
1197 1205 If you want to just activate the debugger AFTER an exception has fired,
1198 1206 without having to type '%pdb on' and rerunning your code, you can use
1199 1207 the %debug magic."""
1200 1208
1201 1209 par = parameter_s.strip().lower()
1202 1210
1203 1211 if par:
1204 1212 try:
1205 1213 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1206 1214 except KeyError:
1207 1215 print ('Incorrect argument. Use on/1, off/0, '
1208 1216 'or nothing for a toggle.')
1209 1217 return
1210 1218 else:
1211 1219 # toggle
1212 1220 new_pdb = not self.shell.call_pdb
1213 1221
1214 1222 # set on the shell
1215 1223 self.shell.call_pdb = new_pdb
1216 1224 print 'Automatic pdb calling has been turned',on_off(new_pdb)
1217 1225
1218 1226 def magic_debug(self, parameter_s=''):
1219 1227 """Activate the interactive debugger in post-mortem mode.
1220 1228
1221 1229 If an exception has just occurred, this lets you inspect its stack
1222 1230 frames interactively. Note that this will always work only on the last
1223 1231 traceback that occurred, so you must call this quickly after an
1224 1232 exception that you wish to inspect has fired, because if another one
1225 1233 occurs, it clobbers the previous one.
1226 1234
1227 1235 If you want IPython to automatically do this on every exception, see
1228 1236 the %pdb magic for more details.
1229 1237 """
1230 1238
1231 1239 self.shell.debugger(force=True)
1232 1240
1233 1241 def magic_prun(self, parameter_s ='',user_mode=1,
1234 1242 opts=None,arg_lst=None,prog_ns=None):
1235 1243
1236 1244 """Run a statement through the python code profiler.
1237 1245
1238 1246 Usage:\\
1239 1247 %prun [options] statement
1240 1248
1241 1249 The given statement (which doesn't require quote marks) is run via the
1242 1250 python profiler in a manner similar to the profile.run() function.
1243 1251 Namespaces are internally managed to work correctly; profile.run
1244 1252 cannot be used in IPython because it makes certain assumptions about
1245 1253 namespaces which do not hold under IPython.
1246 1254
1247 1255 Options:
1248 1256
1249 1257 -l <limit>: you can place restrictions on what or how much of the
1250 1258 profile gets printed. The limit value can be:
1251 1259
1252 1260 * A string: only information for function names containing this string
1253 1261 is printed.
1254 1262
1255 1263 * An integer: only these many lines are printed.
1256 1264
1257 1265 * A float (between 0 and 1): this fraction of the report is printed
1258 1266 (for example, use a limit of 0.4 to see the topmost 40% only).
1259 1267
1260 1268 You can combine several limits with repeated use of the option. For
1261 1269 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1262 1270 information about class constructors.
1263 1271
1264 1272 -r: return the pstats.Stats object generated by the profiling. This
1265 1273 object has all the information about the profile in it, and you can
1266 1274 later use it for further analysis or in other functions.
1267 1275
1268 1276 -s <key>: sort profile by given key. You can provide more than one key
1269 1277 by using the option several times: '-s key1 -s key2 -s key3...'. The
1270 1278 default sorting key is 'time'.
1271 1279
1272 1280 The following is copied verbatim from the profile documentation
1273 1281 referenced below:
1274 1282
1275 1283 When more than one key is provided, additional keys are used as
1276 1284 secondary criteria when the there is equality in all keys selected
1277 1285 before them.
1278 1286
1279 1287 Abbreviations can be used for any key names, as long as the
1280 1288 abbreviation is unambiguous. The following are the keys currently
1281 1289 defined:
1282 1290
1283 1291 Valid Arg Meaning\\
1284 1292 "calls" call count\\
1285 1293 "cumulative" cumulative time\\
1286 1294 "file" file name\\
1287 1295 "module" file name\\
1288 1296 "pcalls" primitive call count\\
1289 1297 "line" line number\\
1290 1298 "name" function name\\
1291 1299 "nfl" name/file/line\\
1292 1300 "stdname" standard name\\
1293 1301 "time" internal time
1294 1302
1295 1303 Note that all sorts on statistics are in descending order (placing
1296 1304 most time consuming items first), where as name, file, and line number
1297 1305 searches are in ascending order (i.e., alphabetical). The subtle
1298 1306 distinction between "nfl" and "stdname" is that the standard name is a
1299 1307 sort of the name as printed, which means that the embedded line
1300 1308 numbers get compared in an odd way. For example, lines 3, 20, and 40
1301 1309 would (if the file names were the same) appear in the string order
1302 1310 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1303 1311 line numbers. In fact, sort_stats("nfl") is the same as
1304 1312 sort_stats("name", "file", "line").
1305 1313
1306 1314 -T <filename>: save profile results as shown on screen to a text
1307 1315 file. The profile is still shown on screen.
1308 1316
1309 1317 -D <filename>: save (via dump_stats) profile statistics to given
1310 1318 filename. This data is in a format understod by the pstats module, and
1311 1319 is generated by a call to the dump_stats() method of profile
1312 1320 objects. The profile is still shown on screen.
1313 1321
1314 1322 If you want to run complete programs under the profiler's control, use
1315 1323 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1316 1324 contains profiler specific options as described here.
1317 1325
1318 1326 You can read the complete documentation for the profile module with:\\
1319 1327 In [1]: import profile; profile.help() """
1320 1328
1321 1329 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1322 1330 # protect user quote marks
1323 1331 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1324 1332
1325 1333 if user_mode: # regular user call
1326 1334 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1327 1335 list_all=1)
1328 1336 namespace = self.shell.user_ns
1329 1337 else: # called to run a program by %run -p
1330 1338 try:
1331 1339 filename = get_py_filename(arg_lst[0])
1332 1340 except IOError,msg:
1333 1341 error(msg)
1334 1342 return
1335 1343
1336 1344 arg_str = 'execfile(filename,prog_ns)'
1337 1345 namespace = locals()
1338 1346
1339 1347 opts.merge(opts_def)
1340 1348
1341 1349 prof = profile.Profile()
1342 1350 try:
1343 1351 prof = prof.runctx(arg_str,namespace,namespace)
1344 1352 sys_exit = ''
1345 1353 except SystemExit:
1346 1354 sys_exit = """*** SystemExit exception caught in code being profiled."""
1347 1355
1348 1356 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1349 1357
1350 1358 lims = opts.l
1351 1359 if lims:
1352 1360 lims = [] # rebuild lims with ints/floats/strings
1353 1361 for lim in opts.l:
1354 1362 try:
1355 1363 lims.append(int(lim))
1356 1364 except ValueError:
1357 1365 try:
1358 1366 lims.append(float(lim))
1359 1367 except ValueError:
1360 1368 lims.append(lim)
1361 1369
1362 1370 # Trap output.
1363 1371 stdout_trap = StringIO()
1364 1372
1365 1373 if hasattr(stats,'stream'):
1366 1374 # In newer versions of python, the stats object has a 'stream'
1367 1375 # attribute to write into.
1368 1376 stats.stream = stdout_trap
1369 1377 stats.print_stats(*lims)
1370 1378 else:
1371 1379 # For older versions, we manually redirect stdout during printing
1372 1380 sys_stdout = sys.stdout
1373 1381 try:
1374 1382 sys.stdout = stdout_trap
1375 1383 stats.print_stats(*lims)
1376 1384 finally:
1377 1385 sys.stdout = sys_stdout
1378 1386
1379 1387 output = stdout_trap.getvalue()
1380 1388 output = output.rstrip()
1381 1389
1382 1390 page(output,screen_lines=self.shell.rc.screen_length)
1383 1391 print sys_exit,
1384 1392
1385 1393 dump_file = opts.D[0]
1386 1394 text_file = opts.T[0]
1387 1395 if dump_file:
1388 1396 prof.dump_stats(dump_file)
1389 1397 print '\n*** Profile stats marshalled to file',\
1390 1398 `dump_file`+'.',sys_exit
1391 1399 if text_file:
1392 1400 pfile = file(text_file,'w')
1393 1401 pfile.write(output)
1394 1402 pfile.close()
1395 1403 print '\n*** Profile printout saved to text file',\
1396 1404 `text_file`+'.',sys_exit
1397 1405
1398 1406 if opts.has_key('r'):
1399 1407 return stats
1400 1408 else:
1401 1409 return None
1402 1410
1403 1411 def magic_run(self, parameter_s ='',runner=None):
1404 1412 """Run the named file inside IPython as a program.
1405 1413
1406 1414 Usage:\\
1407 1415 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1408 1416
1409 1417 Parameters after the filename are passed as command-line arguments to
1410 1418 the program (put in sys.argv). Then, control returns to IPython's
1411 1419 prompt.
1412 1420
1413 1421 This is similar to running at a system prompt:\\
1414 1422 $ python file args\\
1415 1423 but with the advantage of giving you IPython's tracebacks, and of
1416 1424 loading all variables into your interactive namespace for further use
1417 1425 (unless -p is used, see below).
1418 1426
1419 1427 The file is executed in a namespace initially consisting only of
1420 1428 __name__=='__main__' and sys.argv constructed as indicated. It thus
1421 1429 sees its environment as if it were being run as a stand-alone
1422 1430 program. But after execution, the IPython interactive namespace gets
1423 1431 updated with all variables defined in the program (except for __name__
1424 1432 and sys.argv). This allows for very convenient loading of code for
1425 1433 interactive work, while giving each program a 'clean sheet' to run in.
1426 1434
1427 1435 Options:
1428 1436
1429 1437 -n: __name__ is NOT set to '__main__', but to the running file's name
1430 1438 without extension (as python does under import). This allows running
1431 1439 scripts and reloading the definitions in them without calling code
1432 1440 protected by an ' if __name__ == "__main__" ' clause.
1433 1441
1434 1442 -i: run the file in IPython's namespace instead of an empty one. This
1435 1443 is useful if you are experimenting with code written in a text editor
1436 1444 which depends on variables defined interactively.
1437 1445
1438 1446 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1439 1447 being run. This is particularly useful if IPython is being used to
1440 1448 run unittests, which always exit with a sys.exit() call. In such
1441 1449 cases you are interested in the output of the test results, not in
1442 1450 seeing a traceback of the unittest module.
1443 1451
1444 1452 -t: print timing information at the end of the run. IPython will give
1445 1453 you an estimated CPU time consumption for your script, which under
1446 1454 Unix uses the resource module to avoid the wraparound problems of
1447 1455 time.clock(). Under Unix, an estimate of time spent on system tasks
1448 1456 is also given (for Windows platforms this is reported as 0.0).
1449 1457
1450 1458 If -t is given, an additional -N<N> option can be given, where <N>
1451 1459 must be an integer indicating how many times you want the script to
1452 1460 run. The final timing report will include total and per run results.
1453 1461
1454 1462 For example (testing the script uniq_stable.py):
1455 1463
1456 1464 In [1]: run -t uniq_stable
1457 1465
1458 1466 IPython CPU timings (estimated):\\
1459 1467 User : 0.19597 s.\\
1460 1468 System: 0.0 s.\\
1461 1469
1462 1470 In [2]: run -t -N5 uniq_stable
1463 1471
1464 1472 IPython CPU timings (estimated):\\
1465 1473 Total runs performed: 5\\
1466 1474 Times : Total Per run\\
1467 1475 User : 0.910862 s, 0.1821724 s.\\
1468 1476 System: 0.0 s, 0.0 s.
1469 1477
1470 1478 -d: run your program under the control of pdb, the Python debugger.
1471 1479 This allows you to execute your program step by step, watch variables,
1472 1480 etc. Internally, what IPython does is similar to calling:
1473 1481
1474 1482 pdb.run('execfile("YOURFILENAME")')
1475 1483
1476 1484 with a breakpoint set on line 1 of your file. You can change the line
1477 1485 number for this automatic breakpoint to be <N> by using the -bN option
1478 1486 (where N must be an integer). For example:
1479 1487
1480 1488 %run -d -b40 myscript
1481 1489
1482 1490 will set the first breakpoint at line 40 in myscript.py. Note that
1483 1491 the first breakpoint must be set on a line which actually does
1484 1492 something (not a comment or docstring) for it to stop execution.
1485 1493
1486 1494 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1487 1495 first enter 'c' (without qoutes) to start execution up to the first
1488 1496 breakpoint.
1489 1497
1490 1498 Entering 'help' gives information about the use of the debugger. You
1491 1499 can easily see pdb's full documentation with "import pdb;pdb.help()"
1492 1500 at a prompt.
1493 1501
1494 1502 -p: run program under the control of the Python profiler module (which
1495 1503 prints a detailed report of execution times, function calls, etc).
1496 1504
1497 1505 You can pass other options after -p which affect the behavior of the
1498 1506 profiler itself. See the docs for %prun for details.
1499 1507
1500 1508 In this mode, the program's variables do NOT propagate back to the
1501 1509 IPython interactive namespace (because they remain in the namespace
1502 1510 where the profiler executes them).
1503 1511
1504 1512 Internally this triggers a call to %prun, see its documentation for
1505 1513 details on the options available specifically for profiling.
1506 1514
1507 1515 There is one special usage for which the text above doesn't apply:
1508 1516 if the filename ends with .ipy, the file is run as ipython script,
1509 1517 just as if the commands were written on IPython prompt.
1510 1518 """
1511 1519
1512 1520 # get arguments and set sys.argv for program to be run.
1513 1521 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1514 1522 mode='list',list_all=1)
1515 1523
1516 1524 try:
1517 1525 filename = get_py_filename(arg_lst[0])
1518 1526 except IndexError:
1519 1527 warn('you must provide at least a filename.')
1520 1528 print '\n%run:\n',OInspect.getdoc(self.magic_run)
1521 1529 return
1522 1530 except IOError,msg:
1523 1531 error(msg)
1524 1532 return
1525 1533
1526 1534 if filename.lower().endswith('.ipy'):
1527 1535 self.api.runlines(open(filename).read())
1528 1536 return
1529 1537
1530 1538 # Control the response to exit() calls made by the script being run
1531 1539 exit_ignore = opts.has_key('e')
1532 1540
1533 1541 # Make sure that the running script gets a proper sys.argv as if it
1534 1542 # were run from a system shell.
1535 1543 save_argv = sys.argv # save it for later restoring
1536 1544 sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
1537 1545
1538 1546 if opts.has_key('i'):
1539 1547 prog_ns = self.shell.user_ns
1540 1548 __name__save = self.shell.user_ns['__name__']
1541 1549 prog_ns['__name__'] = '__main__'
1542 1550 else:
1543 1551 if opts.has_key('n'):
1544 1552 name = os.path.splitext(os.path.basename(filename))[0]
1545 1553 else:
1546 1554 name = '__main__'
1547 1555 prog_ns = {'__name__':name}
1548 1556
1549 1557 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
1550 1558 # set the __file__ global in the script's namespace
1551 1559 prog_ns['__file__'] = filename
1552 1560
1553 1561 # pickle fix. See iplib for an explanation. But we need to make sure
1554 1562 # that, if we overwrite __main__, we replace it at the end
1555 1563 if prog_ns['__name__'] == '__main__':
1556 1564 restore_main = sys.modules['__main__']
1557 1565 else:
1558 1566 restore_main = False
1559 1567
1560 1568 sys.modules[prog_ns['__name__']] = FakeModule(prog_ns)
1561 1569
1562 1570 stats = None
1563 1571 try:
1564 1572 if self.shell.has_readline:
1565 1573 self.shell.savehist()
1566 1574
1567 1575 if opts.has_key('p'):
1568 1576 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1569 1577 else:
1570 1578 if opts.has_key('d'):
1571 1579 deb = Debugger.Pdb(self.shell.rc.colors)
1572 1580 # reset Breakpoint state, which is moronically kept
1573 1581 # in a class
1574 1582 bdb.Breakpoint.next = 1
1575 1583 bdb.Breakpoint.bplist = {}
1576 1584 bdb.Breakpoint.bpbynumber = [None]
1577 1585 # Set an initial breakpoint to stop execution
1578 1586 maxtries = 10
1579 1587 bp = int(opts.get('b',[1])[0])
1580 1588 checkline = deb.checkline(filename,bp)
1581 1589 if not checkline:
1582 1590 for bp in range(bp+1,bp+maxtries+1):
1583 1591 if deb.checkline(filename,bp):
1584 1592 break
1585 1593 else:
1586 1594 msg = ("\nI failed to find a valid line to set "
1587 1595 "a breakpoint\n"
1588 1596 "after trying up to line: %s.\n"
1589 1597 "Please set a valid breakpoint manually "
1590 1598 "with the -b option." % bp)
1591 1599 error(msg)
1592 1600 return
1593 1601 # if we find a good linenumber, set the breakpoint
1594 1602 deb.do_break('%s:%s' % (filename,bp))
1595 1603 # Start file run
1596 1604 print "NOTE: Enter 'c' at the",
1597 1605 print "%s prompt to start your script." % deb.prompt
1598 1606 try:
1599 1607 deb.run('execfile("%s")' % filename,prog_ns)
1600 1608
1601 1609 except:
1602 1610 etype, value, tb = sys.exc_info()
1603 1611 # Skip three frames in the traceback: the %run one,
1604 1612 # one inside bdb.py, and the command-line typed by the
1605 1613 # user (run by exec in pdb itself).
1606 1614 self.shell.InteractiveTB(etype,value,tb,tb_offset=3)
1607 1615 else:
1608 1616 if runner is None:
1609 1617 runner = self.shell.safe_execfile
1610 1618 if opts.has_key('t'):
1611 1619 try:
1612 1620 nruns = int(opts['N'][0])
1613 1621 if nruns < 1:
1614 1622 error('Number of runs must be >=1')
1615 1623 return
1616 1624 except (KeyError):
1617 1625 nruns = 1
1618 1626 if nruns == 1:
1619 1627 t0 = clock2()
1620 1628 runner(filename,prog_ns,prog_ns,
1621 1629 exit_ignore=exit_ignore)
1622 1630 t1 = clock2()
1623 1631 t_usr = t1[0]-t0[0]
1624 1632 t_sys = t1[1]-t1[1]
1625 1633 print "\nIPython CPU timings (estimated):"
1626 1634 print " User : %10s s." % t_usr
1627 1635 print " System: %10s s." % t_sys
1628 1636 else:
1629 1637 runs = range(nruns)
1630 1638 t0 = clock2()
1631 1639 for nr in runs:
1632 1640 runner(filename,prog_ns,prog_ns,
1633 1641 exit_ignore=exit_ignore)
1634 1642 t1 = clock2()
1635 1643 t_usr = t1[0]-t0[0]
1636 1644 t_sys = t1[1]-t1[1]
1637 1645 print "\nIPython CPU timings (estimated):"
1638 1646 print "Total runs performed:",nruns
1639 1647 print " Times : %10s %10s" % ('Total','Per run')
1640 1648 print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
1641 1649 print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
1642 1650
1643 1651 else:
1644 1652 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1645 1653 if opts.has_key('i'):
1646 1654 self.shell.user_ns['__name__'] = __name__save
1647 1655 else:
1648 1656 # update IPython interactive namespace
1649 1657 del prog_ns['__name__']
1650 1658 self.shell.user_ns.update(prog_ns)
1651 1659 finally:
1652 1660 sys.argv = save_argv
1653 1661 if restore_main:
1654 1662 sys.modules['__main__'] = restore_main
1655 1663 if self.shell.has_readline:
1656 1664 self.shell.readline.read_history_file(self.shell.histfile)
1657 1665
1658 1666 return stats
1659 1667
1660 1668 def magic_runlog(self, parameter_s =''):
1661 1669 """Run files as logs.
1662 1670
1663 1671 Usage:\\
1664 1672 %runlog file1 file2 ...
1665 1673
1666 1674 Run the named files (treating them as log files) in sequence inside
1667 1675 the interpreter, and return to the prompt. This is much slower than
1668 1676 %run because each line is executed in a try/except block, but it
1669 1677 allows running files with syntax errors in them.
1670 1678
1671 1679 Normally IPython will guess when a file is one of its own logfiles, so
1672 1680 you can typically use %run even for logs. This shorthand allows you to
1673 1681 force any file to be treated as a log file."""
1674 1682
1675 1683 for f in parameter_s.split():
1676 1684 self.shell.safe_execfile(f,self.shell.user_ns,
1677 1685 self.shell.user_ns,islog=1)
1678 1686
1679 1687 def magic_timeit(self, parameter_s =''):
1680 1688 """Time execution of a Python statement or expression
1681 1689
1682 1690 Usage:\\
1683 1691 %timeit [-n<N> -r<R> [-t|-c]] statement
1684 1692
1685 1693 Time execution of a Python statement or expression using the timeit
1686 1694 module.
1687 1695
1688 1696 Options:
1689 1697 -n<N>: execute the given statement <N> times in a loop. If this value
1690 1698 is not given, a fitting value is chosen.
1691 1699
1692 1700 -r<R>: repeat the loop iteration <R> times and take the best result.
1693 1701 Default: 3
1694 1702
1695 1703 -t: use time.time to measure the time, which is the default on Unix.
1696 1704 This function measures wall time.
1697 1705
1698 1706 -c: use time.clock to measure the time, which is the default on
1699 1707 Windows and measures wall time. On Unix, resource.getrusage is used
1700 1708 instead and returns the CPU user time.
1701 1709
1702 1710 -p<P>: use a precision of <P> digits to display the timing result.
1703 1711 Default: 3
1704 1712
1705 1713
1706 1714 Examples:\\
1707 1715 In [1]: %timeit pass
1708 1716 10000000 loops, best of 3: 53.3 ns per loop
1709 1717
1710 1718 In [2]: u = None
1711 1719
1712 1720 In [3]: %timeit u is None
1713 1721 10000000 loops, best of 3: 184 ns per loop
1714 1722
1715 1723 In [4]: %timeit -r 4 u == None
1716 1724 1000000 loops, best of 4: 242 ns per loop
1717 1725
1718 1726 In [5]: import time
1719 1727
1720 1728 In [6]: %timeit -n1 time.sleep(2)
1721 1729 1 loops, best of 3: 2 s per loop
1722 1730
1723 1731
1724 1732 The times reported by %timeit will be slightly higher than those
1725 1733 reported by the timeit.py script when variables are accessed. This is
1726 1734 due to the fact that %timeit executes the statement in the namespace
1727 1735 of the shell, compared with timeit.py, which uses a single setup
1728 1736 statement to import function or create variables. Generally, the bias
1729 1737 does not matter as long as results from timeit.py are not mixed with
1730 1738 those from %timeit."""
1731 1739
1732 1740 import timeit
1733 1741 import math
1734 1742
1735 1743 units = ["s", "ms", "\xc2\xb5s", "ns"]
1736 1744 scaling = [1, 1e3, 1e6, 1e9]
1737 1745
1738 1746 opts, stmt = self.parse_options(parameter_s,'n:r:tcp:',
1739 1747 posix=False)
1740 1748 if stmt == "":
1741 1749 return
1742 1750 timefunc = timeit.default_timer
1743 1751 number = int(getattr(opts, "n", 0))
1744 1752 repeat = int(getattr(opts, "r", timeit.default_repeat))
1745 1753 precision = int(getattr(opts, "p", 3))
1746 1754 if hasattr(opts, "t"):
1747 1755 timefunc = time.time
1748 1756 if hasattr(opts, "c"):
1749 1757 timefunc = clock
1750 1758
1751 1759 timer = timeit.Timer(timer=timefunc)
1752 1760 # this code has tight coupling to the inner workings of timeit.Timer,
1753 1761 # but is there a better way to achieve that the code stmt has access
1754 1762 # to the shell namespace?
1755 1763
1756 1764 src = timeit.template % {'stmt': timeit.reindent(stmt, 8),
1757 1765 'setup': "pass"}
1758 1766 code = compile(src, "<magic-timeit>", "exec")
1759 1767 ns = {}
1760 1768 exec code in self.shell.user_ns, ns
1761 1769 timer.inner = ns["inner"]
1762 1770
1763 1771 if number == 0:
1764 1772 # determine number so that 0.2 <= total time < 2.0
1765 1773 number = 1
1766 1774 for i in range(1, 10):
1767 1775 number *= 10
1768 1776 if timer.timeit(number) >= 0.2:
1769 1777 break
1770 1778
1771 1779 best = min(timer.repeat(repeat, number)) / number
1772 1780
1773 1781 if best > 0.0:
1774 1782 order = min(-int(math.floor(math.log10(best)) // 3), 3)
1775 1783 else:
1776 1784 order = 3
1777 1785 print "%d loops, best of %d: %.*g %s per loop" % (number, repeat,
1778 1786 precision,
1779 1787 best * scaling[order],
1780 1788 units[order])
1781 1789
1782 1790 def magic_time(self,parameter_s = ''):
1783 1791 """Time execution of a Python statement or expression.
1784 1792
1785 1793 The CPU and wall clock times are printed, and the value of the
1786 1794 expression (if any) is returned. Note that under Win32, system time
1787 1795 is always reported as 0, since it can not be measured.
1788 1796
1789 1797 This function provides very basic timing functionality. In Python
1790 1798 2.3, the timeit module offers more control and sophistication, so this
1791 1799 could be rewritten to use it (patches welcome).
1792 1800
1793 1801 Some examples:
1794 1802
1795 1803 In [1]: time 2**128
1796 1804 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1797 1805 Wall time: 0.00
1798 1806 Out[1]: 340282366920938463463374607431768211456L
1799 1807
1800 1808 In [2]: n = 1000000
1801 1809
1802 1810 In [3]: time sum(range(n))
1803 1811 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1804 1812 Wall time: 1.37
1805 1813 Out[3]: 499999500000L
1806 1814
1807 1815 In [4]: time print 'hello world'
1808 1816 hello world
1809 1817 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1810 1818 Wall time: 0.00
1811 1819 """
1812 1820
1813 1821 # fail immediately if the given expression can't be compiled
1814 1822 try:
1815 1823 mode = 'eval'
1816 1824 code = compile(parameter_s,'<timed eval>',mode)
1817 1825 except SyntaxError:
1818 1826 mode = 'exec'
1819 1827 code = compile(parameter_s,'<timed exec>',mode)
1820 1828 # skew measurement as little as possible
1821 1829 glob = self.shell.user_ns
1822 1830 clk = clock2
1823 1831 wtime = time.time
1824 1832 # time execution
1825 1833 wall_st = wtime()
1826 1834 if mode=='eval':
1827 1835 st = clk()
1828 1836 out = eval(code,glob)
1829 1837 end = clk()
1830 1838 else:
1831 1839 st = clk()
1832 1840 exec code in glob
1833 1841 end = clk()
1834 1842 out = None
1835 1843 wall_end = wtime()
1836 1844 # Compute actual times and report
1837 1845 wall_time = wall_end-wall_st
1838 1846 cpu_user = end[0]-st[0]
1839 1847 cpu_sys = end[1]-st[1]
1840 1848 cpu_tot = cpu_user+cpu_sys
1841 1849 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
1842 1850 (cpu_user,cpu_sys,cpu_tot)
1843 1851 print "Wall time: %.2f" % wall_time
1844 1852 return out
1845 1853
1846 1854 def magic_macro(self,parameter_s = ''):
1847 1855 """Define a set of input lines as a macro for future re-execution.
1848 1856
1849 1857 Usage:\\
1850 1858 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
1851 1859
1852 1860 Options:
1853 1861
1854 1862 -r: use 'raw' input. By default, the 'processed' history is used,
1855 1863 so that magics are loaded in their transformed version to valid
1856 1864 Python. If this option is given, the raw input as typed as the
1857 1865 command line is used instead.
1858 1866
1859 1867 This will define a global variable called `name` which is a string
1860 1868 made of joining the slices and lines you specify (n1,n2,... numbers
1861 1869 above) from your input history into a single string. This variable
1862 1870 acts like an automatic function which re-executes those lines as if
1863 1871 you had typed them. You just type 'name' at the prompt and the code
1864 1872 executes.
1865 1873
1866 1874 The notation for indicating number ranges is: n1-n2 means 'use line
1867 1875 numbers n1,...n2' (the endpoint is included). That is, '5-7' means
1868 1876 using the lines numbered 5,6 and 7.
1869 1877
1870 1878 Note: as a 'hidden' feature, you can also use traditional python slice
1871 1879 notation, where N:M means numbers N through M-1.
1872 1880
1873 1881 For example, if your history contains (%hist prints it):
1874 1882
1875 1883 44: x=1\\
1876 1884 45: y=3\\
1877 1885 46: z=x+y\\
1878 1886 47: print x\\
1879 1887 48: a=5\\
1880 1888 49: print 'x',x,'y',y\\
1881 1889
1882 1890 you can create a macro with lines 44 through 47 (included) and line 49
1883 1891 called my_macro with:
1884 1892
1885 1893 In [51]: %macro my_macro 44-47 49
1886 1894
1887 1895 Now, typing `my_macro` (without quotes) will re-execute all this code
1888 1896 in one pass.
1889 1897
1890 1898 You don't need to give the line-numbers in order, and any given line
1891 1899 number can appear multiple times. You can assemble macros with any
1892 1900 lines from your input history in any order.
1893 1901
1894 1902 The macro is a simple object which holds its value in an attribute,
1895 1903 but IPython's display system checks for macros and executes them as
1896 1904 code instead of printing them when you type their name.
1897 1905
1898 1906 You can view a macro's contents by explicitly printing it with:
1899 1907
1900 1908 'print macro_name'.
1901 1909
1902 1910 For one-off cases which DON'T contain magic function calls in them you
1903 1911 can obtain similar results by explicitly executing slices from your
1904 1912 input history with:
1905 1913
1906 1914 In [60]: exec In[44:48]+In[49]"""
1907 1915
1908 1916 opts,args = self.parse_options(parameter_s,'r',mode='list')
1909 1917 name,ranges = args[0], args[1:]
1910 1918 #print 'rng',ranges # dbg
1911 1919 lines = self.extract_input_slices(ranges,opts.has_key('r'))
1912 1920 macro = Macro(lines)
1913 1921 self.shell.user_ns.update({name:macro})
1914 1922 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
1915 1923 print 'Macro contents:'
1916 1924 print macro,
1917 1925
1918 1926 def magic_save(self,parameter_s = ''):
1919 1927 """Save a set of lines to a given filename.
1920 1928
1921 1929 Usage:\\
1922 1930 %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
1923 1931
1924 1932 Options:
1925 1933
1926 1934 -r: use 'raw' input. By default, the 'processed' history is used,
1927 1935 so that magics are loaded in their transformed version to valid
1928 1936 Python. If this option is given, the raw input as typed as the
1929 1937 command line is used instead.
1930 1938
1931 1939 This function uses the same syntax as %macro for line extraction, but
1932 1940 instead of creating a macro it saves the resulting string to the
1933 1941 filename you specify.
1934 1942
1935 1943 It adds a '.py' extension to the file if you don't do so yourself, and
1936 1944 it asks for confirmation before overwriting existing files."""
1937 1945
1938 1946 opts,args = self.parse_options(parameter_s,'r',mode='list')
1939 1947 fname,ranges = args[0], args[1:]
1940 1948 if not fname.endswith('.py'):
1941 1949 fname += '.py'
1942 1950 if os.path.isfile(fname):
1943 1951 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
1944 1952 if ans.lower() not in ['y','yes']:
1945 1953 print 'Operation cancelled.'
1946 1954 return
1947 1955 cmds = ''.join(self.extract_input_slices(ranges,opts.has_key('r')))
1948 1956 f = file(fname,'w')
1949 1957 f.write(cmds)
1950 1958 f.close()
1951 1959 print 'The following commands were written to file `%s`:' % fname
1952 1960 print cmds
1953 1961
1954 1962 def _edit_macro(self,mname,macro):
1955 1963 """open an editor with the macro data in a file"""
1956 1964 filename = self.shell.mktempfile(macro.value)
1957 1965 self.shell.hooks.editor(filename)
1958 1966
1959 1967 # and make a new macro object, to replace the old one
1960 1968 mfile = open(filename)
1961 1969 mvalue = mfile.read()
1962 1970 mfile.close()
1963 1971 self.shell.user_ns[mname] = Macro(mvalue)
1964 1972
1965 1973 def magic_ed(self,parameter_s=''):
1966 1974 """Alias to %edit."""
1967 1975 return self.magic_edit(parameter_s)
1968 1976
1969 1977 def magic_edit(self,parameter_s='',last_call=['','']):
1970 1978 """Bring up an editor and execute the resulting code.
1971 1979
1972 1980 Usage:
1973 1981 %edit [options] [args]
1974 1982
1975 1983 %edit runs IPython's editor hook. The default version of this hook is
1976 1984 set to call the __IPYTHON__.rc.editor command. This is read from your
1977 1985 environment variable $EDITOR. If this isn't found, it will default to
1978 1986 vi under Linux/Unix and to notepad under Windows. See the end of this
1979 1987 docstring for how to change the editor hook.
1980 1988
1981 1989 You can also set the value of this editor via the command line option
1982 1990 '-editor' or in your ipythonrc file. This is useful if you wish to use
1983 1991 specifically for IPython an editor different from your typical default
1984 1992 (and for Windows users who typically don't set environment variables).
1985 1993
1986 1994 This command allows you to conveniently edit multi-line code right in
1987 1995 your IPython session.
1988 1996
1989 1997 If called without arguments, %edit opens up an empty editor with a
1990 1998 temporary file and will execute the contents of this file when you
1991 1999 close it (don't forget to save it!).
1992 2000
1993 2001
1994 2002 Options:
1995 2003
1996 2004 -n <number>: open the editor at a specified line number. By default,
1997 2005 the IPython editor hook uses the unix syntax 'editor +N filename', but
1998 2006 you can configure this by providing your own modified hook if your
1999 2007 favorite editor supports line-number specifications with a different
2000 2008 syntax.
2001 2009
2002 2010 -p: this will call the editor with the same data as the previous time
2003 2011 it was used, regardless of how long ago (in your current session) it
2004 2012 was.
2005 2013
2006 2014 -r: use 'raw' input. This option only applies to input taken from the
2007 2015 user's history. By default, the 'processed' history is used, so that
2008 2016 magics are loaded in their transformed version to valid Python. If
2009 2017 this option is given, the raw input as typed as the command line is
2010 2018 used instead. When you exit the editor, it will be executed by
2011 2019 IPython's own processor.
2012 2020
2013 2021 -x: do not execute the edited code immediately upon exit. This is
2014 2022 mainly useful if you are editing programs which need to be called with
2015 2023 command line arguments, which you can then do using %run.
2016 2024
2017 2025
2018 2026 Arguments:
2019 2027
2020 2028 If arguments are given, the following possibilites exist:
2021 2029
2022 2030 - The arguments are numbers or pairs of colon-separated numbers (like
2023 2031 1 4:8 9). These are interpreted as lines of previous input to be
2024 2032 loaded into the editor. The syntax is the same of the %macro command.
2025 2033
2026 2034 - If the argument doesn't start with a number, it is evaluated as a
2027 2035 variable and its contents loaded into the editor. You can thus edit
2028 2036 any string which contains python code (including the result of
2029 2037 previous edits).
2030 2038
2031 2039 - If the argument is the name of an object (other than a string),
2032 2040 IPython will try to locate the file where it was defined and open the
2033 2041 editor at the point where it is defined. You can use `%edit function`
2034 2042 to load an editor exactly at the point where 'function' is defined,
2035 2043 edit it and have the file be executed automatically.
2036 2044
2037 2045 If the object is a macro (see %macro for details), this opens up your
2038 2046 specified editor with a temporary file containing the macro's data.
2039 2047 Upon exit, the macro is reloaded with the contents of the file.
2040 2048
2041 2049 Note: opening at an exact line is only supported under Unix, and some
2042 2050 editors (like kedit and gedit up to Gnome 2.8) do not understand the
2043 2051 '+NUMBER' parameter necessary for this feature. Good editors like
2044 2052 (X)Emacs, vi, jed, pico and joe all do.
2045 2053
2046 2054 - If the argument is not found as a variable, IPython will look for a
2047 2055 file with that name (adding .py if necessary) and load it into the
2048 2056 editor. It will execute its contents with execfile() when you exit,
2049 2057 loading any code in the file into your interactive namespace.
2050 2058
2051 2059 After executing your code, %edit will return as output the code you
2052 2060 typed in the editor (except when it was an existing file). This way
2053 2061 you can reload the code in further invocations of %edit as a variable,
2054 2062 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
2055 2063 the output.
2056 2064
2057 2065 Note that %edit is also available through the alias %ed.
2058 2066
2059 2067 This is an example of creating a simple function inside the editor and
2060 2068 then modifying it. First, start up the editor:
2061 2069
2062 2070 In [1]: ed\\
2063 2071 Editing... done. Executing edited code...\\
2064 2072 Out[1]: 'def foo():\\n print "foo() was defined in an editing session"\\n'
2065 2073
2066 2074 We can then call the function foo():
2067 2075
2068 2076 In [2]: foo()\\
2069 2077 foo() was defined in an editing session
2070 2078
2071 2079 Now we edit foo. IPython automatically loads the editor with the
2072 2080 (temporary) file where foo() was previously defined:
2073 2081
2074 2082 In [3]: ed foo\\
2075 2083 Editing... done. Executing edited code...
2076 2084
2077 2085 And if we call foo() again we get the modified version:
2078 2086
2079 2087 In [4]: foo()\\
2080 2088 foo() has now been changed!
2081 2089
2082 2090 Here is an example of how to edit a code snippet successive
2083 2091 times. First we call the editor:
2084 2092
2085 2093 In [8]: ed\\
2086 2094 Editing... done. Executing edited code...\\
2087 2095 hello\\
2088 2096 Out[8]: "print 'hello'\\n"
2089 2097
2090 2098 Now we call it again with the previous output (stored in _):
2091 2099
2092 2100 In [9]: ed _\\
2093 2101 Editing... done. Executing edited code...\\
2094 2102 hello world\\
2095 2103 Out[9]: "print 'hello world'\\n"
2096 2104
2097 2105 Now we call it with the output #8 (stored in _8, also as Out[8]):
2098 2106
2099 2107 In [10]: ed _8\\
2100 2108 Editing... done. Executing edited code...\\
2101 2109 hello again\\
2102 2110 Out[10]: "print 'hello again'\\n"
2103 2111
2104 2112
2105 2113 Changing the default editor hook:
2106 2114
2107 2115 If you wish to write your own editor hook, you can put it in a
2108 2116 configuration file which you load at startup time. The default hook
2109 2117 is defined in the IPython.hooks module, and you can use that as a
2110 2118 starting example for further modifications. That file also has
2111 2119 general instructions on how to set a new hook for use once you've
2112 2120 defined it."""
2113 2121
2114 2122 # FIXME: This function has become a convoluted mess. It needs a
2115 2123 # ground-up rewrite with clean, simple logic.
2116 2124
2117 2125 def make_filename(arg):
2118 2126 "Make a filename from the given args"
2119 2127 try:
2120 2128 filename = get_py_filename(arg)
2121 2129 except IOError:
2122 2130 if args.endswith('.py'):
2123 2131 filename = arg
2124 2132 else:
2125 2133 filename = None
2126 2134 return filename
2127 2135
2128 2136 # custom exceptions
2129 2137 class DataIsObject(Exception): pass
2130 2138
2131 2139 opts,args = self.parse_options(parameter_s,'prxn:')
2132 2140 # Set a few locals from the options for convenience:
2133 2141 opts_p = opts.has_key('p')
2134 2142 opts_r = opts.has_key('r')
2135 2143
2136 2144 # Default line number value
2137 2145 lineno = opts.get('n',None)
2138 2146
2139 2147 if opts_p:
2140 2148 args = '_%s' % last_call[0]
2141 2149 if not self.shell.user_ns.has_key(args):
2142 2150 args = last_call[1]
2143 2151
2144 2152 # use last_call to remember the state of the previous call, but don't
2145 2153 # let it be clobbered by successive '-p' calls.
2146 2154 try:
2147 2155 last_call[0] = self.shell.outputcache.prompt_count
2148 2156 if not opts_p:
2149 2157 last_call[1] = parameter_s
2150 2158 except:
2151 2159 pass
2152 2160
2153 2161 # by default this is done with temp files, except when the given
2154 2162 # arg is a filename
2155 2163 use_temp = 1
2156 2164
2157 2165 if re.match(r'\d',args):
2158 2166 # Mode where user specifies ranges of lines, like in %macro.
2159 2167 # This means that you can't edit files whose names begin with
2160 2168 # numbers this way. Tough.
2161 2169 ranges = args.split()
2162 2170 data = ''.join(self.extract_input_slices(ranges,opts_r))
2163 2171 elif args.endswith('.py'):
2164 2172 filename = make_filename(args)
2165 2173 data = ''
2166 2174 use_temp = 0
2167 2175 elif args:
2168 2176 try:
2169 2177 # Load the parameter given as a variable. If not a string,
2170 2178 # process it as an object instead (below)
2171 2179
2172 2180 #print '*** args',args,'type',type(args) # dbg
2173 2181 data = eval(args,self.shell.user_ns)
2174 2182 if not type(data) in StringTypes:
2175 2183 raise DataIsObject
2176 2184
2177 2185 except (NameError,SyntaxError):
2178 2186 # given argument is not a variable, try as a filename
2179 2187 filename = make_filename(args)
2180 2188 if filename is None:
2181 2189 warn("Argument given (%s) can't be found as a variable "
2182 2190 "or as a filename." % args)
2183 2191 return
2184 2192
2185 2193 data = ''
2186 2194 use_temp = 0
2187 2195 except DataIsObject:
2188 2196
2189 2197 # macros have a special edit function
2190 2198 if isinstance(data,Macro):
2191 2199 self._edit_macro(args,data)
2192 2200 return
2193 2201
2194 2202 # For objects, try to edit the file where they are defined
2195 2203 try:
2196 2204 filename = inspect.getabsfile(data)
2197 2205 datafile = 1
2198 2206 except TypeError:
2199 2207 filename = make_filename(args)
2200 2208 datafile = 1
2201 2209 warn('Could not find file where `%s` is defined.\n'
2202 2210 'Opening a file named `%s`' % (args,filename))
2203 2211 # Now, make sure we can actually read the source (if it was in
2204 2212 # a temp file it's gone by now).
2205 2213 if datafile:
2206 2214 try:
2207 2215 if lineno is None:
2208 2216 lineno = inspect.getsourcelines(data)[1]
2209 2217 except IOError:
2210 2218 filename = make_filename(args)
2211 2219 if filename is None:
2212 2220 warn('The file `%s` where `%s` was defined cannot '
2213 2221 'be read.' % (filename,data))
2214 2222 return
2215 2223 use_temp = 0
2216 2224 else:
2217 2225 data = ''
2218 2226
2219 2227 if use_temp:
2220 2228 filename = self.shell.mktempfile(data)
2221 2229 print 'IPython will make a temporary file named:',filename
2222 2230
2223 2231 # do actual editing here
2224 2232 print 'Editing...',
2225 2233 sys.stdout.flush()
2226 2234 self.shell.hooks.editor(filename,lineno)
2227 2235 if opts.has_key('x'): # -x prevents actual execution
2228 2236 print
2229 2237 else:
2230 2238 print 'done. Executing edited code...'
2231 2239 if opts_r:
2232 2240 self.shell.runlines(file_read(filename))
2233 2241 else:
2234 2242 self.shell.safe_execfile(filename,self.shell.user_ns)
2235 2243 if use_temp:
2236 2244 try:
2237 2245 return open(filename).read()
2238 2246 except IOError,msg:
2239 2247 if msg.filename == filename:
2240 2248 warn('File not found. Did you forget to save?')
2241 2249 return
2242 2250 else:
2243 2251 self.shell.showtraceback()
2244 2252
2245 2253 def magic_xmode(self,parameter_s = ''):
2246 2254 """Switch modes for the exception handlers.
2247 2255
2248 2256 Valid modes: Plain, Context and Verbose.
2249 2257
2250 2258 If called without arguments, acts as a toggle."""
2251 2259
2252 2260 def xmode_switch_err(name):
2253 2261 warn('Error changing %s exception modes.\n%s' %
2254 2262 (name,sys.exc_info()[1]))
2255 2263
2256 2264 shell = self.shell
2257 2265 new_mode = parameter_s.strip().capitalize()
2258 2266 try:
2259 2267 shell.InteractiveTB.set_mode(mode=new_mode)
2260 2268 print 'Exception reporting mode:',shell.InteractiveTB.mode
2261 2269 except:
2262 2270 xmode_switch_err('user')
2263 2271
2264 2272 # threaded shells use a special handler in sys.excepthook
2265 2273 if shell.isthreaded:
2266 2274 try:
2267 2275 shell.sys_excepthook.set_mode(mode=new_mode)
2268 2276 except:
2269 2277 xmode_switch_err('threaded')
2270 2278
2271 2279 def magic_colors(self,parameter_s = ''):
2272 2280 """Switch color scheme for prompts, info system and exception handlers.
2273 2281
2274 2282 Currently implemented schemes: NoColor, Linux, LightBG.
2275 2283
2276 2284 Color scheme names are not case-sensitive."""
2277 2285
2278 2286 def color_switch_err(name):
2279 2287 warn('Error changing %s color schemes.\n%s' %
2280 2288 (name,sys.exc_info()[1]))
2281 2289
2282 2290
2283 2291 new_scheme = parameter_s.strip()
2284 2292 if not new_scheme:
2285 2293 print 'You must specify a color scheme.'
2286 2294 return
2287 2295 import IPython.rlineimpl as readline
2288 2296 if not readline.have_readline:
2289 2297 msg = """\
2290 2298 Proper color support under MS Windows requires the pyreadline library.
2291 2299 You can find it at:
2292 2300 http://ipython.scipy.org/moin/PyReadline/Intro
2293 2301 Gary's readline needs the ctypes module, from:
2294 2302 http://starship.python.net/crew/theller/ctypes
2295 2303 (Note that ctypes is already part of Python versions 2.5 and newer).
2296 2304
2297 2305 Defaulting color scheme to 'NoColor'"""
2298 2306 new_scheme = 'NoColor'
2299 2307 warn(msg)
2300 2308 # local shortcut
2301 2309 shell = self.shell
2302 2310
2303 2311 # Set prompt colors
2304 2312 try:
2305 2313 shell.outputcache.set_colors(new_scheme)
2306 2314 except:
2307 2315 color_switch_err('prompt')
2308 2316 else:
2309 2317 shell.rc.colors = \
2310 2318 shell.outputcache.color_table.active_scheme_name
2311 2319 # Set exception colors
2312 2320 try:
2313 2321 shell.InteractiveTB.set_colors(scheme = new_scheme)
2314 2322 shell.SyntaxTB.set_colors(scheme = new_scheme)
2315 2323 except:
2316 2324 color_switch_err('exception')
2317 2325
2318 2326 # threaded shells use a verbose traceback in sys.excepthook
2319 2327 if shell.isthreaded:
2320 2328 try:
2321 2329 shell.sys_excepthook.set_colors(scheme=new_scheme)
2322 2330 except:
2323 2331 color_switch_err('system exception handler')
2324 2332
2325 2333 # Set info (for 'object?') colors
2326 2334 if shell.rc.color_info:
2327 2335 try:
2328 2336 shell.inspector.set_active_scheme(new_scheme)
2329 2337 except:
2330 2338 color_switch_err('object inspector')
2331 2339 else:
2332 2340 shell.inspector.set_active_scheme('NoColor')
2333 2341
2334 2342 def magic_color_info(self,parameter_s = ''):
2335 2343 """Toggle color_info.
2336 2344
2337 2345 The color_info configuration parameter controls whether colors are
2338 2346 used for displaying object details (by things like %psource, %pfile or
2339 2347 the '?' system). This function toggles this value with each call.
2340 2348
2341 2349 Note that unless you have a fairly recent pager (less works better
2342 2350 than more) in your system, using colored object information displays
2343 2351 will not work properly. Test it and see."""
2344 2352
2345 2353 self.shell.rc.color_info = 1 - self.shell.rc.color_info
2346 2354 self.magic_colors(self.shell.rc.colors)
2347 2355 print 'Object introspection functions have now coloring:',
2348 2356 print ['OFF','ON'][self.shell.rc.color_info]
2349 2357
2350 2358 def magic_Pprint(self, parameter_s=''):
2351 2359 """Toggle pretty printing on/off."""
2352 2360
2353 2361 self.shell.rc.pprint = 1 - self.shell.rc.pprint
2354 2362 print 'Pretty printing has been turned', \
2355 2363 ['OFF','ON'][self.shell.rc.pprint]
2356 2364
2357 2365 def magic_exit(self, parameter_s=''):
2358 2366 """Exit IPython, confirming if configured to do so.
2359 2367
2360 2368 You can configure whether IPython asks for confirmation upon exit by
2361 2369 setting the confirm_exit flag in the ipythonrc file."""
2362 2370
2363 2371 self.shell.exit()
2364 2372
2365 2373 def magic_quit(self, parameter_s=''):
2366 2374 """Exit IPython, confirming if configured to do so (like %exit)"""
2367 2375
2368 2376 self.shell.exit()
2369 2377
2370 2378 def magic_Exit(self, parameter_s=''):
2371 2379 """Exit IPython without confirmation."""
2372 2380
2373 2381 self.shell.exit_now = True
2374 2382
2375 2383 def magic_Quit(self, parameter_s=''):
2376 2384 """Exit IPython without confirmation (like %Exit)."""
2377 2385
2378 2386 self.shell.exit_now = True
2379 2387
2380 2388 #......................................................................
2381 2389 # Functions to implement unix shell-type things
2382 2390
2383 2391 def magic_alias(self, parameter_s = ''):
2384 2392 """Define an alias for a system command.
2385 2393
2386 2394 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2387 2395
2388 2396 Then, typing 'alias_name params' will execute the system command 'cmd
2389 2397 params' (from your underlying operating system).
2390 2398
2391 2399 Aliases have lower precedence than magic functions and Python normal
2392 2400 variables, so if 'foo' is both a Python variable and an alias, the
2393 2401 alias can not be executed until 'del foo' removes the Python variable.
2394 2402
2395 2403 You can use the %l specifier in an alias definition to represent the
2396 2404 whole line when the alias is called. For example:
2397 2405
2398 2406 In [2]: alias all echo "Input in brackets: <%l>"\\
2399 2407 In [3]: all hello world\\
2400 2408 Input in brackets: <hello world>
2401 2409
2402 2410 You can also define aliases with parameters using %s specifiers (one
2403 2411 per parameter):
2404 2412
2405 2413 In [1]: alias parts echo first %s second %s\\
2406 2414 In [2]: %parts A B\\
2407 2415 first A second B\\
2408 2416 In [3]: %parts A\\
2409 2417 Incorrect number of arguments: 2 expected.\\
2410 2418 parts is an alias to: 'echo first %s second %s'
2411 2419
2412 2420 Note that %l and %s are mutually exclusive. You can only use one or
2413 2421 the other in your aliases.
2414 2422
2415 2423 Aliases expand Python variables just like system calls using ! or !!
2416 2424 do: all expressions prefixed with '$' get expanded. For details of
2417 2425 the semantic rules, see PEP-215:
2418 2426 http://www.python.org/peps/pep-0215.html. This is the library used by
2419 2427 IPython for variable expansion. If you want to access a true shell
2420 2428 variable, an extra $ is necessary to prevent its expansion by IPython:
2421 2429
2422 2430 In [6]: alias show echo\\
2423 2431 In [7]: PATH='A Python string'\\
2424 2432 In [8]: show $PATH\\
2425 2433 A Python string\\
2426 2434 In [9]: show $$PATH\\
2427 2435 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2428 2436
2429 2437 You can use the alias facility to acess all of $PATH. See the %rehash
2430 2438 and %rehashx functions, which automatically create aliases for the
2431 2439 contents of your $PATH.
2432 2440
2433 2441 If called with no parameters, %alias prints the current alias table."""
2434 2442
2435 2443 par = parameter_s.strip()
2436 2444 if not par:
2437 2445 stored = self.db.get('stored_aliases', {} )
2438 2446 atab = self.shell.alias_table
2439 2447 aliases = atab.keys()
2440 2448 aliases.sort()
2441 2449 res = []
2442 2450 showlast = []
2443 2451 for alias in aliases:
2444 2452 tgt = atab[alias][1]
2445 2453 # 'interesting' aliases
2446 2454 if (alias in stored or
2447 2455 alias != os.path.splitext(tgt)[0] or
2448 2456 ' ' in tgt):
2449 2457 showlast.append((alias, tgt))
2450 2458 else:
2451 2459 res.append((alias, tgt ))
2452 2460
2453 2461 # show most interesting aliases last
2454 2462 res.extend(showlast)
2455 2463 print "Total number of aliases:",len(aliases)
2456 2464 return res
2457 2465 try:
2458 2466 alias,cmd = par.split(None,1)
2459 2467 except:
2460 2468 print OInspect.getdoc(self.magic_alias)
2461 2469 else:
2462 2470 nargs = cmd.count('%s')
2463 2471 if nargs>0 and cmd.find('%l')>=0:
2464 2472 error('The %s and %l specifiers are mutually exclusive '
2465 2473 'in alias definitions.')
2466 2474 else: # all looks OK
2467 2475 self.shell.alias_table[alias] = (nargs,cmd)
2468 2476 self.shell.alias_table_validate(verbose=0)
2469 2477 # end magic_alias
2470 2478
2471 2479 def magic_unalias(self, parameter_s = ''):
2472 2480 """Remove an alias"""
2473 2481
2474 2482 aname = parameter_s.strip()
2475 2483 if aname in self.shell.alias_table:
2476 2484 del self.shell.alias_table[aname]
2477 2485 stored = self.db.get('stored_aliases', {} )
2478 2486 if aname in stored:
2479 2487 print "Removing %stored alias",aname
2480 2488 del stored[aname]
2481 2489 self.db['stored_aliases'] = stored
2482 2490
2483 2491 def magic_rehash(self, parameter_s = ''):
2484 2492 """Update the alias table with all entries in $PATH.
2485 2493
2486 2494 This version does no checks on execute permissions or whether the
2487 2495 contents of $PATH are truly files (instead of directories or something
2488 2496 else). For such a safer (but slower) version, use %rehashx."""
2489 2497
2490 2498 # This function (and rehashx) manipulate the alias_table directly
2491 2499 # rather than calling magic_alias, for speed reasons. A rehash on a
2492 2500 # typical Linux box involves several thousand entries, so efficiency
2493 2501 # here is a top concern.
2494 2502
2495 2503 path = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep))
2496 2504 alias_table = self.shell.alias_table
2497 2505 for pdir in path:
2498 2506 for ff in os.listdir(pdir):
2499 2507 # each entry in the alias table must be (N,name), where
2500 2508 # N is the number of positional arguments of the alias.
2501 2509 alias_table[ff] = (0,ff)
2502 2510 # Make sure the alias table doesn't contain keywords or builtins
2503 2511 self.shell.alias_table_validate()
2504 2512 # Call again init_auto_alias() so we get 'rm -i' and other modified
2505 2513 # aliases since %rehash will probably clobber them
2506 2514 self.shell.init_auto_alias()
2507 2515
2508 2516 def magic_rehashx(self, parameter_s = ''):
2509 2517 """Update the alias table with all executable files in $PATH.
2510 2518
2511 2519 This version explicitly checks that every entry in $PATH is a file
2512 2520 with execute access (os.X_OK), so it is much slower than %rehash.
2513 2521
2514 2522 Under Windows, it checks executability as a match agains a
2515 2523 '|'-separated string of extensions, stored in the IPython config
2516 2524 variable win_exec_ext. This defaults to 'exe|com|bat'. """
2517 2525
2518 2526 path = [os.path.abspath(os.path.expanduser(p)) for p in
2519 2527 os.environ['PATH'].split(os.pathsep)]
2520 2528 path = filter(os.path.isdir,path)
2521 2529
2522 2530 alias_table = self.shell.alias_table
2523 2531 syscmdlist = []
2524 2532 if os.name == 'posix':
2525 2533 isexec = lambda fname:os.path.isfile(fname) and \
2526 2534 os.access(fname,os.X_OK)
2527 2535 else:
2528 2536
2529 2537 try:
2530 2538 winext = os.environ['pathext'].replace(';','|').replace('.','')
2531 2539 except KeyError:
2532 2540 winext = 'exe|com|bat|py'
2533 2541 if 'py' not in winext:
2534 2542 winext += '|py'
2535 2543 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2536 2544 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2537 2545 savedir = os.getcwd()
2538 2546 try:
2539 2547 # write the whole loop for posix/Windows so we don't have an if in
2540 2548 # the innermost part
2541 2549 if os.name == 'posix':
2542 2550 for pdir in path:
2543 2551 os.chdir(pdir)
2544 2552 for ff in os.listdir(pdir):
2545 2553 if isexec(ff) and ff not in self.shell.no_alias:
2546 2554 # each entry in the alias table must be (N,name),
2547 2555 # where N is the number of positional arguments of the
2548 2556 # alias.
2549 2557 alias_table[ff] = (0,ff)
2550 2558 syscmdlist.append(ff)
2551 2559 else:
2552 2560 for pdir in path:
2553 2561 os.chdir(pdir)
2554 2562 for ff in os.listdir(pdir):
2555 2563 base, ext = os.path.splitext(ff)
2556 2564 if isexec(ff) and base not in self.shell.no_alias:
2557 2565 if ext.lower() == '.exe':
2558 2566 ff = base
2559 2567 alias_table[base] = (0,ff)
2560 2568 syscmdlist.append(ff)
2561 2569 # Make sure the alias table doesn't contain keywords or builtins
2562 2570 self.shell.alias_table_validate()
2563 2571 # Call again init_auto_alias() so we get 'rm -i' and other
2564 2572 # modified aliases since %rehashx will probably clobber them
2565 2573 self.shell.init_auto_alias()
2566 2574 db = self.getapi().db
2567 2575 db['syscmdlist'] = syscmdlist
2568 2576 finally:
2569 2577 os.chdir(savedir)
2570 2578
2571 2579 def magic_pwd(self, parameter_s = ''):
2572 2580 """Return the current working directory path."""
2573 2581 return os.getcwd()
2574 2582
2575 2583 def magic_cd(self, parameter_s=''):
2576 2584 """Change the current working directory.
2577 2585
2578 2586 This command automatically maintains an internal list of directories
2579 2587 you visit during your IPython session, in the variable _dh. The
2580 2588 command %dhist shows this history nicely formatted. You can also
2581 2589 do 'cd -<tab>' to see directory history conveniently.
2582 2590
2583 2591 Usage:
2584 2592
2585 2593 cd 'dir': changes to directory 'dir'.
2586 2594
2587 2595 cd -: changes to the last visited directory.
2588 2596
2589 2597 cd -<n>: changes to the n-th directory in the directory history.
2590 2598
2591 2599 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2592 2600 (note: cd <bookmark_name> is enough if there is no
2593 2601 directory <bookmark_name>, but a bookmark with the name exists.)
2594 2602 'cd -b <tab>' allows you to tab-complete bookmark names.
2595 2603
2596 2604 Options:
2597 2605
2598 2606 -q: quiet. Do not print the working directory after the cd command is
2599 2607 executed. By default IPython's cd command does print this directory,
2600 2608 since the default prompts do not display path information.
2601 2609
2602 2610 Note that !cd doesn't work for this purpose because the shell where
2603 2611 !command runs is immediately discarded after executing 'command'."""
2604 2612
2605 2613 parameter_s = parameter_s.strip()
2606 2614 #bkms = self.shell.persist.get("bookmarks",{})
2607 2615
2608 2616 numcd = re.match(r'(-)(\d+)$',parameter_s)
2609 2617 # jump in directory history by number
2610 2618 if numcd:
2611 2619 nn = int(numcd.group(2))
2612 2620 try:
2613 2621 ps = self.shell.user_ns['_dh'][nn]
2614 2622 except IndexError:
2615 2623 print 'The requested directory does not exist in history.'
2616 2624 return
2617 2625 else:
2618 2626 opts = {}
2619 2627 else:
2620 2628 #turn all non-space-escaping backslashes to slashes,
2621 2629 # for c:\windows\directory\names\
2622 2630 parameter_s = re.sub(r'\\(?! )','/', parameter_s)
2623 2631 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2624 2632 # jump to previous
2625 2633 if ps == '-':
2626 2634 try:
2627 2635 ps = self.shell.user_ns['_dh'][-2]
2628 2636 except IndexError:
2629 2637 print 'No previous directory to change to.'
2630 2638 return
2631 2639 # jump to bookmark if needed
2632 2640 else:
2633 2641 if not os.path.isdir(ps) or opts.has_key('b'):
2634 2642 bkms = self.db.get('bookmarks', {})
2635 2643
2636 2644 if bkms.has_key(ps):
2637 2645 target = bkms[ps]
2638 2646 print '(bookmark:%s) -> %s' % (ps,target)
2639 2647 ps = target
2640 2648 else:
2641 2649 if opts.has_key('b'):
2642 2650 error("Bookmark '%s' not found. "
2643 2651 "Use '%%bookmark -l' to see your bookmarks." % ps)
2644 2652 return
2645 2653
2646 2654 # at this point ps should point to the target dir
2647 2655 if ps:
2648 2656 try:
2649 2657 os.chdir(os.path.expanduser(ps))
2650 2658 if self.shell.rc.term_title:
2651 2659 #print 'set term title:',self.shell.rc.term_title # dbg
2652 2660 ttitle = ("IPy:" + (
2653 2661 os.getcwd() == '/' and '/' or \
2654 2662 os.path.basename(os.getcwd())))
2655 2663 platutils.set_term_title(ttitle)
2656 2664 except OSError:
2657 2665 print sys.exc_info()[1]
2658 2666 else:
2659 2667 self.shell.user_ns['_dh'].append(os.getcwd())
2660 2668 else:
2661 2669 os.chdir(self.shell.home_dir)
2662 2670 if self.shell.rc.term_title:
2663 2671 platutils.set_term_title("IPy:~")
2664 2672 self.shell.user_ns['_dh'].append(os.getcwd())
2665 2673 if not 'q' in opts:
2666 2674 print self.shell.user_ns['_dh'][-1]
2667 2675
2668 2676 def magic_dhist(self, parameter_s=''):
2669 2677 """Print your history of visited directories.
2670 2678
2671 2679 %dhist -> print full history\\
2672 2680 %dhist n -> print last n entries only\\
2673 2681 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2674 2682
2675 2683 This history is automatically maintained by the %cd command, and
2676 2684 always available as the global list variable _dh. You can use %cd -<n>
2677 2685 to go to directory number <n>."""
2678 2686
2679 2687 dh = self.shell.user_ns['_dh']
2680 2688 if parameter_s:
2681 2689 try:
2682 2690 args = map(int,parameter_s.split())
2683 2691 except:
2684 2692 self.arg_err(Magic.magic_dhist)
2685 2693 return
2686 2694 if len(args) == 1:
2687 2695 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2688 2696 elif len(args) == 2:
2689 2697 ini,fin = args
2690 2698 else:
2691 2699 self.arg_err(Magic.magic_dhist)
2692 2700 return
2693 2701 else:
2694 2702 ini,fin = 0,len(dh)
2695 2703 nlprint(dh,
2696 2704 header = 'Directory history (kept in _dh)',
2697 2705 start=ini,stop=fin)
2698 2706
2699 2707 def magic_env(self, parameter_s=''):
2700 2708 """List environment variables."""
2701 2709
2702 2710 return os.environ.data
2703 2711
2704 2712 def magic_pushd(self, parameter_s=''):
2705 2713 """Place the current dir on stack and change directory.
2706 2714
2707 2715 Usage:\\
2708 2716 %pushd ['dirname']
2709 2717
2710 2718 %pushd with no arguments does a %pushd to your home directory.
2711 2719 """
2712 2720 if parameter_s == '': parameter_s = '~'
2713 2721 dir_s = self.shell.dir_stack
2714 2722 if len(dir_s)>0 and os.path.expanduser(parameter_s) != \
2715 2723 os.path.expanduser(self.shell.dir_stack[0]):
2716 2724 try:
2717 2725 self.magic_cd(parameter_s)
2718 2726 dir_s.insert(0,os.getcwd().replace(self.home_dir,'~'))
2719 2727 self.magic_dirs()
2720 2728 except:
2721 2729 print 'Invalid directory'
2722 2730 else:
2723 2731 print 'You are already there!'
2724 2732
2725 2733 def magic_popd(self, parameter_s=''):
2726 2734 """Change to directory popped off the top of the stack.
2727 2735 """
2728 2736 if len (self.shell.dir_stack) > 1:
2729 2737 self.shell.dir_stack.pop(0)
2730 2738 self.magic_cd(self.shell.dir_stack[0])
2731 2739 print self.shell.dir_stack[0]
2732 2740 else:
2733 2741 print "You can't remove the starting directory from the stack:",\
2734 2742 self.shell.dir_stack
2735 2743
2736 2744 def magic_dirs(self, parameter_s=''):
2737 2745 """Return the current directory stack."""
2738 2746
2739 2747 return self.shell.dir_stack[:]
2740 2748
2741 2749 def magic_sc(self, parameter_s=''):
2742 2750 """Shell capture - execute a shell command and capture its output.
2743 2751
2744 2752 DEPRECATED. Suboptimal, retained for backwards compatibility.
2745 2753
2746 2754 You should use the form 'var = !command' instead. Example:
2747 2755
2748 2756 "%sc -l myfiles = ls ~" should now be written as
2749 2757
2750 2758 "myfiles = !ls ~"
2751 2759
2752 2760 myfiles.s, myfiles.l and myfiles.n still apply as documented
2753 2761 below.
2754 2762
2755 2763 --
2756 2764 %sc [options] varname=command
2757 2765
2758 2766 IPython will run the given command using commands.getoutput(), and
2759 2767 will then update the user's interactive namespace with a variable
2760 2768 called varname, containing the value of the call. Your command can
2761 2769 contain shell wildcards, pipes, etc.
2762 2770
2763 2771 The '=' sign in the syntax is mandatory, and the variable name you
2764 2772 supply must follow Python's standard conventions for valid names.
2765 2773
2766 2774 (A special format without variable name exists for internal use)
2767 2775
2768 2776 Options:
2769 2777
2770 2778 -l: list output. Split the output on newlines into a list before
2771 2779 assigning it to the given variable. By default the output is stored
2772 2780 as a single string.
2773 2781
2774 2782 -v: verbose. Print the contents of the variable.
2775 2783
2776 2784 In most cases you should not need to split as a list, because the
2777 2785 returned value is a special type of string which can automatically
2778 2786 provide its contents either as a list (split on newlines) or as a
2779 2787 space-separated string. These are convenient, respectively, either
2780 2788 for sequential processing or to be passed to a shell command.
2781 2789
2782 2790 For example:
2783 2791
2784 2792 # Capture into variable a
2785 2793 In [9]: sc a=ls *py
2786 2794
2787 2795 # a is a string with embedded newlines
2788 2796 In [10]: a
2789 2797 Out[10]: 'setup.py\nwin32_manual_post_install.py'
2790 2798
2791 2799 # which can be seen as a list:
2792 2800 In [11]: a.l
2793 2801 Out[11]: ['setup.py', 'win32_manual_post_install.py']
2794 2802
2795 2803 # or as a whitespace-separated string:
2796 2804 In [12]: a.s
2797 2805 Out[12]: 'setup.py win32_manual_post_install.py'
2798 2806
2799 2807 # a.s is useful to pass as a single command line:
2800 2808 In [13]: !wc -l $a.s
2801 2809 146 setup.py
2802 2810 130 win32_manual_post_install.py
2803 2811 276 total
2804 2812
2805 2813 # while the list form is useful to loop over:
2806 2814 In [14]: for f in a.l:
2807 2815 ....: !wc -l $f
2808 2816 ....:
2809 2817 146 setup.py
2810 2818 130 win32_manual_post_install.py
2811 2819
2812 2820 Similiarly, the lists returned by the -l option are also special, in
2813 2821 the sense that you can equally invoke the .s attribute on them to
2814 2822 automatically get a whitespace-separated string from their contents:
2815 2823
2816 2824 In [1]: sc -l b=ls *py
2817 2825
2818 2826 In [2]: b
2819 2827 Out[2]: ['setup.py', 'win32_manual_post_install.py']
2820 2828
2821 2829 In [3]: b.s
2822 2830 Out[3]: 'setup.py win32_manual_post_install.py'
2823 2831
2824 2832 In summary, both the lists and strings used for ouptut capture have
2825 2833 the following special attributes:
2826 2834
2827 2835 .l (or .list) : value as list.
2828 2836 .n (or .nlstr): value as newline-separated string.
2829 2837 .s (or .spstr): value as space-separated string.
2830 2838 """
2831 2839
2832 2840 opts,args = self.parse_options(parameter_s,'lv')
2833 2841 # Try to get a variable name and command to run
2834 2842 try:
2835 2843 # the variable name must be obtained from the parse_options
2836 2844 # output, which uses shlex.split to strip options out.
2837 2845 var,_ = args.split('=',1)
2838 2846 var = var.strip()
2839 2847 # But the the command has to be extracted from the original input
2840 2848 # parameter_s, not on what parse_options returns, to avoid the
2841 2849 # quote stripping which shlex.split performs on it.
2842 2850 _,cmd = parameter_s.split('=',1)
2843 2851 except ValueError:
2844 2852 var,cmd = '',''
2845 2853 # If all looks ok, proceed
2846 2854 out,err = self.shell.getoutputerror(cmd)
2847 2855 if err:
2848 2856 print >> Term.cerr,err
2849 2857 if opts.has_key('l'):
2850 2858 out = SList(out.split('\n'))
2851 2859 else:
2852 2860 out = LSString(out)
2853 2861 if opts.has_key('v'):
2854 2862 print '%s ==\n%s' % (var,pformat(out))
2855 2863 if var:
2856 2864 self.shell.user_ns.update({var:out})
2857 2865 else:
2858 2866 return out
2859 2867
2860 2868 def magic_sx(self, parameter_s=''):
2861 2869 """Shell execute - run a shell command and capture its output.
2862 2870
2863 2871 %sx command
2864 2872
2865 2873 IPython will run the given command using commands.getoutput(), and
2866 2874 return the result formatted as a list (split on '\\n'). Since the
2867 2875 output is _returned_, it will be stored in ipython's regular output
2868 2876 cache Out[N] and in the '_N' automatic variables.
2869 2877
2870 2878 Notes:
2871 2879
2872 2880 1) If an input line begins with '!!', then %sx is automatically
2873 2881 invoked. That is, while:
2874 2882 !ls
2875 2883 causes ipython to simply issue system('ls'), typing
2876 2884 !!ls
2877 2885 is a shorthand equivalent to:
2878 2886 %sx ls
2879 2887
2880 2888 2) %sx differs from %sc in that %sx automatically splits into a list,
2881 2889 like '%sc -l'. The reason for this is to make it as easy as possible
2882 2890 to process line-oriented shell output via further python commands.
2883 2891 %sc is meant to provide much finer control, but requires more
2884 2892 typing.
2885 2893
2886 2894 3) Just like %sc -l, this is a list with special attributes:
2887 2895
2888 2896 .l (or .list) : value as list.
2889 2897 .n (or .nlstr): value as newline-separated string.
2890 2898 .s (or .spstr): value as whitespace-separated string.
2891 2899
2892 2900 This is very useful when trying to use such lists as arguments to
2893 2901 system commands."""
2894 2902
2895 2903 if parameter_s:
2896 2904 out,err = self.shell.getoutputerror(parameter_s)
2897 2905 if err:
2898 2906 print >> Term.cerr,err
2899 2907 return SList(out.split('\n'))
2900 2908
2901 2909 def magic_bg(self, parameter_s=''):
2902 2910 """Run a job in the background, in a separate thread.
2903 2911
2904 2912 For example,
2905 2913
2906 2914 %bg myfunc(x,y,z=1)
2907 2915
2908 2916 will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the
2909 2917 execution starts, a message will be printed indicating the job
2910 2918 number. If your job number is 5, you can use
2911 2919
2912 2920 myvar = jobs.result(5) or myvar = jobs[5].result
2913 2921
2914 2922 to assign this result to variable 'myvar'.
2915 2923
2916 2924 IPython has a job manager, accessible via the 'jobs' object. You can
2917 2925 type jobs? to get more information about it, and use jobs.<TAB> to see
2918 2926 its attributes. All attributes not starting with an underscore are
2919 2927 meant for public use.
2920 2928
2921 2929 In particular, look at the jobs.new() method, which is used to create
2922 2930 new jobs. This magic %bg function is just a convenience wrapper
2923 2931 around jobs.new(), for expression-based jobs. If you want to create a
2924 2932 new job with an explicit function object and arguments, you must call
2925 2933 jobs.new() directly.
2926 2934
2927 2935 The jobs.new docstring also describes in detail several important
2928 2936 caveats associated with a thread-based model for background job
2929 2937 execution. Type jobs.new? for details.
2930 2938
2931 2939 You can check the status of all jobs with jobs.status().
2932 2940
2933 2941 The jobs variable is set by IPython into the Python builtin namespace.
2934 2942 If you ever declare a variable named 'jobs', you will shadow this
2935 2943 name. You can either delete your global jobs variable to regain
2936 2944 access to the job manager, or make a new name and assign it manually
2937 2945 to the manager (stored in IPython's namespace). For example, to
2938 2946 assign the job manager to the Jobs name, use:
2939 2947
2940 2948 Jobs = __builtins__.jobs"""
2941 2949
2942 2950 self.shell.jobs.new(parameter_s,self.shell.user_ns)
2943 2951
2944 2952
2945 2953 def magic_bookmark(self, parameter_s=''):
2946 2954 """Manage IPython's bookmark system.
2947 2955
2948 2956 %bookmark <name> - set bookmark to current dir
2949 2957 %bookmark <name> <dir> - set bookmark to <dir>
2950 2958 %bookmark -l - list all bookmarks
2951 2959 %bookmark -d <name> - remove bookmark
2952 2960 %bookmark -r - remove all bookmarks
2953 2961
2954 2962 You can later on access a bookmarked folder with:
2955 2963 %cd -b <name>
2956 2964 or simply '%cd <name>' if there is no directory called <name> AND
2957 2965 there is such a bookmark defined.
2958 2966
2959 2967 Your bookmarks persist through IPython sessions, but they are
2960 2968 associated with each profile."""
2961 2969
2962 2970 opts,args = self.parse_options(parameter_s,'drl',mode='list')
2963 2971 if len(args) > 2:
2964 2972 error('You can only give at most two arguments')
2965 2973 return
2966 2974
2967 2975 bkms = self.db.get('bookmarks',{})
2968 2976
2969 2977 if opts.has_key('d'):
2970 2978 try:
2971 2979 todel = args[0]
2972 2980 except IndexError:
2973 2981 error('You must provide a bookmark to delete')
2974 2982 else:
2975 2983 try:
2976 2984 del bkms[todel]
2977 2985 except:
2978 2986 error("Can't delete bookmark '%s'" % todel)
2979 2987 elif opts.has_key('r'):
2980 2988 bkms = {}
2981 2989 elif opts.has_key('l'):
2982 2990 bks = bkms.keys()
2983 2991 bks.sort()
2984 2992 if bks:
2985 2993 size = max(map(len,bks))
2986 2994 else:
2987 2995 size = 0
2988 2996 fmt = '%-'+str(size)+'s -> %s'
2989 2997 print 'Current bookmarks:'
2990 2998 for bk in bks:
2991 2999 print fmt % (bk,bkms[bk])
2992 3000 else:
2993 3001 if not args:
2994 3002 error("You must specify the bookmark name")
2995 3003 elif len(args)==1:
2996 3004 bkms[args[0]] = os.getcwd()
2997 3005 elif len(args)==2:
2998 3006 bkms[args[0]] = args[1]
2999 3007 self.db['bookmarks'] = bkms
3000 3008
3001 3009 def magic_pycat(self, parameter_s=''):
3002 3010 """Show a syntax-highlighted file through a pager.
3003 3011
3004 3012 This magic is similar to the cat utility, but it will assume the file
3005 3013 to be Python source and will show it with syntax highlighting. """
3006 3014
3007 3015 try:
3008 3016 filename = get_py_filename(parameter_s)
3009 3017 cont = file_read(filename)
3010 3018 except IOError:
3011 3019 try:
3012 3020 cont = eval(parameter_s,self.user_ns)
3013 3021 except NameError:
3014 3022 cont = None
3015 3023 if cont is None:
3016 3024 print "Error: no such file or variable"
3017 3025 return
3018 3026
3019 3027 page(self.shell.pycolorize(cont),
3020 3028 screen_lines=self.shell.rc.screen_length)
3021 3029
3022 3030 def magic_cpaste(self, parameter_s=''):
3023 3031 """Allows you to paste & execute a pre-formatted code block from clipboard
3024 3032
3025 3033 You must terminate the block with '--' (two minus-signs) alone on the
3026 3034 line. You can also provide your own sentinel with '%paste -s %%' ('%%'
3027 3035 is the new sentinel for this operation)
3028 3036
3029 3037 The block is dedented prior to execution to enable execution of
3030 3038 method definitions. '>' characters at the beginning of a line is
3031 3039 ignored, to allow pasting directly from e-mails. The executed block
3032 3040 is also assigned to variable named 'pasted_block' for later editing
3033 3041 with '%edit pasted_block'.
3034 3042
3035 3043 You can also pass a variable name as an argument, e.g. '%cpaste foo'.
3036 3044 This assigns the pasted block to variable 'foo' as string, without
3037 3045 dedenting or executing it.
3038 3046
3039 3047 Do not be alarmed by garbled output on Windows (it's a readline bug).
3040 3048 Just press enter and type -- (and press enter again) and the block
3041 3049 will be what was just pasted.
3042 3050
3043 3051 IPython statements (magics, shell escapes) are not supported (yet).
3044 3052 """
3045 3053 opts,args = self.parse_options(parameter_s,'s:',mode='string')
3046 3054 par = args.strip()
3047 3055 sentinel = opts.get('s','--')
3048 3056
3049 3057 from IPython import iplib
3050 3058 lines = []
3051 3059 print "Pasting code; enter '%s' alone on the line to stop." % sentinel
3052 3060 while 1:
3053 3061 l = iplib.raw_input_original(':')
3054 3062 if l ==sentinel:
3055 3063 break
3056 3064 lines.append(l.lstrip('>'))
3057 3065 block = "\n".join(lines) + '\n'
3058 3066 #print "block:\n",block
3059 3067 if not par:
3060 3068 b = textwrap.dedent(block)
3061 3069 exec b in self.user_ns
3062 3070 self.user_ns['pasted_block'] = b
3063 3071 else:
3064 3072 self.user_ns[par] = block
3065 3073 print "Block assigned to '%s'" % par
3066 3074
3067 3075 def magic_quickref(self,arg):
3068 3076 """ Show a quick reference sheet """
3069 3077 import IPython.usage
3070 3078 qr = IPython.usage.quick_reference + self.magic_magic('-brief')
3071 3079
3072 3080 page(qr)
3073 3081
3074 3082 def magic_upgrade(self,arg):
3075 3083 """ Upgrade your IPython installation
3076 3084
3077 3085 This will copy the config files that don't yet exist in your
3078 3086 ipython dir from the system config dir. Use this after upgrading
3079 3087 IPython if you don't wish to delete your .ipython dir.
3080 3088
3081 3089 Call with -nolegacy to get rid of ipythonrc* files (recommended for
3082 3090 new users)
3083 3091
3084 3092 """
3085 3093 ip = self.getapi()
3086 3094 ipinstallation = path(IPython.__file__).dirname()
3087 3095 upgrade_script = '%s "%s"' % (sys.executable,ipinstallation / 'upgrade_dir.py')
3088 3096 src_config = ipinstallation / 'UserConfig'
3089 3097 userdir = path(ip.options.ipythondir)
3090 3098 cmd = '%s "%s" "%s"' % (upgrade_script, src_config, userdir)
3091 3099 print ">",cmd
3092 3100 shell(cmd)
3093 3101 if arg == '-nolegacy':
3094 3102 legacy = userdir.files('ipythonrc*')
3095 3103 print "Nuking legacy files:",legacy
3096 3104
3097 3105 [p.remove() for p in legacy]
3098 3106 suffix = (sys.platform == 'win32' and '.ini' or '')
3099 3107 (userdir / ('ipythonrc' + suffix)).write_text('# Empty, see ipy_user_conf.py\n')
3100 3108
3101 3109 # end Magic
@@ -1,1756 +1,1763 b''
1 1 # -*- coding: utf-8 -*-
2 2 """
3 3 General purpose utilities.
4 4
5 5 This is a grab-bag of stuff I find useful in most programs I write. Some of
6 6 these things are also convenient when working at the command line.
7 7
8 $Id: genutils.py 2154 2007-03-19 00:10:07Z fperez $"""
8 $Id: genutils.py 2190 2007-03-30 18:35:46Z fperez $"""
9 9
10 10 #*****************************************************************************
11 11 # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu>
12 12 #
13 13 # Distributed under the terms of the BSD License. The full license is in
14 14 # the file COPYING, distributed as part of this software.
15 15 #*****************************************************************************
16 16
17 17 from IPython import Release
18 18 __author__ = '%s <%s>' % Release.authors['Fernando']
19 19 __license__ = Release.license
20 20
21 21 #****************************************************************************
22 22 # required modules from the Python standard library
23 23 import __main__
24 24 import commands
25 25 import os
26 26 import re
27 27 import shlex
28 28 import shutil
29 29 import sys
30 30 import tempfile
31 31 import time
32 32 import types
33 33 import warnings
34 34
35 35 # Other IPython utilities
36 36 from IPython.Itpl import Itpl,itpl,printpl
37 37 from IPython import DPyGetOpt
38 38 from path import path
39 39 if os.name == "nt":
40 40 from IPython.winconsole import get_console_size
41 41
42 42 #****************************************************************************
43 43 # Exceptions
44 44 class Error(Exception):
45 45 """Base class for exceptions in this module."""
46 46 pass
47 47
48 48 #----------------------------------------------------------------------------
49 49 class IOStream:
50 50 def __init__(self,stream,fallback):
51 51 if not hasattr(stream,'write') or not hasattr(stream,'flush'):
52 52 stream = fallback
53 53 self.stream = stream
54 54 self._swrite = stream.write
55 55 self.flush = stream.flush
56 56
57 57 def write(self,data):
58 58 try:
59 59 self._swrite(data)
60 60 except:
61 61 try:
62 62 # print handles some unicode issues which may trip a plain
63 63 # write() call. Attempt to emulate write() by using a
64 64 # trailing comma
65 65 print >> self.stream, data,
66 66 except:
67 67 # if we get here, something is seriously broken.
68 68 print >> sys.stderr, \
69 69 'ERROR - failed to write data to stream:', self.stream
70 70
71 71 def close(self):
72 72 pass
73 73
74 74
75 75 class IOTerm:
76 76 """ Term holds the file or file-like objects for handling I/O operations.
77 77
78 78 These are normally just sys.stdin, sys.stdout and sys.stderr but for
79 79 Windows they can can replaced to allow editing the strings before they are
80 80 displayed."""
81 81
82 82 # In the future, having IPython channel all its I/O operations through
83 83 # this class will make it easier to embed it into other environments which
84 84 # are not a normal terminal (such as a GUI-based shell)
85 85 def __init__(self,cin=None,cout=None,cerr=None):
86 86 self.cin = IOStream(cin,sys.stdin)
87 87 self.cout = IOStream(cout,sys.stdout)
88 88 self.cerr = IOStream(cerr,sys.stderr)
89 89
90 90 # Global variable to be used for all I/O
91 91 Term = IOTerm()
92 92
93 93 import IPython.rlineimpl as readline
94 94 # Remake Term to use the readline i/o facilities
95 95 if sys.platform == 'win32' and readline.have_readline:
96 96
97 97 Term = IOTerm(cout=readline._outputfile,cerr=readline._outputfile)
98 98
99 99
100 100 #****************************************************************************
101 101 # Generic warning/error printer, used by everything else
102 102 def warn(msg,level=2,exit_val=1):
103 103 """Standard warning printer. Gives formatting consistency.
104 104
105 105 Output is sent to Term.cerr (sys.stderr by default).
106 106
107 107 Options:
108 108
109 109 -level(2): allows finer control:
110 110 0 -> Do nothing, dummy function.
111 111 1 -> Print message.
112 112 2 -> Print 'WARNING:' + message. (Default level).
113 113 3 -> Print 'ERROR:' + message.
114 114 4 -> Print 'FATAL ERROR:' + message and trigger a sys.exit(exit_val).
115 115
116 116 -exit_val (1): exit value returned by sys.exit() for a level 4
117 117 warning. Ignored for all other levels."""
118 118
119 119 if level>0:
120 120 header = ['','','WARNING: ','ERROR: ','FATAL ERROR: ']
121 121 print >> Term.cerr, '%s%s' % (header[level],msg)
122 122 if level == 4:
123 123 print >> Term.cerr,'Exiting.\n'
124 124 sys.exit(exit_val)
125 125
126 126 def info(msg):
127 127 """Equivalent to warn(msg,level=1)."""
128 128
129 129 warn(msg,level=1)
130 130
131 131 def error(msg):
132 132 """Equivalent to warn(msg,level=3)."""
133 133
134 134 warn(msg,level=3)
135 135
136 136 def fatal(msg,exit_val=1):
137 137 """Equivalent to warn(msg,exit_val=exit_val,level=4)."""
138 138
139 139 warn(msg,exit_val=exit_val,level=4)
140 140
141 141 #---------------------------------------------------------------------------
142 142 # Debugging routines
143 143 #
144 144 def debugx(expr,pre_msg=''):
145 145 """Print the value of an expression from the caller's frame.
146 146
147 147 Takes an expression, evaluates it in the caller's frame and prints both
148 148 the given expression and the resulting value (as well as a debug mark
149 149 indicating the name of the calling function. The input must be of a form
150 150 suitable for eval().
151 151
152 152 An optional message can be passed, which will be prepended to the printed
153 153 expr->value pair."""
154 154
155 155 cf = sys._getframe(1)
156 156 print '[DBG:%s] %s%s -> %r' % (cf.f_code.co_name,pre_msg,expr,
157 157 eval(expr,cf.f_globals,cf.f_locals))
158 158
159 159 # deactivate it by uncommenting the following line, which makes it a no-op
160 160 #def debugx(expr,pre_msg=''): pass
161 161
162 162 #----------------------------------------------------------------------------
163 163 StringTypes = types.StringTypes
164 164
165 165 # Basic timing functionality
166 166
167 167 # If possible (Unix), use the resource module instead of time.clock()
168 168 try:
169 169 import resource
170 170 def clocku():
171 171 """clocku() -> floating point number
172 172
173 173 Return the *USER* CPU time in seconds since the start of the process.
174 174 This is done via a call to resource.getrusage, so it avoids the
175 175 wraparound problems in time.clock()."""
176 176
177 177 return resource.getrusage(resource.RUSAGE_SELF)[0]
178 178
179 179 def clocks():
180 180 """clocks() -> floating point number
181 181
182 182 Return the *SYSTEM* CPU time in seconds since the start of the process.
183 183 This is done via a call to resource.getrusage, so it avoids the
184 184 wraparound problems in time.clock()."""
185 185
186 186 return resource.getrusage(resource.RUSAGE_SELF)[1]
187 187
188 188 def clock():
189 189 """clock() -> floating point number
190 190
191 191 Return the *TOTAL USER+SYSTEM* CPU time in seconds since the start of
192 192 the process. This is done via a call to resource.getrusage, so it
193 193 avoids the wraparound problems in time.clock()."""
194 194
195 195 u,s = resource.getrusage(resource.RUSAGE_SELF)[:2]
196 196 return u+s
197 197
198 198 def clock2():
199 199 """clock2() -> (t_user,t_system)
200 200
201 201 Similar to clock(), but return a tuple of user/system times."""
202 202 return resource.getrusage(resource.RUSAGE_SELF)[:2]
203 203
204 204 except ImportError:
205 205 # There is no distinction of user/system time under windows, so we just use
206 206 # time.clock() for everything...
207 207 clocku = clocks = clock = time.clock
208 208 def clock2():
209 209 """Under windows, system CPU time can't be measured.
210 210
211 211 This just returns clock() and zero."""
212 212 return time.clock(),0.0
213 213
214 214 def timings_out(reps,func,*args,**kw):
215 215 """timings_out(reps,func,*args,**kw) -> (t_total,t_per_call,output)
216 216
217 217 Execute a function reps times, return a tuple with the elapsed total
218 218 CPU time in seconds, the time per call and the function's output.
219 219
220 220 Under Unix, the return value is the sum of user+system time consumed by
221 221 the process, computed via the resource module. This prevents problems
222 222 related to the wraparound effect which the time.clock() function has.
223 223
224 224 Under Windows the return value is in wall clock seconds. See the
225 225 documentation for the time module for more details."""
226 226
227 227 reps = int(reps)
228 228 assert reps >=1, 'reps must be >= 1'
229 229 if reps==1:
230 230 start = clock()
231 231 out = func(*args,**kw)
232 232 tot_time = clock()-start
233 233 else:
234 234 rng = xrange(reps-1) # the last time is executed separately to store output
235 235 start = clock()
236 236 for dummy in rng: func(*args,**kw)
237 237 out = func(*args,**kw) # one last time
238 238 tot_time = clock()-start
239 239 av_time = tot_time / reps
240 240 return tot_time,av_time,out
241 241
242 242 def timings(reps,func,*args,**kw):
243 243 """timings(reps,func,*args,**kw) -> (t_total,t_per_call)
244 244
245 245 Execute a function reps times, return a tuple with the elapsed total CPU
246 246 time in seconds and the time per call. These are just the first two values
247 247 in timings_out()."""
248 248
249 249 return timings_out(reps,func,*args,**kw)[0:2]
250 250
251 251 def timing(func,*args,**kw):
252 252 """timing(func,*args,**kw) -> t_total
253 253
254 254 Execute a function once, return the elapsed total CPU time in
255 255 seconds. This is just the first value in timings_out()."""
256 256
257 257 return timings_out(1,func,*args,**kw)[0]
258 258
259 259 #****************************************************************************
260 260 # file and system
261 261
262 262 def arg_split(s,posix=False):
263 263 """Split a command line's arguments in a shell-like manner.
264 264
265 265 This is a modified version of the standard library's shlex.split()
266 266 function, but with a default of posix=False for splitting, so that quotes
267 267 in inputs are respected."""
268
268
269 # XXX - there may be unicode-related problems here!!! I'm not sure that
270 # shlex is truly unicode-safe, so it might be necessary to do
271 #
272 # s = s.encode(sys.stdin.encoding)
273 #
274 # first, to ensure that shlex gets a normal string. Input from anyone who
275 # knows more about unicode and shlex than I would be good to have here...
269 276 lex = shlex.shlex(s, posix=posix)
270 277 lex.whitespace_split = True
271 278 return list(lex)
272 279
273 280 def system(cmd,verbose=0,debug=0,header=''):
274 281 """Execute a system command, return its exit status.
275 282
276 283 Options:
277 284
278 285 - verbose (0): print the command to be executed.
279 286
280 287 - debug (0): only print, do not actually execute.
281 288
282 289 - header (''): Header to print on screen prior to the executed command (it
283 290 is only prepended to the command, no newlines are added).
284 291
285 292 Note: a stateful version of this function is available through the
286 293 SystemExec class."""
287 294
288 295 stat = 0
289 296 if verbose or debug: print header+cmd
290 297 sys.stdout.flush()
291 298 if not debug: stat = os.system(cmd)
292 299 return stat
293 300
294 301 # This function is used by ipython in a lot of places to make system calls.
295 302 # We need it to be slightly different under win32, due to the vagaries of
296 303 # 'network shares'. A win32 override is below.
297 304
298 305 def shell(cmd,verbose=0,debug=0,header=''):
299 306 """Execute a command in the system shell, always return None.
300 307
301 308 Options:
302 309
303 310 - verbose (0): print the command to be executed.
304 311
305 312 - debug (0): only print, do not actually execute.
306 313
307 314 - header (''): Header to print on screen prior to the executed command (it
308 315 is only prepended to the command, no newlines are added).
309 316
310 317 Note: this is similar to genutils.system(), but it returns None so it can
311 318 be conveniently used in interactive loops without getting the return value
312 319 (typically 0) printed many times."""
313 320
314 321 stat = 0
315 322 if verbose or debug: print header+cmd
316 323 # flush stdout so we don't mangle python's buffering
317 324 sys.stdout.flush()
318 325 if not debug:
319 326 os.system(cmd)
320 327
321 328 # override shell() for win32 to deal with network shares
322 329 if os.name in ('nt','dos'):
323 330
324 331 shell_ori = shell
325 332
326 333 def shell(cmd,verbose=0,debug=0,header=''):
327 334 if os.getcwd().startswith(r"\\"):
328 335 path = os.getcwd()
329 336 # change to c drive (cannot be on UNC-share when issuing os.system,
330 337 # as cmd.exe cannot handle UNC addresses)
331 338 os.chdir("c:")
332 339 # issue pushd to the UNC-share and then run the command
333 340 try:
334 341 shell_ori('"pushd %s&&"'%path+cmd,verbose,debug,header)
335 342 finally:
336 343 os.chdir(path)
337 344 else:
338 345 shell_ori(cmd,verbose,debug,header)
339 346
340 347 shell.__doc__ = shell_ori.__doc__
341 348
342 349 def getoutput(cmd,verbose=0,debug=0,header='',split=0):
343 350 """Dummy substitute for perl's backquotes.
344 351
345 352 Executes a command and returns the output.
346 353
347 354 Accepts the same arguments as system(), plus:
348 355
349 356 - split(0): if true, the output is returned as a list split on newlines.
350 357
351 358 Note: a stateful version of this function is available through the
352 359 SystemExec class.
353 360
354 361 This is pretty much deprecated and rarely used,
355 362 genutils.getoutputerror may be what you need.
356 363
357 364 """
358 365
359 366 if verbose or debug: print header+cmd
360 367 if not debug:
361 368 output = os.popen(cmd).read()
362 369 # stipping last \n is here for backwards compat.
363 370 if output.endswith('\n'):
364 371 output = output[:-1]
365 372 if split:
366 373 return output.split('\n')
367 374 else:
368 375 return output
369 376
370 377 def getoutputerror(cmd,verbose=0,debug=0,header='',split=0):
371 378 """Return (standard output,standard error) of executing cmd in a shell.
372 379
373 380 Accepts the same arguments as system(), plus:
374 381
375 382 - split(0): if true, each of stdout/err is returned as a list split on
376 383 newlines.
377 384
378 385 Note: a stateful version of this function is available through the
379 386 SystemExec class."""
380 387
381 388 if verbose or debug: print header+cmd
382 389 if not cmd:
383 390 if split:
384 391 return [],[]
385 392 else:
386 393 return '',''
387 394 if not debug:
388 395 pin,pout,perr = os.popen3(cmd)
389 396 tout = pout.read().rstrip()
390 397 terr = perr.read().rstrip()
391 398 pin.close()
392 399 pout.close()
393 400 perr.close()
394 401 if split:
395 402 return tout.split('\n'),terr.split('\n')
396 403 else:
397 404 return tout,terr
398 405
399 406 # for compatibility with older naming conventions
400 407 xsys = system
401 408 bq = getoutput
402 409
403 410 class SystemExec:
404 411 """Access the system and getoutput functions through a stateful interface.
405 412
406 413 Note: here we refer to the system and getoutput functions from this
407 414 library, not the ones from the standard python library.
408 415
409 416 This class offers the system and getoutput functions as methods, but the
410 417 verbose, debug and header parameters can be set for the instance (at
411 418 creation time or later) so that they don't need to be specified on each
412 419 call.
413 420
414 421 For efficiency reasons, there's no way to override the parameters on a
415 422 per-call basis other than by setting instance attributes. If you need
416 423 local overrides, it's best to directly call system() or getoutput().
417 424
418 425 The following names are provided as alternate options:
419 426 - xsys: alias to system
420 427 - bq: alias to getoutput
421 428
422 429 An instance can then be created as:
423 430 >>> sysexec = SystemExec(verbose=1,debug=0,header='Calling: ')
424 431
425 432 And used as:
426 433 >>> sysexec.xsys('pwd')
427 434 >>> dirlist = sysexec.bq('ls -l')
428 435 """
429 436
430 437 def __init__(self,verbose=0,debug=0,header='',split=0):
431 438 """Specify the instance's values for verbose, debug and header."""
432 439 setattr_list(self,'verbose debug header split')
433 440
434 441 def system(self,cmd):
435 442 """Stateful interface to system(), with the same keyword parameters."""
436 443
437 444 system(cmd,self.verbose,self.debug,self.header)
438 445
439 446 def shell(self,cmd):
440 447 """Stateful interface to shell(), with the same keyword parameters."""
441 448
442 449 shell(cmd,self.verbose,self.debug,self.header)
443 450
444 451 xsys = system # alias
445 452
446 453 def getoutput(self,cmd):
447 454 """Stateful interface to getoutput()."""
448 455
449 456 return getoutput(cmd,self.verbose,self.debug,self.header,self.split)
450 457
451 458 def getoutputerror(self,cmd):
452 459 """Stateful interface to getoutputerror()."""
453 460
454 461 return getoutputerror(cmd,self.verbose,self.debug,self.header,self.split)
455 462
456 463 bq = getoutput # alias
457 464
458 465 #-----------------------------------------------------------------------------
459 466 def mutex_opts(dict,ex_op):
460 467 """Check for presence of mutually exclusive keys in a dict.
461 468
462 469 Call: mutex_opts(dict,[[op1a,op1b],[op2a,op2b]...]"""
463 470 for op1,op2 in ex_op:
464 471 if op1 in dict and op2 in dict:
465 472 raise ValueError,'\n*** ERROR in Arguments *** '\
466 473 'Options '+op1+' and '+op2+' are mutually exclusive.'
467 474
468 475 #-----------------------------------------------------------------------------
469 476 def get_py_filename(name):
470 477 """Return a valid python filename in the current directory.
471 478
472 479 If the given name is not a file, it adds '.py' and searches again.
473 480 Raises IOError with an informative message if the file isn't found."""
474 481
475 482 name = os.path.expanduser(name)
476 483 if not os.path.isfile(name) and not name.endswith('.py'):
477 484 name += '.py'
478 485 if os.path.isfile(name):
479 486 return name
480 487 else:
481 488 raise IOError,'File `%s` not found.' % name
482 489
483 490 #-----------------------------------------------------------------------------
484 491 def filefind(fname,alt_dirs = None):
485 492 """Return the given filename either in the current directory, if it
486 493 exists, or in a specified list of directories.
487 494
488 495 ~ expansion is done on all file and directory names.
489 496
490 497 Upon an unsuccessful search, raise an IOError exception."""
491 498
492 499 if alt_dirs is None:
493 500 try:
494 501 alt_dirs = get_home_dir()
495 502 except HomeDirError:
496 503 alt_dirs = os.getcwd()
497 504 search = [fname] + list_strings(alt_dirs)
498 505 search = map(os.path.expanduser,search)
499 506 #print 'search list for',fname,'list:',search # dbg
500 507 fname = search[0]
501 508 if os.path.isfile(fname):
502 509 return fname
503 510 for direc in search[1:]:
504 511 testname = os.path.join(direc,fname)
505 512 #print 'testname',testname # dbg
506 513 if os.path.isfile(testname):
507 514 return testname
508 515 raise IOError,'File' + `fname` + \
509 516 ' not found in current or supplied directories:' + `alt_dirs`
510 517
511 518 #----------------------------------------------------------------------------
512 519 def file_read(filename):
513 520 """Read a file and close it. Returns the file source."""
514 521 fobj = open(filename,'r');
515 522 source = fobj.read();
516 523 fobj.close()
517 524 return source
518 525
519 526 def file_readlines(filename):
520 527 """Read a file and close it. Returns the file source using readlines()."""
521 528 fobj = open(filename,'r');
522 529 lines = fobj.readlines();
523 530 fobj.close()
524 531 return lines
525 532
526 533 #----------------------------------------------------------------------------
527 534 def target_outdated(target,deps):
528 535 """Determine whether a target is out of date.
529 536
530 537 target_outdated(target,deps) -> 1/0
531 538
532 539 deps: list of filenames which MUST exist.
533 540 target: single filename which may or may not exist.
534 541
535 542 If target doesn't exist or is older than any file listed in deps, return
536 543 true, otherwise return false.
537 544 """
538 545 try:
539 546 target_time = os.path.getmtime(target)
540 547 except os.error:
541 548 return 1
542 549 for dep in deps:
543 550 dep_time = os.path.getmtime(dep)
544 551 if dep_time > target_time:
545 552 #print "For target",target,"Dep failed:",dep # dbg
546 553 #print "times (dep,tar):",dep_time,target_time # dbg
547 554 return 1
548 555 return 0
549 556
550 557 #-----------------------------------------------------------------------------
551 558 def target_update(target,deps,cmd):
552 559 """Update a target with a given command given a list of dependencies.
553 560
554 561 target_update(target,deps,cmd) -> runs cmd if target is outdated.
555 562
556 563 This is just a wrapper around target_outdated() which calls the given
557 564 command if target is outdated."""
558 565
559 566 if target_outdated(target,deps):
560 567 xsys(cmd)
561 568
562 569 #----------------------------------------------------------------------------
563 570 def unquote_ends(istr):
564 571 """Remove a single pair of quotes from the endpoints of a string."""
565 572
566 573 if not istr:
567 574 return istr
568 575 if (istr[0]=="'" and istr[-1]=="'") or \
569 576 (istr[0]=='"' and istr[-1]=='"'):
570 577 return istr[1:-1]
571 578 else:
572 579 return istr
573 580
574 581 #----------------------------------------------------------------------------
575 582 def process_cmdline(argv,names=[],defaults={},usage=''):
576 583 """ Process command-line options and arguments.
577 584
578 585 Arguments:
579 586
580 587 - argv: list of arguments, typically sys.argv.
581 588
582 589 - names: list of option names. See DPyGetOpt docs for details on options
583 590 syntax.
584 591
585 592 - defaults: dict of default values.
586 593
587 594 - usage: optional usage notice to print if a wrong argument is passed.
588 595
589 596 Return a dict of options and a list of free arguments."""
590 597
591 598 getopt = DPyGetOpt.DPyGetOpt()
592 599 getopt.setIgnoreCase(0)
593 600 getopt.parseConfiguration(names)
594 601
595 602 try:
596 603 getopt.processArguments(argv)
597 604 except:
598 605 print usage
599 606 warn(`sys.exc_value`,level=4)
600 607
601 608 defaults.update(getopt.optionValues)
602 609 args = getopt.freeValues
603 610
604 611 return defaults,args
605 612
606 613 #----------------------------------------------------------------------------
607 614 def optstr2types(ostr):
608 615 """Convert a string of option names to a dict of type mappings.
609 616
610 617 optstr2types(str) -> {None:'string_opts',int:'int_opts',float:'float_opts'}
611 618
612 619 This is used to get the types of all the options in a string formatted
613 620 with the conventions of DPyGetOpt. The 'type' None is used for options
614 621 which are strings (they need no further conversion). This function's main
615 622 use is to get a typemap for use with read_dict().
616 623 """
617 624
618 625 typeconv = {None:'',int:'',float:''}
619 626 typemap = {'s':None,'i':int,'f':float}
620 627 opt_re = re.compile(r'([\w]*)([^:=]*:?=?)([sif]?)')
621 628
622 629 for w in ostr.split():
623 630 oname,alias,otype = opt_re.match(w).groups()
624 631 if otype == '' or alias == '!': # simple switches are integers too
625 632 otype = 'i'
626 633 typeconv[typemap[otype]] += oname + ' '
627 634 return typeconv
628 635
629 636 #----------------------------------------------------------------------------
630 637 def read_dict(filename,type_conv=None,**opt):
631 638
632 639 """Read a dictionary of key=value pairs from an input file, optionally
633 640 performing conversions on the resulting values.
634 641
635 642 read_dict(filename,type_conv,**opt) -> dict
636 643
637 644 Only one value per line is accepted, the format should be
638 645 # optional comments are ignored
639 646 key value\n
640 647
641 648 Args:
642 649
643 650 - type_conv: A dictionary specifying which keys need to be converted to
644 651 which types. By default all keys are read as strings. This dictionary
645 652 should have as its keys valid conversion functions for strings
646 653 (int,long,float,complex, or your own). The value for each key
647 654 (converter) should be a whitespace separated string containing the names
648 655 of all the entries in the file to be converted using that function. For
649 656 keys to be left alone, use None as the conversion function (only needed
650 657 with purge=1, see below).
651 658
652 659 - opt: dictionary with extra options as below (default in parens)
653 660
654 661 purge(0): if set to 1, all keys *not* listed in type_conv are purged out
655 662 of the dictionary to be returned. If purge is going to be used, the
656 663 set of keys to be left as strings also has to be explicitly specified
657 664 using the (non-existent) conversion function None.
658 665
659 666 fs(None): field separator. This is the key/value separator to be used
660 667 when parsing the file. The None default means any whitespace [behavior
661 668 of string.split()].
662 669
663 670 strip(0): if 1, strip string values of leading/trailinig whitespace.
664 671
665 672 warn(1): warning level if requested keys are not found in file.
666 673 - 0: silently ignore.
667 674 - 1: inform but proceed.
668 675 - 2: raise KeyError exception.
669 676
670 677 no_empty(0): if 1, remove keys with whitespace strings as a value.
671 678
672 679 unique([]): list of keys (or space separated string) which can't be
673 680 repeated. If one such key is found in the file, each new instance
674 681 overwrites the previous one. For keys not listed here, the behavior is
675 682 to make a list of all appearances.
676 683
677 684 Example:
678 685 If the input file test.ini has:
679 686 i 3
680 687 x 4.5
681 688 y 5.5
682 689 s hi ho
683 690 Then:
684 691
685 692 >>> type_conv={int:'i',float:'x',None:'s'}
686 693 >>> read_dict('test.ini')
687 694 {'i': '3', 's': 'hi ho', 'x': '4.5', 'y': '5.5'}
688 695 >>> read_dict('test.ini',type_conv)
689 696 {'i': 3, 's': 'hi ho', 'x': 4.5, 'y': '5.5'}
690 697 >>> read_dict('test.ini',type_conv,purge=1)
691 698 {'i': 3, 's': 'hi ho', 'x': 4.5}
692 699 """
693 700
694 701 # starting config
695 702 opt.setdefault('purge',0)
696 703 opt.setdefault('fs',None) # field sep defaults to any whitespace
697 704 opt.setdefault('strip',0)
698 705 opt.setdefault('warn',1)
699 706 opt.setdefault('no_empty',0)
700 707 opt.setdefault('unique','')
701 708 if type(opt['unique']) in StringTypes:
702 709 unique_keys = qw(opt['unique'])
703 710 elif type(opt['unique']) in (types.TupleType,types.ListType):
704 711 unique_keys = opt['unique']
705 712 else:
706 713 raise ValueError, 'Unique keys must be given as a string, List or Tuple'
707 714
708 715 dict = {}
709 716 # first read in table of values as strings
710 717 file = open(filename,'r')
711 718 for line in file.readlines():
712 719 line = line.strip()
713 720 if len(line) and line[0]=='#': continue
714 721 if len(line)>0:
715 722 lsplit = line.split(opt['fs'],1)
716 723 try:
717 724 key,val = lsplit
718 725 except ValueError:
719 726 key,val = lsplit[0],''
720 727 key = key.strip()
721 728 if opt['strip']: val = val.strip()
722 729 if val == "''" or val == '""': val = ''
723 730 if opt['no_empty'] and (val=='' or val.isspace()):
724 731 continue
725 732 # if a key is found more than once in the file, build a list
726 733 # unless it's in the 'unique' list. In that case, last found in file
727 734 # takes precedence. User beware.
728 735 try:
729 736 if dict[key] and key in unique_keys:
730 737 dict[key] = val
731 738 elif type(dict[key]) is types.ListType:
732 739 dict[key].append(val)
733 740 else:
734 741 dict[key] = [dict[key],val]
735 742 except KeyError:
736 743 dict[key] = val
737 744 # purge if requested
738 745 if opt['purge']:
739 746 accepted_keys = qwflat(type_conv.values())
740 747 for key in dict.keys():
741 748 if key in accepted_keys: continue
742 749 del(dict[key])
743 750 # now convert if requested
744 751 if type_conv==None: return dict
745 752 conversions = type_conv.keys()
746 753 try: conversions.remove(None)
747 754 except: pass
748 755 for convert in conversions:
749 756 for val in qw(type_conv[convert]):
750 757 try:
751 758 dict[val] = convert(dict[val])
752 759 except KeyError,e:
753 760 if opt['warn'] == 0:
754 761 pass
755 762 elif opt['warn'] == 1:
756 763 print >>sys.stderr, 'Warning: key',val,\
757 764 'not found in file',filename
758 765 elif opt['warn'] == 2:
759 766 raise KeyError,e
760 767 else:
761 768 raise ValueError,'Warning level must be 0,1 or 2'
762 769
763 770 return dict
764 771
765 772 #----------------------------------------------------------------------------
766 773 def flag_calls(func):
767 774 """Wrap a function to detect and flag when it gets called.
768 775
769 776 This is a decorator which takes a function and wraps it in a function with
770 777 a 'called' attribute. wrapper.called is initialized to False.
771 778
772 779 The wrapper.called attribute is set to False right before each call to the
773 780 wrapped function, so if the call fails it remains False. After the call
774 781 completes, wrapper.called is set to True and the output is returned.
775 782
776 783 Testing for truth in wrapper.called allows you to determine if a call to
777 784 func() was attempted and succeeded."""
778 785
779 786 def wrapper(*args,**kw):
780 787 wrapper.called = False
781 788 out = func(*args,**kw)
782 789 wrapper.called = True
783 790 return out
784 791
785 792 wrapper.called = False
786 793 wrapper.__doc__ = func.__doc__
787 794 return wrapper
788 795
789 796 #----------------------------------------------------------------------------
790 797 class HomeDirError(Error):
791 798 pass
792 799
793 800 def get_home_dir():
794 801 """Return the closest possible equivalent to a 'home' directory.
795 802
796 803 We first try $HOME. Absent that, on NT it's $HOMEDRIVE\$HOMEPATH.
797 804
798 805 Currently only Posix and NT are implemented, a HomeDirError exception is
799 806 raised for all other OSes. """
800 807
801 808 isdir = os.path.isdir
802 809 env = os.environ
803 810 try:
804 811 homedir = env['HOME']
805 812 if not isdir(homedir):
806 813 # in case a user stuck some string which does NOT resolve to a
807 814 # valid path, it's as good as if we hadn't foud it
808 815 raise KeyError
809 816 return homedir
810 817 except KeyError:
811 818 if os.name == 'posix':
812 819 raise HomeDirError,'undefined $HOME, IPython can not proceed.'
813 820 elif os.name == 'nt':
814 821 # For some strange reason, win9x returns 'nt' for os.name.
815 822 try:
816 823 homedir = os.path.join(env['HOMEDRIVE'],env['HOMEPATH'])
817 824 if not isdir(homedir):
818 825 homedir = os.path.join(env['USERPROFILE'])
819 826 if not isdir(homedir):
820 827 raise HomeDirError
821 828 return homedir
822 829 except:
823 830 try:
824 831 # Use the registry to get the 'My Documents' folder.
825 832 import _winreg as wreg
826 833 key = wreg.OpenKey(wreg.HKEY_CURRENT_USER,
827 834 "Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders")
828 835 homedir = wreg.QueryValueEx(key,'Personal')[0]
829 836 key.Close()
830 837 if not isdir(homedir):
831 838 e = ('Invalid "Personal" folder registry key '
832 839 'typically "My Documents".\n'
833 840 'Value: %s\n'
834 841 'This is not a valid directory on your system.' %
835 842 homedir)
836 843 raise HomeDirError(e)
837 844 return homedir
838 845 except HomeDirError:
839 846 raise
840 847 except:
841 848 return 'C:\\'
842 849 elif os.name == 'dos':
843 850 # Desperate, may do absurd things in classic MacOS. May work under DOS.
844 851 return 'C:\\'
845 852 else:
846 853 raise HomeDirError,'support for your operating system not implemented.'
847 854
848 855 #****************************************************************************
849 856 # strings and text
850 857
851 858 class LSString(str):
852 859 """String derivative with a special access attributes.
853 860
854 861 These are normal strings, but with the special attributes:
855 862
856 863 .l (or .list) : value as list (split on newlines).
857 864 .n (or .nlstr): original value (the string itself).
858 865 .s (or .spstr): value as whitespace-separated string.
859 866
860 867 Any values which require transformations are computed only once and
861 868 cached.
862 869
863 870 Such strings are very useful to efficiently interact with the shell, which
864 871 typically only understands whitespace-separated options for commands."""
865 872
866 873 def get_list(self):
867 874 try:
868 875 return self.__list
869 876 except AttributeError:
870 877 self.__list = self.split('\n')
871 878 return self.__list
872 879
873 880 l = list = property(get_list)
874 881
875 882 def get_spstr(self):
876 883 try:
877 884 return self.__spstr
878 885 except AttributeError:
879 886 self.__spstr = self.replace('\n',' ')
880 887 return self.__spstr
881 888
882 889 s = spstr = property(get_spstr)
883 890
884 891 def get_nlstr(self):
885 892 return self
886 893
887 894 n = nlstr = property(get_nlstr)
888 895
889 896 def get_paths(self):
890 897 try:
891 898 return self.__paths
892 899 except AttributeError:
893 900 self.__paths = [path(p) for p in self.split('\n') if os.path.exists(p)]
894 901 return self.__paths
895 902
896 903 p = paths = property(get_paths)
897 904
898 905
899 906 #----------------------------------------------------------------------------
900 907 class SList(list):
901 908 """List derivative with a special access attributes.
902 909
903 910 These are normal lists, but with the special attributes:
904 911
905 912 .l (or .list) : value as list (the list itself).
906 913 .n (or .nlstr): value as a string, joined on newlines.
907 914 .s (or .spstr): value as a string, joined on spaces.
908 915
909 916 Any values which require transformations are computed only once and
910 917 cached."""
911 918
912 919 def get_list(self):
913 920 return self
914 921
915 922 l = list = property(get_list)
916 923
917 924 def get_spstr(self):
918 925 try:
919 926 return self.__spstr
920 927 except AttributeError:
921 928 self.__spstr = ' '.join(self)
922 929 return self.__spstr
923 930
924 931 s = spstr = property(get_spstr)
925 932
926 933 def get_nlstr(self):
927 934 try:
928 935 return self.__nlstr
929 936 except AttributeError:
930 937 self.__nlstr = '\n'.join(self)
931 938 return self.__nlstr
932 939
933 940 n = nlstr = property(get_nlstr)
934 941
935 942 def get_paths(self):
936 943 try:
937 944 return self.__paths
938 945 except AttributeError:
939 946 self.__paths = [path(p) for p in self if os.path.exists(p)]
940 947 return self.__paths
941 948
942 949 p = paths = property(get_paths)
943 950
944 951 #----------------------------------------------------------------------------
945 952 def esc_quotes(strng):
946 953 """Return the input string with single and double quotes escaped out"""
947 954
948 955 return strng.replace('"','\\"').replace("'","\\'")
949 956
950 957 #----------------------------------------------------------------------------
951 958 def make_quoted_expr(s):
952 959 """Return string s in appropriate quotes, using raw string if possible.
953 960
954 961 Effectively this turns string: cd \ao\ao\
955 962 to: r"cd \ao\ao\_"[:-1]
956 963
957 964 Note the use of raw string and padding at the end to allow trailing backslash.
958 965
959 966 """
960 967
961 968 tail = ''
962 969 tailpadding = ''
963 970 raw = ''
964 971 if "\\" in s:
965 972 raw = 'r'
966 973 if s.endswith('\\'):
967 974 tail = '[:-1]'
968 975 tailpadding = '_'
969 976 if '"' not in s:
970 977 quote = '"'
971 978 elif "'" not in s:
972 979 quote = "'"
973 980 elif '"""' not in s and not s.endswith('"'):
974 981 quote = '"""'
975 982 elif "'''" not in s and not s.endswith("'"):
976 983 quote = "'''"
977 984 else:
978 985 # give up, backslash-escaped string will do
979 986 return '"%s"' % esc_quotes(s)
980 987 res = itpl("$raw$quote$s$tailpadding$quote$tail")
981 988 return res
982 989
983 990
984 991 #----------------------------------------------------------------------------
985 992 def raw_input_multi(header='', ps1='==> ', ps2='..> ',terminate_str = '.'):
986 993 """Take multiple lines of input.
987 994
988 995 A list with each line of input as a separate element is returned when a
989 996 termination string is entered (defaults to a single '.'). Input can also
990 997 terminate via EOF (^D in Unix, ^Z-RET in Windows).
991 998
992 999 Lines of input which end in \\ are joined into single entries (and a
993 1000 secondary continuation prompt is issued as long as the user terminates
994 1001 lines with \\). This allows entering very long strings which are still
995 1002 meant to be treated as single entities.
996 1003 """
997 1004
998 1005 try:
999 1006 if header:
1000 1007 header += '\n'
1001 1008 lines = [raw_input(header + ps1)]
1002 1009 except EOFError:
1003 1010 return []
1004 1011 terminate = [terminate_str]
1005 1012 try:
1006 1013 while lines[-1:] != terminate:
1007 1014 new_line = raw_input(ps1)
1008 1015 while new_line.endswith('\\'):
1009 1016 new_line = new_line[:-1] + raw_input(ps2)
1010 1017 lines.append(new_line)
1011 1018
1012 1019 return lines[:-1] # don't return the termination command
1013 1020 except EOFError:
1014 1021 print
1015 1022 return lines
1016 1023
1017 1024 #----------------------------------------------------------------------------
1018 1025 def raw_input_ext(prompt='', ps2='... '):
1019 1026 """Similar to raw_input(), but accepts extended lines if input ends with \\."""
1020 1027
1021 1028 line = raw_input(prompt)
1022 1029 while line.endswith('\\'):
1023 1030 line = line[:-1] + raw_input(ps2)
1024 1031 return line
1025 1032
1026 1033 #----------------------------------------------------------------------------
1027 1034 def ask_yes_no(prompt,default=None):
1028 1035 """Asks a question and returns an integer 1/0 (y/n) answer.
1029 1036
1030 1037 If default is given (one of 'y','n'), it is used if the user input is
1031 1038 empty. Otherwise the question is repeated until an answer is given.
1032 1039
1033 1040 An EOF is treated as the default answer. If there is no default, an
1034 1041 exception is raised to prevent infinite loops.
1035 1042
1036 1043 Valid answers are: y/yes/n/no (match is not case sensitive)."""
1037 1044
1038 1045 answers = {'y':True,'n':False,'yes':True,'no':False}
1039 1046 ans = None
1040 1047 while ans not in answers.keys():
1041 1048 try:
1042 1049 ans = raw_input(prompt+' ').lower()
1043 1050 if not ans: # response was an empty string
1044 1051 ans = default
1045 1052 except KeyboardInterrupt:
1046 1053 pass
1047 1054 except EOFError:
1048 1055 if default in answers.keys():
1049 1056 ans = default
1050 1057 print
1051 1058 else:
1052 1059 raise
1053 1060
1054 1061 return answers[ans]
1055 1062
1056 1063 #----------------------------------------------------------------------------
1057 1064 def marquee(txt='',width=78,mark='*'):
1058 1065 """Return the input string centered in a 'marquee'."""
1059 1066 if not txt:
1060 1067 return (mark*width)[:width]
1061 1068 nmark = (width-len(txt)-2)/len(mark)/2
1062 1069 if nmark < 0: nmark =0
1063 1070 marks = mark*nmark
1064 1071 return '%s %s %s' % (marks,txt,marks)
1065 1072
1066 1073 #----------------------------------------------------------------------------
1067 1074 class EvalDict:
1068 1075 """
1069 1076 Emulate a dict which evaluates its contents in the caller's frame.
1070 1077
1071 1078 Usage:
1072 1079 >>>number = 19
1073 1080 >>>text = "python"
1074 1081 >>>print "%(text.capitalize())s %(number/9.0).1f rules!" % EvalDict()
1075 1082 """
1076 1083
1077 1084 # This version is due to sismex01@hebmex.com on c.l.py, and is basically a
1078 1085 # modified (shorter) version of:
1079 1086 # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66018 by
1080 1087 # Skip Montanaro (skip@pobox.com).
1081 1088
1082 1089 def __getitem__(self, name):
1083 1090 frame = sys._getframe(1)
1084 1091 return eval(name, frame.f_globals, frame.f_locals)
1085 1092
1086 1093 EvalString = EvalDict # for backwards compatibility
1087 1094 #----------------------------------------------------------------------------
1088 1095 def qw(words,flat=0,sep=None,maxsplit=-1):
1089 1096 """Similar to Perl's qw() operator, but with some more options.
1090 1097
1091 1098 qw(words,flat=0,sep=' ',maxsplit=-1) -> words.split(sep,maxsplit)
1092 1099
1093 1100 words can also be a list itself, and with flat=1, the output will be
1094 1101 recursively flattened. Examples:
1095 1102
1096 1103 >>> qw('1 2')
1097 1104 ['1', '2']
1098 1105 >>> qw(['a b','1 2',['m n','p q']])
1099 1106 [['a', 'b'], ['1', '2'], [['m', 'n'], ['p', 'q']]]
1100 1107 >>> qw(['a b','1 2',['m n','p q']],flat=1)
1101 1108 ['a', 'b', '1', '2', 'm', 'n', 'p', 'q'] """
1102 1109
1103 1110 if type(words) in StringTypes:
1104 1111 return [word.strip() for word in words.split(sep,maxsplit)
1105 1112 if word and not word.isspace() ]
1106 1113 if flat:
1107 1114 return flatten(map(qw,words,[1]*len(words)))
1108 1115 return map(qw,words)
1109 1116
1110 1117 #----------------------------------------------------------------------------
1111 1118 def qwflat(words,sep=None,maxsplit=-1):
1112 1119 """Calls qw(words) in flat mode. It's just a convenient shorthand."""
1113 1120 return qw(words,1,sep,maxsplit)
1114 1121
1115 1122 #----------------------------------------------------------------------------
1116 1123 def qw_lol(indata):
1117 1124 """qw_lol('a b') -> [['a','b']],
1118 1125 otherwise it's just a call to qw().
1119 1126
1120 1127 We need this to make sure the modules_some keys *always* end up as a
1121 1128 list of lists."""
1122 1129
1123 1130 if type(indata) in StringTypes:
1124 1131 return [qw(indata)]
1125 1132 else:
1126 1133 return qw(indata)
1127 1134
1128 1135 #-----------------------------------------------------------------------------
1129 1136 def list_strings(arg):
1130 1137 """Always return a list of strings, given a string or list of strings
1131 1138 as input."""
1132 1139
1133 1140 if type(arg) in StringTypes: return [arg]
1134 1141 else: return arg
1135 1142
1136 1143 #----------------------------------------------------------------------------
1137 1144 def grep(pat,list,case=1):
1138 1145 """Simple minded grep-like function.
1139 1146 grep(pat,list) returns occurrences of pat in list, None on failure.
1140 1147
1141 1148 It only does simple string matching, with no support for regexps. Use the
1142 1149 option case=0 for case-insensitive matching."""
1143 1150
1144 1151 # This is pretty crude. At least it should implement copying only references
1145 1152 # to the original data in case it's big. Now it copies the data for output.
1146 1153 out=[]
1147 1154 if case:
1148 1155 for term in list:
1149 1156 if term.find(pat)>-1: out.append(term)
1150 1157 else:
1151 1158 lpat=pat.lower()
1152 1159 for term in list:
1153 1160 if term.lower().find(lpat)>-1: out.append(term)
1154 1161
1155 1162 if len(out): return out
1156 1163 else: return None
1157 1164
1158 1165 #----------------------------------------------------------------------------
1159 1166 def dgrep(pat,*opts):
1160 1167 """Return grep() on dir()+dir(__builtins__).
1161 1168
1162 1169 A very common use of grep() when working interactively."""
1163 1170
1164 1171 return grep(pat,dir(__main__)+dir(__main__.__builtins__),*opts)
1165 1172
1166 1173 #----------------------------------------------------------------------------
1167 1174 def idgrep(pat):
1168 1175 """Case-insensitive dgrep()"""
1169 1176
1170 1177 return dgrep(pat,0)
1171 1178
1172 1179 #----------------------------------------------------------------------------
1173 1180 def igrep(pat,list):
1174 1181 """Synonym for case-insensitive grep."""
1175 1182
1176 1183 return grep(pat,list,case=0)
1177 1184
1178 1185 #----------------------------------------------------------------------------
1179 1186 def indent(str,nspaces=4,ntabs=0):
1180 1187 """Indent a string a given number of spaces or tabstops.
1181 1188
1182 1189 indent(str,nspaces=4,ntabs=0) -> indent str by ntabs+nspaces.
1183 1190 """
1184 1191 if str is None:
1185 1192 return
1186 1193 ind = '\t'*ntabs+' '*nspaces
1187 1194 outstr = '%s%s' % (ind,str.replace(os.linesep,os.linesep+ind))
1188 1195 if outstr.endswith(os.linesep+ind):
1189 1196 return outstr[:-len(ind)]
1190 1197 else:
1191 1198 return outstr
1192 1199
1193 1200 #-----------------------------------------------------------------------------
1194 1201 def native_line_ends(filename,backup=1):
1195 1202 """Convert (in-place) a file to line-ends native to the current OS.
1196 1203
1197 1204 If the optional backup argument is given as false, no backup of the
1198 1205 original file is left. """
1199 1206
1200 1207 backup_suffixes = {'posix':'~','dos':'.bak','nt':'.bak','mac':'.bak'}
1201 1208
1202 1209 bak_filename = filename + backup_suffixes[os.name]
1203 1210
1204 1211 original = open(filename).read()
1205 1212 shutil.copy2(filename,bak_filename)
1206 1213 try:
1207 1214 new = open(filename,'wb')
1208 1215 new.write(os.linesep.join(original.splitlines()))
1209 1216 new.write(os.linesep) # ALWAYS put an eol at the end of the file
1210 1217 new.close()
1211 1218 except:
1212 1219 os.rename(bak_filename,filename)
1213 1220 if not backup:
1214 1221 try:
1215 1222 os.remove(bak_filename)
1216 1223 except:
1217 1224 pass
1218 1225
1219 1226 #----------------------------------------------------------------------------
1220 1227 def get_pager_cmd(pager_cmd = None):
1221 1228 """Return a pager command.
1222 1229
1223 1230 Makes some attempts at finding an OS-correct one."""
1224 1231
1225 1232 if os.name == 'posix':
1226 1233 default_pager_cmd = 'less -r' # -r for color control sequences
1227 1234 elif os.name in ['nt','dos']:
1228 1235 default_pager_cmd = 'type'
1229 1236
1230 1237 if pager_cmd is None:
1231 1238 try:
1232 1239 pager_cmd = os.environ['PAGER']
1233 1240 except:
1234 1241 pager_cmd = default_pager_cmd
1235 1242 return pager_cmd
1236 1243
1237 1244 #-----------------------------------------------------------------------------
1238 1245 def get_pager_start(pager,start):
1239 1246 """Return the string for paging files with an offset.
1240 1247
1241 1248 This is the '+N' argument which less and more (under Unix) accept.
1242 1249 """
1243 1250
1244 1251 if pager in ['less','more']:
1245 1252 if start:
1246 1253 start_string = '+' + str(start)
1247 1254 else:
1248 1255 start_string = ''
1249 1256 else:
1250 1257 start_string = ''
1251 1258 return start_string
1252 1259
1253 1260 #----------------------------------------------------------------------------
1254 1261 # (X)emacs on W32 doesn't like to be bypassed with msvcrt.getch()
1255 1262 if os.name == 'nt' and os.environ.get('TERM','dumb') != 'emacs':
1256 1263 import msvcrt
1257 1264 def page_more():
1258 1265 """ Smart pausing between pages
1259 1266
1260 1267 @return: True if need print more lines, False if quit
1261 1268 """
1262 1269 Term.cout.write('---Return to continue, q to quit--- ')
1263 1270 ans = msvcrt.getch()
1264 1271 if ans in ("q", "Q"):
1265 1272 result = False
1266 1273 else:
1267 1274 result = True
1268 1275 Term.cout.write("\b"*37 + " "*37 + "\b"*37)
1269 1276 return result
1270 1277 else:
1271 1278 def page_more():
1272 1279 ans = raw_input('---Return to continue, q to quit--- ')
1273 1280 if ans.lower().startswith('q'):
1274 1281 return False
1275 1282 else:
1276 1283 return True
1277 1284
1278 1285 esc_re = re.compile(r"(\x1b[^m]+m)")
1279 1286
1280 1287 def page_dumb(strng,start=0,screen_lines=25):
1281 1288 """Very dumb 'pager' in Python, for when nothing else works.
1282 1289
1283 1290 Only moves forward, same interface as page(), except for pager_cmd and
1284 1291 mode."""
1285 1292
1286 1293 out_ln = strng.splitlines()[start:]
1287 1294 screens = chop(out_ln,screen_lines-1)
1288 1295 if len(screens) == 1:
1289 1296 print >>Term.cout, os.linesep.join(screens[0])
1290 1297 else:
1291 1298 last_escape = ""
1292 1299 for scr in screens[0:-1]:
1293 1300 hunk = os.linesep.join(scr)
1294 1301 print >>Term.cout, last_escape + hunk
1295 1302 if not page_more():
1296 1303 return
1297 1304 esc_list = esc_re.findall(hunk)
1298 1305 if len(esc_list) > 0:
1299 1306 last_escape = esc_list[-1]
1300 1307 print >>Term.cout, last_escape + os.linesep.join(screens[-1])
1301 1308
1302 1309 #----------------------------------------------------------------------------
1303 1310 def page(strng,start=0,screen_lines=0,pager_cmd = None):
1304 1311 """Print a string, piping through a pager after a certain length.
1305 1312
1306 1313 The screen_lines parameter specifies the number of *usable* lines of your
1307 1314 terminal screen (total lines minus lines you need to reserve to show other
1308 1315 information).
1309 1316
1310 1317 If you set screen_lines to a number <=0, page() will try to auto-determine
1311 1318 your screen size and will only use up to (screen_size+screen_lines) for
1312 1319 printing, paging after that. That is, if you want auto-detection but need
1313 1320 to reserve the bottom 3 lines of the screen, use screen_lines = -3, and for
1314 1321 auto-detection without any lines reserved simply use screen_lines = 0.
1315 1322
1316 1323 If a string won't fit in the allowed lines, it is sent through the
1317 1324 specified pager command. If none given, look for PAGER in the environment,
1318 1325 and ultimately default to less.
1319 1326
1320 1327 If no system pager works, the string is sent through a 'dumb pager'
1321 1328 written in python, very simplistic.
1322 1329 """
1323 1330
1324 1331 # Ugly kludge, but calling curses.initscr() flat out crashes in emacs
1325 1332 TERM = os.environ.get('TERM','dumb')
1326 1333 if TERM in ['dumb','emacs'] and os.name != 'nt':
1327 1334 print strng
1328 1335 return
1329 1336 # chop off the topmost part of the string we don't want to see
1330 1337 str_lines = strng.split(os.linesep)[start:]
1331 1338 str_toprint = os.linesep.join(str_lines)
1332 1339 num_newlines = len(str_lines)
1333 1340 len_str = len(str_toprint)
1334 1341
1335 1342 # Dumb heuristics to guesstimate number of on-screen lines the string
1336 1343 # takes. Very basic, but good enough for docstrings in reasonable
1337 1344 # terminals. If someone later feels like refining it, it's not hard.
1338 1345 numlines = max(num_newlines,int(len_str/80)+1)
1339 1346
1340 1347 if os.name == "nt":
1341 1348 screen_lines_def = get_console_size(defaulty=25)[1]
1342 1349 else:
1343 1350 screen_lines_def = 25 # default value if we can't auto-determine
1344 1351
1345 1352 # auto-determine screen size
1346 1353 if screen_lines <= 0:
1347 1354 if TERM=='xterm':
1348 1355 try:
1349 1356 import curses
1350 1357 if hasattr(curses,'initscr'):
1351 1358 use_curses = 1
1352 1359 else:
1353 1360 use_curses = 0
1354 1361 except ImportError:
1355 1362 use_curses = 0
1356 1363 else:
1357 1364 # curses causes problems on many terminals other than xterm.
1358 1365 use_curses = 0
1359 1366 if use_curses:
1360 1367 scr = curses.initscr()
1361 1368 screen_lines_real,screen_cols = scr.getmaxyx()
1362 1369 curses.endwin()
1363 1370 screen_lines += screen_lines_real
1364 1371 #print '***Screen size:',screen_lines_real,'lines x',\
1365 1372 #screen_cols,'columns.' # dbg
1366 1373 else:
1367 1374 screen_lines += screen_lines_def
1368 1375
1369 1376 #print 'numlines',numlines,'screenlines',screen_lines # dbg
1370 1377 if numlines <= screen_lines :
1371 1378 #print '*** normal print' # dbg
1372 1379 print >>Term.cout, str_toprint
1373 1380 else:
1374 1381 # Try to open pager and default to internal one if that fails.
1375 1382 # All failure modes are tagged as 'retval=1', to match the return
1376 1383 # value of a failed system command. If any intermediate attempt
1377 1384 # sets retval to 1, at the end we resort to our own page_dumb() pager.
1378 1385 pager_cmd = get_pager_cmd(pager_cmd)
1379 1386 pager_cmd += ' ' + get_pager_start(pager_cmd,start)
1380 1387 if os.name == 'nt':
1381 1388 if pager_cmd.startswith('type'):
1382 1389 # The default WinXP 'type' command is failing on complex strings.
1383 1390 retval = 1
1384 1391 else:
1385 1392 tmpname = tempfile.mktemp('.txt')
1386 1393 tmpfile = file(tmpname,'wt')
1387 1394 tmpfile.write(strng)
1388 1395 tmpfile.close()
1389 1396 cmd = "%s < %s" % (pager_cmd,tmpname)
1390 1397 if os.system(cmd):
1391 1398 retval = 1
1392 1399 else:
1393 1400 retval = None
1394 1401 os.remove(tmpname)
1395 1402 else:
1396 1403 try:
1397 1404 retval = None
1398 1405 # if I use popen4, things hang. No idea why.
1399 1406 #pager,shell_out = os.popen4(pager_cmd)
1400 1407 pager = os.popen(pager_cmd,'w')
1401 1408 pager.write(strng)
1402 1409 pager.close()
1403 1410 retval = pager.close() # success returns None
1404 1411 except IOError,msg: # broken pipe when user quits
1405 1412 if msg.args == (32,'Broken pipe'):
1406 1413 retval = None
1407 1414 else:
1408 1415 retval = 1
1409 1416 except OSError:
1410 1417 # Other strange problems, sometimes seen in Win2k/cygwin
1411 1418 retval = 1
1412 1419 if retval is not None:
1413 1420 page_dumb(strng,screen_lines=screen_lines)
1414 1421
1415 1422 #----------------------------------------------------------------------------
1416 1423 def page_file(fname,start = 0, pager_cmd = None):
1417 1424 """Page a file, using an optional pager command and starting line.
1418 1425 """
1419 1426
1420 1427 pager_cmd = get_pager_cmd(pager_cmd)
1421 1428 pager_cmd += ' ' + get_pager_start(pager_cmd,start)
1422 1429
1423 1430 try:
1424 1431 if os.environ['TERM'] in ['emacs','dumb']:
1425 1432 raise EnvironmentError
1426 1433 xsys(pager_cmd + ' ' + fname)
1427 1434 except:
1428 1435 try:
1429 1436 if start > 0:
1430 1437 start -= 1
1431 1438 page(open(fname).read(),start)
1432 1439 except:
1433 1440 print 'Unable to show file',`fname`
1434 1441
1435 1442 #----------------------------------------------------------------------------
1436 1443 def snip_print(str,width = 75,print_full = 0,header = ''):
1437 1444 """Print a string snipping the midsection to fit in width.
1438 1445
1439 1446 print_full: mode control:
1440 1447 - 0: only snip long strings
1441 1448 - 1: send to page() directly.
1442 1449 - 2: snip long strings and ask for full length viewing with page()
1443 1450 Return 1 if snipping was necessary, 0 otherwise."""
1444 1451
1445 1452 if print_full == 1:
1446 1453 page(header+str)
1447 1454 return 0
1448 1455
1449 1456 print header,
1450 1457 if len(str) < width:
1451 1458 print str
1452 1459 snip = 0
1453 1460 else:
1454 1461 whalf = int((width -5)/2)
1455 1462 print str[:whalf] + ' <...> ' + str[-whalf:]
1456 1463 snip = 1
1457 1464 if snip and print_full == 2:
1458 1465 if raw_input(header+' Snipped. View (y/n)? [N]').lower() == 'y':
1459 1466 page(str)
1460 1467 return snip
1461 1468
1462 1469 #****************************************************************************
1463 1470 # lists, dicts and structures
1464 1471
1465 1472 def belong(candidates,checklist):
1466 1473 """Check whether a list of items appear in a given list of options.
1467 1474
1468 1475 Returns a list of 1 and 0, one for each candidate given."""
1469 1476
1470 1477 return [x in checklist for x in candidates]
1471 1478
1472 1479 #----------------------------------------------------------------------------
1473 1480 def uniq_stable(elems):
1474 1481 """uniq_stable(elems) -> list
1475 1482
1476 1483 Return from an iterable, a list of all the unique elements in the input,
1477 1484 but maintaining the order in which they first appear.
1478 1485
1479 1486 A naive solution to this problem which just makes a dictionary with the
1480 1487 elements as keys fails to respect the stability condition, since
1481 1488 dictionaries are unsorted by nature.
1482 1489
1483 1490 Note: All elements in the input must be valid dictionary keys for this
1484 1491 routine to work, as it internally uses a dictionary for efficiency
1485 1492 reasons."""
1486 1493
1487 1494 unique = []
1488 1495 unique_dict = {}
1489 1496 for nn in elems:
1490 1497 if nn not in unique_dict:
1491 1498 unique.append(nn)
1492 1499 unique_dict[nn] = None
1493 1500 return unique
1494 1501
1495 1502 #----------------------------------------------------------------------------
1496 1503 class NLprinter:
1497 1504 """Print an arbitrarily nested list, indicating index numbers.
1498 1505
1499 1506 An instance of this class called nlprint is available and callable as a
1500 1507 function.
1501 1508
1502 1509 nlprint(list,indent=' ',sep=': ') -> prints indenting each level by 'indent'
1503 1510 and using 'sep' to separate the index from the value. """
1504 1511
1505 1512 def __init__(self):
1506 1513 self.depth = 0
1507 1514
1508 1515 def __call__(self,lst,pos='',**kw):
1509 1516 """Prints the nested list numbering levels."""
1510 1517 kw.setdefault('indent',' ')
1511 1518 kw.setdefault('sep',': ')
1512 1519 kw.setdefault('start',0)
1513 1520 kw.setdefault('stop',len(lst))
1514 1521 # we need to remove start and stop from kw so they don't propagate
1515 1522 # into a recursive call for a nested list.
1516 1523 start = kw['start']; del kw['start']
1517 1524 stop = kw['stop']; del kw['stop']
1518 1525 if self.depth == 0 and 'header' in kw.keys():
1519 1526 print kw['header']
1520 1527
1521 1528 for idx in range(start,stop):
1522 1529 elem = lst[idx]
1523 1530 if type(elem)==type([]):
1524 1531 self.depth += 1
1525 1532 self.__call__(elem,itpl('$pos$idx,'),**kw)
1526 1533 self.depth -= 1
1527 1534 else:
1528 1535 printpl(kw['indent']*self.depth+'$pos$idx$kw["sep"]$elem')
1529 1536
1530 1537 nlprint = NLprinter()
1531 1538 #----------------------------------------------------------------------------
1532 1539 def all_belong(candidates,checklist):
1533 1540 """Check whether a list of items ALL appear in a given list of options.
1534 1541
1535 1542 Returns a single 1 or 0 value."""
1536 1543
1537 1544 return 1-(0 in [x in checklist for x in candidates])
1538 1545
1539 1546 #----------------------------------------------------------------------------
1540 1547 def sort_compare(lst1,lst2,inplace = 1):
1541 1548 """Sort and compare two lists.
1542 1549
1543 1550 By default it does it in place, thus modifying the lists. Use inplace = 0
1544 1551 to avoid that (at the cost of temporary copy creation)."""
1545 1552 if not inplace:
1546 1553 lst1 = lst1[:]
1547 1554 lst2 = lst2[:]
1548 1555 lst1.sort(); lst2.sort()
1549 1556 return lst1 == lst2
1550 1557
1551 1558 #----------------------------------------------------------------------------
1552 1559 def mkdict(**kwargs):
1553 1560 """Return a dict from a keyword list.
1554 1561
1555 1562 It's just syntactic sugar for making ditcionary creation more convenient:
1556 1563 # the standard way
1557 1564 >>>data = { 'red' : 1, 'green' : 2, 'blue' : 3 }
1558 1565 # a cleaner way
1559 1566 >>>data = dict(red=1, green=2, blue=3)
1560 1567
1561 1568 If you need more than this, look at the Struct() class."""
1562 1569
1563 1570 return kwargs
1564 1571
1565 1572 #----------------------------------------------------------------------------
1566 1573 def list2dict(lst):
1567 1574 """Takes a list of (key,value) pairs and turns it into a dict."""
1568 1575
1569 1576 dic = {}
1570 1577 for k,v in lst: dic[k] = v
1571 1578 return dic
1572 1579
1573 1580 #----------------------------------------------------------------------------
1574 1581 def list2dict2(lst,default=''):
1575 1582 """Takes a list and turns it into a dict.
1576 1583 Much slower than list2dict, but more versatile. This version can take
1577 1584 lists with sublists of arbitrary length (including sclars)."""
1578 1585
1579 1586 dic = {}
1580 1587 for elem in lst:
1581 1588 if type(elem) in (types.ListType,types.TupleType):
1582 1589 size = len(elem)
1583 1590 if size == 0:
1584 1591 pass
1585 1592 elif size == 1:
1586 1593 dic[elem] = default
1587 1594 else:
1588 1595 k,v = elem[0], elem[1:]
1589 1596 if len(v) == 1: v = v[0]
1590 1597 dic[k] = v
1591 1598 else:
1592 1599 dic[elem] = default
1593 1600 return dic
1594 1601
1595 1602 #----------------------------------------------------------------------------
1596 1603 def flatten(seq):
1597 1604 """Flatten a list of lists (NOT recursive, only works for 2d lists)."""
1598 1605
1599 1606 return [x for subseq in seq for x in subseq]
1600 1607
1601 1608 #----------------------------------------------------------------------------
1602 1609 def get_slice(seq,start=0,stop=None,step=1):
1603 1610 """Get a slice of a sequence with variable step. Specify start,stop,step."""
1604 1611 if stop == None:
1605 1612 stop = len(seq)
1606 1613 item = lambda i: seq[i]
1607 1614 return map(item,xrange(start,stop,step))
1608 1615
1609 1616 #----------------------------------------------------------------------------
1610 1617 def chop(seq,size):
1611 1618 """Chop a sequence into chunks of the given size."""
1612 1619 chunk = lambda i: seq[i:i+size]
1613 1620 return map(chunk,xrange(0,len(seq),size))
1614 1621
1615 1622 #----------------------------------------------------------------------------
1616 1623 # with is a keyword as of python 2.5, so this function is renamed to withobj
1617 1624 # from its old 'with' name.
1618 1625 def with_obj(object, **args):
1619 1626 """Set multiple attributes for an object, similar to Pascal's with.
1620 1627
1621 1628 Example:
1622 1629 with_obj(jim,
1623 1630 born = 1960,
1624 1631 haircolour = 'Brown',
1625 1632 eyecolour = 'Green')
1626 1633
1627 1634 Credit: Greg Ewing, in
1628 1635 http://mail.python.org/pipermail/python-list/2001-May/040703.html.
1629 1636
1630 1637 NOTE: up until IPython 0.7.2, this was called simply 'with', but 'with'
1631 1638 has become a keyword for Python 2.5, so we had to rename it."""
1632 1639
1633 1640 object.__dict__.update(args)
1634 1641
1635 1642 #----------------------------------------------------------------------------
1636 1643 def setattr_list(obj,alist,nspace = None):
1637 1644 """Set a list of attributes for an object taken from a namespace.
1638 1645
1639 1646 setattr_list(obj,alist,nspace) -> sets in obj all the attributes listed in
1640 1647 alist with their values taken from nspace, which must be a dict (something
1641 1648 like locals() will often do) If nspace isn't given, locals() of the
1642 1649 *caller* is used, so in most cases you can omit it.
1643 1650
1644 1651 Note that alist can be given as a string, which will be automatically
1645 1652 split into a list on whitespace. If given as a list, it must be a list of
1646 1653 *strings* (the variable names themselves), not of variables."""
1647 1654
1648 1655 # this grabs the local variables from the *previous* call frame -- that is
1649 1656 # the locals from the function that called setattr_list().
1650 1657 # - snipped from weave.inline()
1651 1658 if nspace is None:
1652 1659 call_frame = sys._getframe().f_back
1653 1660 nspace = call_frame.f_locals
1654 1661
1655 1662 if type(alist) in StringTypes:
1656 1663 alist = alist.split()
1657 1664 for attr in alist:
1658 1665 val = eval(attr,nspace)
1659 1666 setattr(obj,attr,val)
1660 1667
1661 1668 #----------------------------------------------------------------------------
1662 1669 def getattr_list(obj,alist,*args):
1663 1670 """getattr_list(obj,alist[, default]) -> attribute list.
1664 1671
1665 1672 Get a list of named attributes for an object. When a default argument is
1666 1673 given, it is returned when the attribute doesn't exist; without it, an
1667 1674 exception is raised in that case.
1668 1675
1669 1676 Note that alist can be given as a string, which will be automatically
1670 1677 split into a list on whitespace. If given as a list, it must be a list of
1671 1678 *strings* (the variable names themselves), not of variables."""
1672 1679
1673 1680 if type(alist) in StringTypes:
1674 1681 alist = alist.split()
1675 1682 if args:
1676 1683 if len(args)==1:
1677 1684 default = args[0]
1678 1685 return map(lambda attr: getattr(obj,attr,default),alist)
1679 1686 else:
1680 1687 raise ValueError,'getattr_list() takes only one optional argument'
1681 1688 else:
1682 1689 return map(lambda attr: getattr(obj,attr),alist)
1683 1690
1684 1691 #----------------------------------------------------------------------------
1685 1692 def map_method(method,object_list,*argseq,**kw):
1686 1693 """map_method(method,object_list,*args,**kw) -> list
1687 1694
1688 1695 Return a list of the results of applying the methods to the items of the
1689 1696 argument sequence(s). If more than one sequence is given, the method is
1690 1697 called with an argument list consisting of the corresponding item of each
1691 1698 sequence. All sequences must be of the same length.
1692 1699
1693 1700 Keyword arguments are passed verbatim to all objects called.
1694 1701
1695 1702 This is Python code, so it's not nearly as fast as the builtin map()."""
1696 1703
1697 1704 out_list = []
1698 1705 idx = 0
1699 1706 for object in object_list:
1700 1707 try:
1701 1708 handler = getattr(object, method)
1702 1709 except AttributeError:
1703 1710 out_list.append(None)
1704 1711 else:
1705 1712 if argseq:
1706 1713 args = map(lambda lst:lst[idx],argseq)
1707 1714 #print 'ob',object,'hand',handler,'ar',args # dbg
1708 1715 out_list.append(handler(args,**kw))
1709 1716 else:
1710 1717 out_list.append(handler(**kw))
1711 1718 idx += 1
1712 1719 return out_list
1713 1720
1714 1721 #----------------------------------------------------------------------------
1715 1722 def import_fail_info(mod_name,fns=None):
1716 1723 """Inform load failure for a module."""
1717 1724
1718 1725 if fns == None:
1719 1726 warn("Loading of %s failed.\n" % (mod_name,))
1720 1727 else:
1721 1728 warn("Loading of %s from %s failed.\n" % (fns,mod_name))
1722 1729
1723 1730 #----------------------------------------------------------------------------
1724 1731 # Proposed popitem() extension, written as a method
1725 1732
1726 1733
1727 1734 class NotGiven: pass
1728 1735
1729 1736 def popkey(dct,key,default=NotGiven):
1730 1737 """Return dct[key] and delete dct[key].
1731 1738
1732 1739 If default is given, return it if dct[key] doesn't exist, otherwise raise
1733 1740 KeyError. """
1734 1741
1735 1742 try:
1736 1743 val = dct[key]
1737 1744 except KeyError:
1738 1745 if default is NotGiven:
1739 1746 raise
1740 1747 else:
1741 1748 return default
1742 1749 else:
1743 1750 del dct[key]
1744 1751 return val
1745 1752
1746 1753 def wrap_deprecated(func, suggest = '<nothing>'):
1747 1754 def newFunc(*args, **kwargs):
1748 1755 warnings.warn("Call to deprecated function %s, use %s instead" %
1749 1756 ( func.__name__, suggest),
1750 1757 category=DeprecationWarning,
1751 1758 stacklevel = 2)
1752 1759 return func(*args, **kwargs)
1753 1760 return newFunc
1754 1761
1755 1762 #*************************** end of file <genutils.py> **********************
1756 1763
@@ -1,2579 +1,2580 b''
1 1 # -*- coding: utf-8 -*-
2 2 """
3 3 IPython -- An enhanced Interactive Python
4 4
5 5 Requires Python 2.3 or newer.
6 6
7 7 This file contains all the classes and helper functions specific to IPython.
8 8
9 $Id: iplib.py 2187 2007-03-30 04:56:40Z fperez $
9 $Id: iplib.py 2190 2007-03-30 18:35:46Z fperez $
10 10 """
11 11
12 12 #*****************************************************************************
13 13 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
14 14 # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu>
15 15 #
16 16 # Distributed under the terms of the BSD License. The full license is in
17 17 # the file COPYING, distributed as part of this software.
18 18 #
19 19 # Note: this code originally subclassed code.InteractiveConsole from the
20 20 # Python standard library. Over time, all of that class has been copied
21 21 # verbatim here for modifications which could not be accomplished by
22 22 # subclassing. At this point, there are no dependencies at all on the code
23 23 # module anymore (it is not even imported). The Python License (sec. 2)
24 24 # allows for this, but it's always nice to acknowledge credit where credit is
25 25 # due.
26 26 #*****************************************************************************
27 27
28 28 #****************************************************************************
29 29 # Modules and globals
30 30
31 31 from IPython import Release
32 32 __author__ = '%s <%s>\n%s <%s>' % \
33 33 ( Release.authors['Janko'] + Release.authors['Fernando'] )
34 34 __license__ = Release.license
35 35 __version__ = Release.version
36 36
37 37 # Python standard modules
38 38 import __main__
39 39 import __builtin__
40 40 import StringIO
41 41 import bdb
42 42 import cPickle as pickle
43 43 import codeop
44 44 import exceptions
45 45 import glob
46 46 import inspect
47 47 import keyword
48 48 import new
49 49 import os
50 50 import pydoc
51 51 import re
52 52 import shutil
53 53 import string
54 54 import sys
55 55 import tempfile
56 56 import traceback
57 57 import types
58 58 import pickleshare
59 59 from sets import Set
60 60 from pprint import pprint, pformat
61 61
62 62 # IPython's own modules
63 63 import IPython
64 64 from IPython import OInspect,PyColorize,ultraTB
65 65 from IPython.ColorANSI import ColorScheme,ColorSchemeTable # too long names
66 66 from IPython.FakeModule import FakeModule
67 67 from IPython.Itpl import Itpl,itpl,printpl,ItplNS,itplns
68 68 from IPython.Logger import Logger
69 69 from IPython.Magic import Magic
70 70 from IPython.Prompts import CachedOutput
71 71 from IPython.ipstruct import Struct
72 72 from IPython.background_jobs import BackgroundJobManager
73 73 from IPython.usage import cmd_line_usage,interactive_usage
74 74 from IPython.genutils import *
75 75 from IPython.strdispatch import StrDispatch
76 76 import IPython.ipapi
77 77
78 78 # Globals
79 79
80 80 # store the builtin raw_input globally, and use this always, in case user code
81 81 # overwrites it (like wx.py.PyShell does)
82 82 raw_input_original = raw_input
83 83
84 84 # compiled regexps for autoindent management
85 85 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
86 86
87 87
88 88 #****************************************************************************
89 89 # Some utility function definitions
90 90
91 91 ini_spaces_re = re.compile(r'^(\s+)')
92 92
93 93 def num_ini_spaces(strng):
94 94 """Return the number of initial spaces in a string"""
95 95
96 96 ini_spaces = ini_spaces_re.match(strng)
97 97 if ini_spaces:
98 98 return ini_spaces.end()
99 99 else:
100 100 return 0
101 101
102 102 def softspace(file, newvalue):
103 103 """Copied from code.py, to remove the dependency"""
104 104
105 105 oldvalue = 0
106 106 try:
107 107 oldvalue = file.softspace
108 108 except AttributeError:
109 109 pass
110 110 try:
111 111 file.softspace = newvalue
112 112 except (AttributeError, TypeError):
113 113 # "attribute-less object" or "read-only attributes"
114 114 pass
115 115 return oldvalue
116 116
117 117
118 118 #****************************************************************************
119 119 # Local use exceptions
120 120 class SpaceInInput(exceptions.Exception): pass
121 121
122 122
123 123 #****************************************************************************
124 124 # Local use classes
125 125 class Bunch: pass
126 126
127 127 class Undefined: pass
128 128
129 129 class Quitter(object):
130 130 """Simple class to handle exit, similar to Python 2.5's.
131 131
132 132 It handles exiting in an ipython-safe manner, which the one in Python 2.5
133 133 doesn't do (obviously, since it doesn't know about ipython)."""
134 134
135 135 def __init__(self,shell,name):
136 136 self.shell = shell
137 137 self.name = name
138 138
139 139 def __repr__(self):
140 140 return 'Type %s() to exit.' % self.name
141 141 __str__ = __repr__
142 142
143 143 def __call__(self):
144 144 self.shell.exit()
145 145
146 146 class InputList(list):
147 147 """Class to store user input.
148 148
149 149 It's basically a list, but slices return a string instead of a list, thus
150 150 allowing things like (assuming 'In' is an instance):
151 151
152 152 exec In[4:7]
153 153
154 154 or
155 155
156 156 exec In[5:9] + In[14] + In[21:25]"""
157 157
158 158 def __getslice__(self,i,j):
159 159 return ''.join(list.__getslice__(self,i,j))
160 160
161 161 class SyntaxTB(ultraTB.ListTB):
162 162 """Extension which holds some state: the last exception value"""
163 163
164 164 def __init__(self,color_scheme = 'NoColor'):
165 165 ultraTB.ListTB.__init__(self,color_scheme)
166 166 self.last_syntax_error = None
167 167
168 168 def __call__(self, etype, value, elist):
169 169 self.last_syntax_error = value
170 170 ultraTB.ListTB.__call__(self,etype,value,elist)
171 171
172 172 def clear_err_state(self):
173 173 """Return the current error state and clear it"""
174 174 e = self.last_syntax_error
175 175 self.last_syntax_error = None
176 176 return e
177 177
178 178 #****************************************************************************
179 179 # Main IPython class
180 180
181 181 # FIXME: the Magic class is a mixin for now, and will unfortunately remain so
182 182 # until a full rewrite is made. I've cleaned all cross-class uses of
183 183 # attributes and methods, but too much user code out there relies on the
184 184 # equlity %foo == __IP.magic_foo, so I can't actually remove the mixin usage.
185 185 #
186 186 # But at least now, all the pieces have been separated and we could, in
187 187 # principle, stop using the mixin. This will ease the transition to the
188 188 # chainsaw branch.
189 189
190 190 # For reference, the following is the list of 'self.foo' uses in the Magic
191 191 # class as of 2005-12-28. These are names we CAN'T use in the main ipython
192 192 # class, to prevent clashes.
193 193
194 194 # ['self.__class__', 'self.__dict__', 'self._inspect', 'self._ofind',
195 195 # 'self.arg_err', 'self.extract_input', 'self.format_', 'self.lsmagic',
196 196 # 'self.magic_', 'self.options_table', 'self.parse', 'self.shell',
197 197 # 'self.value']
198 198
199 199 class InteractiveShell(object,Magic):
200 200 """An enhanced console for Python."""
201 201
202 202 # class attribute to indicate whether the class supports threads or not.
203 203 # Subclasses with thread support should override this as needed.
204 204 isthreaded = False
205 205
206 206 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
207 207 user_ns = None,user_global_ns=None,banner2='',
208 208 custom_exceptions=((),None),embedded=False):
209 209
210 210 # log system
211 211 self.logger = Logger(self,logfname='ipython_log.py',logmode='rotate')
212 212
213 213 # some minimal strict typechecks. For some core data structures, I
214 214 # want actual basic python types, not just anything that looks like
215 215 # one. This is especially true for namespaces.
216 216 for ns in (user_ns,user_global_ns):
217 217 if ns is not None and type(ns) != types.DictType:
218 218 raise TypeError,'namespace must be a dictionary'
219 219
220 220 # Job manager (for jobs run as background threads)
221 221 self.jobs = BackgroundJobManager()
222 222
223 223 # Store the actual shell's name
224 224 self.name = name
225 225
226 226 # We need to know whether the instance is meant for embedding, since
227 227 # global/local namespaces need to be handled differently in that case
228 228 self.embedded = embedded
229 229
230 230 # command compiler
231 231 self.compile = codeop.CommandCompiler()
232 232
233 233 # User input buffer
234 234 self.buffer = []
235 235
236 236 # Default name given in compilation of code
237 237 self.filename = '<ipython console>'
238 238
239 239 # Install our own quitter instead of the builtins. For python2.3-2.4,
240 240 # this brings in behavior like 2.5, and for 2.5 it's identical.
241 241 __builtin__.exit = Quitter(self,'exit')
242 242 __builtin__.quit = Quitter(self,'quit')
243 243
244 244 # Make an empty namespace, which extension writers can rely on both
245 245 # existing and NEVER being used by ipython itself. This gives them a
246 246 # convenient location for storing additional information and state
247 247 # their extensions may require, without fear of collisions with other
248 248 # ipython names that may develop later.
249 249 self.meta = Struct()
250 250
251 251 # Create the namespace where the user will operate. user_ns is
252 252 # normally the only one used, and it is passed to the exec calls as
253 253 # the locals argument. But we do carry a user_global_ns namespace
254 254 # given as the exec 'globals' argument, This is useful in embedding
255 255 # situations where the ipython shell opens in a context where the
256 256 # distinction between locals and globals is meaningful.
257 257
258 258 # FIXME. For some strange reason, __builtins__ is showing up at user
259 259 # level as a dict instead of a module. This is a manual fix, but I
260 260 # should really track down where the problem is coming from. Alex
261 261 # Schmolck reported this problem first.
262 262
263 263 # A useful post by Alex Martelli on this topic:
264 264 # Re: inconsistent value from __builtins__
265 265 # Von: Alex Martelli <aleaxit@yahoo.com>
266 266 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
267 267 # Gruppen: comp.lang.python
268 268
269 269 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
270 270 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
271 271 # > <type 'dict'>
272 272 # > >>> print type(__builtins__)
273 273 # > <type 'module'>
274 274 # > Is this difference in return value intentional?
275 275
276 276 # Well, it's documented that '__builtins__' can be either a dictionary
277 277 # or a module, and it's been that way for a long time. Whether it's
278 278 # intentional (or sensible), I don't know. In any case, the idea is
279 279 # that if you need to access the built-in namespace directly, you
280 280 # should start with "import __builtin__" (note, no 's') which will
281 281 # definitely give you a module. Yeah, it's somewhat confusing:-(.
282 282
283 283 # These routines return properly built dicts as needed by the rest of
284 284 # the code, and can also be used by extension writers to generate
285 285 # properly initialized namespaces.
286 286 user_ns = IPython.ipapi.make_user_ns(user_ns)
287 287 user_global_ns = IPython.ipapi.make_user_global_ns(user_global_ns)
288 288
289 289 # Assign namespaces
290 290 # This is the namespace where all normal user variables live
291 291 self.user_ns = user_ns
292 292 # Embedded instances require a separate namespace for globals.
293 293 # Normally this one is unused by non-embedded instances.
294 294 self.user_global_ns = user_global_ns
295 295 # A namespace to keep track of internal data structures to prevent
296 296 # them from cluttering user-visible stuff. Will be updated later
297 297 self.internal_ns = {}
298 298
299 299 # Namespace of system aliases. Each entry in the alias
300 300 # table must be a 2-tuple of the form (N,name), where N is the number
301 301 # of positional arguments of the alias.
302 302 self.alias_table = {}
303 303
304 304 # A table holding all the namespaces IPython deals with, so that
305 305 # introspection facilities can search easily.
306 306 self.ns_table = {'user':user_ns,
307 307 'user_global':user_global_ns,
308 308 'alias':self.alias_table,
309 309 'internal':self.internal_ns,
310 310 'builtin':__builtin__.__dict__
311 311 }
312 312
313 313 # The user namespace MUST have a pointer to the shell itself.
314 314 self.user_ns[name] = self
315 315
316 316 # We need to insert into sys.modules something that looks like a
317 317 # module but which accesses the IPython namespace, for shelve and
318 318 # pickle to work interactively. Normally they rely on getting
319 319 # everything out of __main__, but for embedding purposes each IPython
320 320 # instance has its own private namespace, so we can't go shoving
321 321 # everything into __main__.
322 322
323 323 # note, however, that we should only do this for non-embedded
324 324 # ipythons, which really mimic the __main__.__dict__ with their own
325 325 # namespace. Embedded instances, on the other hand, should not do
326 326 # this because they need to manage the user local/global namespaces
327 327 # only, but they live within a 'normal' __main__ (meaning, they
328 328 # shouldn't overtake the execution environment of the script they're
329 329 # embedded in).
330 330
331 331 if not embedded:
332 332 try:
333 333 main_name = self.user_ns['__name__']
334 334 except KeyError:
335 335 raise KeyError,'user_ns dictionary MUST have a "__name__" key'
336 336 else:
337 337 #print "pickle hack in place" # dbg
338 338 #print 'main_name:',main_name # dbg
339 339 sys.modules[main_name] = FakeModule(self.user_ns)
340 340
341 341 # List of input with multi-line handling.
342 342 # Fill its zero entry, user counter starts at 1
343 343 self.input_hist = InputList(['\n'])
344 344 # This one will hold the 'raw' input history, without any
345 345 # pre-processing. This will allow users to retrieve the input just as
346 346 # it was exactly typed in by the user, with %hist -r.
347 347 self.input_hist_raw = InputList(['\n'])
348 348
349 349 # list of visited directories
350 350 try:
351 351 self.dir_hist = [os.getcwd()]
352 352 except IOError, e:
353 353 self.dir_hist = []
354 354
355 355 # dict of output history
356 356 self.output_hist = {}
357 357
358 358 # dict of things NOT to alias (keywords, builtins and some magics)
359 359 no_alias = {}
360 360 no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias']
361 361 for key in keyword.kwlist + no_alias_magics:
362 362 no_alias[key] = 1
363 363 no_alias.update(__builtin__.__dict__)
364 364 self.no_alias = no_alias
365 365
366 366 # make global variables for user access to these
367 367 self.user_ns['_ih'] = self.input_hist
368 368 self.user_ns['_oh'] = self.output_hist
369 369 self.user_ns['_dh'] = self.dir_hist
370 370
371 371 # user aliases to input and output histories
372 372 self.user_ns['In'] = self.input_hist
373 373 self.user_ns['Out'] = self.output_hist
374 374
375 375 # Object variable to store code object waiting execution. This is
376 376 # used mainly by the multithreaded shells, but it can come in handy in
377 377 # other situations. No need to use a Queue here, since it's a single
378 378 # item which gets cleared once run.
379 379 self.code_to_run = None
380 380
381 381 # escapes for automatic behavior on the command line
382 382 self.ESC_SHELL = '!'
383 383 self.ESC_HELP = '?'
384 384 self.ESC_MAGIC = '%'
385 385 self.ESC_QUOTE = ','
386 386 self.ESC_QUOTE2 = ';'
387 387 self.ESC_PAREN = '/'
388 388
389 389 # And their associated handlers
390 390 self.esc_handlers = {self.ESC_PAREN : self.handle_auto,
391 391 self.ESC_QUOTE : self.handle_auto,
392 392 self.ESC_QUOTE2 : self.handle_auto,
393 393 self.ESC_MAGIC : self.handle_magic,
394 394 self.ESC_HELP : self.handle_help,
395 395 self.ESC_SHELL : self.handle_shell_escape,
396 396 }
397 397
398 398 # class initializations
399 399 Magic.__init__(self,self)
400 400
401 401 # Python source parser/formatter for syntax highlighting
402 402 pyformat = PyColorize.Parser().format
403 403 self.pycolorize = lambda src: pyformat(src,'str',self.rc['colors'])
404 404
405 405 # hooks holds pointers used for user-side customizations
406 406 self.hooks = Struct()
407 407
408 408 self.strdispatchers = {}
409 409
410 410 # Set all default hooks, defined in the IPython.hooks module.
411 411 hooks = IPython.hooks
412 412 for hook_name in hooks.__all__:
413 413 # default hooks have priority 100, i.e. low; user hooks should have 0-100 priority
414 414 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
415 415 #print "bound hook",hook_name
416 416
417 417 # Flag to mark unconditional exit
418 418 self.exit_now = False
419 419
420 420 self.usage_min = """\
421 421 An enhanced console for Python.
422 422 Some of its features are:
423 423 - Readline support if the readline library is present.
424 424 - Tab completion in the local namespace.
425 425 - Logging of input, see command-line options.
426 426 - System shell escape via ! , eg !ls.
427 427 - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.)
428 428 - Keeps track of locally defined variables via %who, %whos.
429 429 - Show object information with a ? eg ?x or x? (use ?? for more info).
430 430 """
431 431 if usage: self.usage = usage
432 432 else: self.usage = self.usage_min
433 433
434 434 # Storage
435 435 self.rc = rc # This will hold all configuration information
436 436 self.pager = 'less'
437 437 # temporary files used for various purposes. Deleted at exit.
438 438 self.tempfiles = []
439 439
440 440 # Keep track of readline usage (later set by init_readline)
441 441 self.has_readline = False
442 442
443 443 # template for logfile headers. It gets resolved at runtime by the
444 444 # logstart method.
445 445 self.loghead_tpl = \
446 446 """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE ***
447 447 #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW
448 448 #log# opts = %s
449 449 #log# args = %s
450 450 #log# It is safe to make manual edits below here.
451 451 #log#-----------------------------------------------------------------------
452 452 """
453 453 # for pushd/popd management
454 454 try:
455 455 self.home_dir = get_home_dir()
456 456 except HomeDirError,msg:
457 457 fatal(msg)
458 458
459 459 self.dir_stack = [os.getcwd().replace(self.home_dir,'~')]
460 460
461 461 # Functions to call the underlying shell.
462 462
463 463 # The first is similar to os.system, but it doesn't return a value,
464 464 # and it allows interpolation of variables in the user's namespace.
465 465 self.system = lambda cmd: \
466 466 shell(self.var_expand(cmd,depth=2),
467 467 header=self.rc.system_header,
468 468 verbose=self.rc.system_verbose)
469 469
470 470 # These are for getoutput and getoutputerror:
471 471 self.getoutput = lambda cmd: \
472 472 getoutput(self.var_expand(cmd,depth=2),
473 473 header=self.rc.system_header,
474 474 verbose=self.rc.system_verbose)
475 475
476 476 self.getoutputerror = lambda cmd: \
477 477 getoutputerror(self.var_expand(cmd,depth=2),
478 478 header=self.rc.system_header,
479 479 verbose=self.rc.system_verbose)
480 480
481 481 # RegExp for splitting line contents into pre-char//first
482 482 # word-method//rest. For clarity, each group in on one line.
483 483
484 484 # WARNING: update the regexp if the above escapes are changed, as they
485 485 # are hardwired in.
486 486
487 487 # Don't get carried away with trying to make the autocalling catch too
488 488 # much: it's better to be conservative rather than to trigger hidden
489 489 # evals() somewhere and end up causing side effects.
490 490 self.line_split = re.compile(r'^(\s*[,;/]?\s*)'
491 491 r'([\?\w\.]+\w*\s*)'
492 492 r'(\(?.*$)')
493 493
494 494 self.shell_line_split = re.compile(r'^(\s*)'
495 495 r'(\S*\s*)'
496 496 r'(\(?.*$)')
497 497
498 498
499 499 # A simpler regexp used as a fallback if the above doesn't work. This
500 500 # one is more conservative in how it partitions the input. This code
501 501 # can probably be cleaned up to do everything with just one regexp, but
502 502 # I'm afraid of breaking something; do it once the unit tests are in
503 503 # place.
504 504 self.line_split_fallback = re.compile(r'^(\s*)'
505 505 r'([%\!\?\w\.]*)'
506 506 r'(.*)')
507 507
508 508 # Original re, keep around for a while in case changes break something
509 509 #self.line_split = re.compile(r'(^[\s*!\?%,/]?)'
510 510 # r'(\s*[\?\w\.]+\w*\s*)'
511 511 # r'(\(?.*$)')
512 512
513 513 # RegExp to identify potential function names
514 514 self.re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$')
515 515
516 516 # RegExp to exclude strings with this start from autocalling. In
517 517 # particular, all binary operators should be excluded, so that if foo
518 518 # is callable, foo OP bar doesn't become foo(OP bar), which is
519 519 # invalid. The characters '!=()' don't need to be checked for, as the
520 520 # _prefilter routine explicitely does so, to catch direct calls and
521 521 # rebindings of existing names.
522 522
523 523 # Warning: the '-' HAS TO BE AT THE END of the first group, otherwise
524 524 # it affects the rest of the group in square brackets.
525 525 self.re_exclude_auto = re.compile(r'^[<>,&^\|\*/\+-]'
526 526 '|^is |^not |^in |^and |^or ')
527 527
528 528 # try to catch also methods for stuff in lists/tuples/dicts: off
529 529 # (experimental). For this to work, the line_split regexp would need
530 530 # to be modified so it wouldn't break things at '['. That line is
531 531 # nasty enough that I shouldn't change it until I can test it _well_.
532 532 #self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$')
533 533
534 534 # keep track of where we started running (mainly for crash post-mortem)
535 535 self.starting_dir = os.getcwd()
536 536
537 537 # Various switches which can be set
538 538 self.CACHELENGTH = 5000 # this is cheap, it's just text
539 539 self.BANNER = "Python %(version)s on %(platform)s\n" % sys.__dict__
540 540 self.banner2 = banner2
541 541
542 542 # TraceBack handlers:
543 543
544 544 # Syntax error handler.
545 545 self.SyntaxTB = SyntaxTB(color_scheme='NoColor')
546 546
547 547 # The interactive one is initialized with an offset, meaning we always
548 548 # want to remove the topmost item in the traceback, which is our own
549 549 # internal code. Valid modes: ['Plain','Context','Verbose']
550 550 self.InteractiveTB = ultraTB.AutoFormattedTB(mode = 'Plain',
551 551 color_scheme='NoColor',
552 552 tb_offset = 1)
553 553
554 554 # IPython itself shouldn't crash. This will produce a detailed
555 555 # post-mortem if it does. But we only install the crash handler for
556 556 # non-threaded shells, the threaded ones use a normal verbose reporter
557 557 # and lose the crash handler. This is because exceptions in the main
558 558 # thread (such as in GUI code) propagate directly to sys.excepthook,
559 559 # and there's no point in printing crash dumps for every user exception.
560 560 if self.isthreaded:
561 561 ipCrashHandler = ultraTB.FormattedTB()
562 562 else:
563 563 from IPython import CrashHandler
564 564 ipCrashHandler = CrashHandler.IPythonCrashHandler(self)
565 565 self.set_crash_handler(ipCrashHandler)
566 566
567 567 # and add any custom exception handlers the user may have specified
568 568 self.set_custom_exc(*custom_exceptions)
569 569
570 570 # indentation management
571 571 self.autoindent = False
572 572 self.indent_current_nsp = 0
573 573
574 574 # Make some aliases automatically
575 575 # Prepare list of shell aliases to auto-define
576 576 if os.name == 'posix':
577 577 auto_alias = ('mkdir mkdir', 'rmdir rmdir',
578 578 'mv mv -i','rm rm -i','cp cp -i',
579 579 'cat cat','less less','clear clear',
580 580 # a better ls
581 581 'ls ls -F',
582 582 # long ls
583 583 'll ls -lF')
584 584 # Extra ls aliases with color, which need special treatment on BSD
585 585 # variants
586 586 ls_extra = ( # color ls
587 587 'lc ls -F -o --color',
588 588 # ls normal files only
589 589 'lf ls -F -o --color %l | grep ^-',
590 590 # ls symbolic links
591 591 'lk ls -F -o --color %l | grep ^l',
592 592 # directories or links to directories,
593 593 'ldir ls -F -o --color %l | grep /$',
594 594 # things which are executable
595 595 'lx ls -F -o --color %l | grep ^-..x',
596 596 )
597 597 # The BSDs don't ship GNU ls, so they don't understand the
598 598 # --color switch out of the box
599 599 if 'bsd' in sys.platform:
600 600 ls_extra = ( # ls normal files only
601 601 'lf ls -lF | grep ^-',
602 602 # ls symbolic links
603 603 'lk ls -lF | grep ^l',
604 604 # directories or links to directories,
605 605 'ldir ls -lF | grep /$',
606 606 # things which are executable
607 607 'lx ls -lF | grep ^-..x',
608 608 )
609 609 auto_alias = auto_alias + ls_extra
610 610 elif os.name in ['nt','dos']:
611 611 auto_alias = ('dir dir /on', 'ls dir /on',
612 612 'ddir dir /ad /on', 'ldir dir /ad /on',
613 613 'mkdir mkdir','rmdir rmdir','echo echo',
614 614 'ren ren','cls cls','copy copy')
615 615 else:
616 616 auto_alias = ()
617 617 self.auto_alias = [s.split(None,1) for s in auto_alias]
618 618 # Call the actual (public) initializer
619 619 self.init_auto_alias()
620 620
621 621 # Produce a public API instance
622 622 self.api = IPython.ipapi.IPApi(self)
623 623
624 624 # track which builtins we add, so we can clean up later
625 625 self.builtins_added = {}
626 626 # This method will add the necessary builtins for operation, but
627 627 # tracking what it did via the builtins_added dict.
628 628 self.add_builtins()
629 629
630 630 # end __init__
631 631
632 632 def var_expand(self,cmd,depth=0):
633 633 """Expand python variables in a string.
634 634
635 635 The depth argument indicates how many frames above the caller should
636 636 be walked to look for the local namespace where to expand variables.
637 637
638 638 The global namespace for expansion is always the user's interactive
639 639 namespace.
640 640 """
641 641
642 642 return str(ItplNS(cmd.replace('#','\#'),
643 643 self.user_ns, # globals
644 644 # Skip our own frame in searching for locals:
645 645 sys._getframe(depth+1).f_locals # locals
646 646 ))
647 647
648 648 def pre_config_initialization(self):
649 649 """Pre-configuration init method
650 650
651 651 This is called before the configuration files are processed to
652 652 prepare the services the config files might need.
653 653
654 654 self.rc already has reasonable default values at this point.
655 655 """
656 656 rc = self.rc
657 657
658 658 self.db = pickleshare.PickleShareDB(rc.ipythondir + "/db")
659 659
660 660 def post_config_initialization(self):
661 661 """Post configuration init method
662 662
663 663 This is called after the configuration files have been processed to
664 664 'finalize' the initialization."""
665 665
666 666 rc = self.rc
667 667
668 668 # Object inspector
669 669 self.inspector = OInspect.Inspector(OInspect.InspectColors,
670 670 PyColorize.ANSICodeColors,
671 671 'NoColor',
672 672 rc.object_info_string_level)
673 673
674 674 # Load readline proper
675 675 if rc.readline:
676 676 self.init_readline()
677 677
678 678 # local shortcut, this is used a LOT
679 679 self.log = self.logger.log
680 680
681 681 # Initialize cache, set in/out prompts and printing system
682 682 self.outputcache = CachedOutput(self,
683 683 rc.cache_size,
684 684 rc.pprint,
685 685 input_sep = rc.separate_in,
686 686 output_sep = rc.separate_out,
687 687 output_sep2 = rc.separate_out2,
688 688 ps1 = rc.prompt_in1,
689 689 ps2 = rc.prompt_in2,
690 690 ps_out = rc.prompt_out,
691 691 pad_left = rc.prompts_pad_left)
692 692
693 693 # user may have over-ridden the default print hook:
694 694 try:
695 695 self.outputcache.__class__.display = self.hooks.display
696 696 except AttributeError:
697 697 pass
698 698
699 699 # I don't like assigning globally to sys, because it means when
700 700 # embedding instances, each embedded instance overrides the previous
701 701 # choice. But sys.displayhook seems to be called internally by exec,
702 702 # so I don't see a way around it. We first save the original and then
703 703 # overwrite it.
704 704 self.sys_displayhook = sys.displayhook
705 705 sys.displayhook = self.outputcache
706 706
707 707 # Set user colors (don't do it in the constructor above so that it
708 708 # doesn't crash if colors option is invalid)
709 709 self.magic_colors(rc.colors)
710 710
711 711 # Set calling of pdb on exceptions
712 712 self.call_pdb = rc.pdb
713 713
714 714 # Load user aliases
715 715 for alias in rc.alias:
716 716 self.magic_alias(alias)
717 717 self.hooks.late_startup_hook()
718 718
719 719 batchrun = False
720 720 for batchfile in [path(arg) for arg in self.rc.args
721 721 if arg.lower().endswith('.ipy')]:
722 722 if not batchfile.isfile():
723 723 print "No such batch file:", batchfile
724 724 continue
725 725 self.api.runlines(batchfile.text())
726 726 batchrun = True
727 727 if batchrun:
728 728 self.exit_now = True
729 729
730 730 def add_builtins(self):
731 731 """Store ipython references into the builtin namespace.
732 732
733 733 Some parts of ipython operate via builtins injected here, which hold a
734 734 reference to IPython itself."""
735 735
736 736 # TODO: deprecate all except _ip; 'jobs' should be installed
737 737 # by an extension and the rest are under _ip, ipalias is redundant
738 738 builtins_new = dict(__IPYTHON__ = self,
739 739 ip_set_hook = self.set_hook,
740 740 jobs = self.jobs,
741 741 ipmagic = wrap_deprecated(self.ipmagic,'_ip.magic()'),
742 742 ipalias = wrap_deprecated(self.ipalias),
743 743 ipsystem = wrap_deprecated(self.ipsystem,'_ip.system()'),
744 744 _ip = self.api
745 745 )
746 746 for biname,bival in builtins_new.items():
747 747 try:
748 748 # store the orignal value so we can restore it
749 749 self.builtins_added[biname] = __builtin__.__dict__[biname]
750 750 except KeyError:
751 751 # or mark that it wasn't defined, and we'll just delete it at
752 752 # cleanup
753 753 self.builtins_added[biname] = Undefined
754 754 __builtin__.__dict__[biname] = bival
755 755
756 756 # Keep in the builtins a flag for when IPython is active. We set it
757 757 # with setdefault so that multiple nested IPythons don't clobber one
758 758 # another. Each will increase its value by one upon being activated,
759 759 # which also gives us a way to determine the nesting level.
760 760 __builtin__.__dict__.setdefault('__IPYTHON__active',0)
761 761
762 762 def clean_builtins(self):
763 763 """Remove any builtins which might have been added by add_builtins, or
764 764 restore overwritten ones to their previous values."""
765 765 for biname,bival in self.builtins_added.items():
766 766 if bival is Undefined:
767 767 del __builtin__.__dict__[biname]
768 768 else:
769 769 __builtin__.__dict__[biname] = bival
770 770 self.builtins_added.clear()
771 771
772 772 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
773 773 """set_hook(name,hook) -> sets an internal IPython hook.
774 774
775 775 IPython exposes some of its internal API as user-modifiable hooks. By
776 776 adding your function to one of these hooks, you can modify IPython's
777 777 behavior to call at runtime your own routines."""
778 778
779 779 # At some point in the future, this should validate the hook before it
780 780 # accepts it. Probably at least check that the hook takes the number
781 781 # of args it's supposed to.
782 782
783 783 f = new.instancemethod(hook,self,self.__class__)
784 784
785 785 # check if the hook is for strdispatcher first
786 786 if str_key is not None:
787 787 sdp = self.strdispatchers.get(name, StrDispatch())
788 788 sdp.add_s(str_key, f, priority )
789 789 self.strdispatchers[name] = sdp
790 790 return
791 791 if re_key is not None:
792 792 sdp = self.strdispatchers.get(name, StrDispatch())
793 793 sdp.add_re(re.compile(re_key), f, priority )
794 794 self.strdispatchers[name] = sdp
795 795 return
796 796
797 797 dp = getattr(self.hooks, name, None)
798 798 if name not in IPython.hooks.__all__:
799 799 print "Warning! Hook '%s' is not one of %s" % (name, IPython.hooks.__all__ )
800 800 if not dp:
801 801 dp = IPython.hooks.CommandChainDispatcher()
802 802
803 803 try:
804 804 dp.add(f,priority)
805 805 except AttributeError:
806 806 # it was not commandchain, plain old func - replace
807 807 dp = f
808 808
809 809 setattr(self.hooks,name, dp)
810 810
811 811
812 812 #setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__))
813 813
814 814 def set_crash_handler(self,crashHandler):
815 815 """Set the IPython crash handler.
816 816
817 817 This must be a callable with a signature suitable for use as
818 818 sys.excepthook."""
819 819
820 820 # Install the given crash handler as the Python exception hook
821 821 sys.excepthook = crashHandler
822 822
823 823 # The instance will store a pointer to this, so that runtime code
824 824 # (such as magics) can access it. This is because during the
825 825 # read-eval loop, it gets temporarily overwritten (to deal with GUI
826 826 # frameworks).
827 827 self.sys_excepthook = sys.excepthook
828 828
829 829
830 830 def set_custom_exc(self,exc_tuple,handler):
831 831 """set_custom_exc(exc_tuple,handler)
832 832
833 833 Set a custom exception handler, which will be called if any of the
834 834 exceptions in exc_tuple occur in the mainloop (specifically, in the
835 835 runcode() method.
836 836
837 837 Inputs:
838 838
839 839 - exc_tuple: a *tuple* of valid exceptions to call the defined
840 840 handler for. It is very important that you use a tuple, and NOT A
841 841 LIST here, because of the way Python's except statement works. If
842 842 you only want to trap a single exception, use a singleton tuple:
843 843
844 844 exc_tuple == (MyCustomException,)
845 845
846 846 - handler: this must be defined as a function with the following
847 847 basic interface: def my_handler(self,etype,value,tb).
848 848
849 849 This will be made into an instance method (via new.instancemethod)
850 850 of IPython itself, and it will be called if any of the exceptions
851 851 listed in the exc_tuple are caught. If the handler is None, an
852 852 internal basic one is used, which just prints basic info.
853 853
854 854 WARNING: by putting in your own exception handler into IPython's main
855 855 execution loop, you run a very good chance of nasty crashes. This
856 856 facility should only be used if you really know what you are doing."""
857 857
858 858 assert type(exc_tuple)==type(()) , \
859 859 "The custom exceptions must be given AS A TUPLE."
860 860
861 861 def dummy_handler(self,etype,value,tb):
862 862 print '*** Simple custom exception handler ***'
863 863 print 'Exception type :',etype
864 864 print 'Exception value:',value
865 865 print 'Traceback :',tb
866 866 print 'Source code :','\n'.join(self.buffer)
867 867
868 868 if handler is None: handler = dummy_handler
869 869
870 870 self.CustomTB = new.instancemethod(handler,self,self.__class__)
871 871 self.custom_exceptions = exc_tuple
872 872
873 873 def set_custom_completer(self,completer,pos=0):
874 874 """set_custom_completer(completer,pos=0)
875 875
876 876 Adds a new custom completer function.
877 877
878 878 The position argument (defaults to 0) is the index in the completers
879 879 list where you want the completer to be inserted."""
880 880
881 881 newcomp = new.instancemethod(completer,self.Completer,
882 882 self.Completer.__class__)
883 883 self.Completer.matchers.insert(pos,newcomp)
884 884
885 885 def _get_call_pdb(self):
886 886 return self._call_pdb
887 887
888 888 def _set_call_pdb(self,val):
889 889
890 890 if val not in (0,1,False,True):
891 891 raise ValueError,'new call_pdb value must be boolean'
892 892
893 893 # store value in instance
894 894 self._call_pdb = val
895 895
896 896 # notify the actual exception handlers
897 897 self.InteractiveTB.call_pdb = val
898 898 if self.isthreaded:
899 899 try:
900 900 self.sys_excepthook.call_pdb = val
901 901 except:
902 902 warn('Failed to activate pdb for threaded exception handler')
903 903
904 904 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
905 905 'Control auto-activation of pdb at exceptions')
906 906
907 907
908 908 # These special functions get installed in the builtin namespace, to
909 909 # provide programmatic (pure python) access to magics, aliases and system
910 910 # calls. This is important for logging, user scripting, and more.
911 911
912 912 # We are basically exposing, via normal python functions, the three
913 913 # mechanisms in which ipython offers special call modes (magics for
914 914 # internal control, aliases for direct system access via pre-selected
915 915 # names, and !cmd for calling arbitrary system commands).
916 916
917 917 def ipmagic(self,arg_s):
918 918 """Call a magic function by name.
919 919
920 920 Input: a string containing the name of the magic function to call and any
921 921 additional arguments to be passed to the magic.
922 922
923 923 ipmagic('name -opt foo bar') is equivalent to typing at the ipython
924 924 prompt:
925 925
926 926 In[1]: %name -opt foo bar
927 927
928 928 To call a magic without arguments, simply use ipmagic('name').
929 929
930 930 This provides a proper Python function to call IPython's magics in any
931 931 valid Python code you can type at the interpreter, including loops and
932 932 compound statements. It is added by IPython to the Python builtin
933 933 namespace upon initialization."""
934 934
935 935 args = arg_s.split(' ',1)
936 936 magic_name = args[0]
937 937 magic_name = magic_name.lstrip(self.ESC_MAGIC)
938 938
939 939 try:
940 940 magic_args = args[1]
941 941 except IndexError:
942 942 magic_args = ''
943 943 fn = getattr(self,'magic_'+magic_name,None)
944 944 if fn is None:
945 945 error("Magic function `%s` not found." % magic_name)
946 946 else:
947 947 magic_args = self.var_expand(magic_args,1)
948 948 return fn(magic_args)
949 949
950 950 def ipalias(self,arg_s):
951 951 """Call an alias by name.
952 952
953 953 Input: a string containing the name of the alias to call and any
954 954 additional arguments to be passed to the magic.
955 955
956 956 ipalias('name -opt foo bar') is equivalent to typing at the ipython
957 957 prompt:
958 958
959 959 In[1]: name -opt foo bar
960 960
961 961 To call an alias without arguments, simply use ipalias('name').
962 962
963 963 This provides a proper Python function to call IPython's aliases in any
964 964 valid Python code you can type at the interpreter, including loops and
965 965 compound statements. It is added by IPython to the Python builtin
966 966 namespace upon initialization."""
967 967
968 968 args = arg_s.split(' ',1)
969 969 alias_name = args[0]
970 970 try:
971 971 alias_args = args[1]
972 972 except IndexError:
973 973 alias_args = ''
974 974 if alias_name in self.alias_table:
975 975 self.call_alias(alias_name,alias_args)
976 976 else:
977 977 error("Alias `%s` not found." % alias_name)
978 978
979 979 def ipsystem(self,arg_s):
980 980 """Make a system call, using IPython."""
981 981
982 982 self.system(arg_s)
983 983
984 984 def complete(self,text):
985 985 """Return a sorted list of all possible completions on text.
986 986
987 987 Inputs:
988 988
989 989 - text: a string of text to be completed on.
990 990
991 991 This is a wrapper around the completion mechanism, similar to what
992 992 readline does at the command line when the TAB key is hit. By
993 993 exposing it as a method, it can be used by other non-readline
994 994 environments (such as GUIs) for text completion.
995 995
996 996 Simple usage example:
997 997
998 998 In [1]: x = 'hello'
999 999
1000 1000 In [2]: __IP.complete('x.l')
1001 1001 Out[2]: ['x.ljust', 'x.lower', 'x.lstrip']"""
1002 1002
1003 1003 complete = self.Completer.complete
1004 1004 state = 0
1005 1005 # use a dict so we get unique keys, since ipyhton's multiple
1006 1006 # completers can return duplicates.
1007 1007 comps = {}
1008 1008 while True:
1009 1009 newcomp = complete(text,state)
1010 1010 if newcomp is None:
1011 1011 break
1012 1012 comps[newcomp] = 1
1013 1013 state += 1
1014 1014 outcomps = comps.keys()
1015 1015 outcomps.sort()
1016 1016 return outcomps
1017 1017
1018 1018 def set_completer_frame(self, frame=None):
1019 1019 if frame:
1020 1020 self.Completer.namespace = frame.f_locals
1021 1021 self.Completer.global_namespace = frame.f_globals
1022 1022 else:
1023 1023 self.Completer.namespace = self.user_ns
1024 1024 self.Completer.global_namespace = self.user_global_ns
1025 1025
1026 1026 def init_auto_alias(self):
1027 1027 """Define some aliases automatically.
1028 1028
1029 1029 These are ALL parameter-less aliases"""
1030 1030
1031 1031 for alias,cmd in self.auto_alias:
1032 1032 self.alias_table[alias] = (0,cmd)
1033 1033
1034 1034 def alias_table_validate(self,verbose=0):
1035 1035 """Update information about the alias table.
1036 1036
1037 1037 In particular, make sure no Python keywords/builtins are in it."""
1038 1038
1039 1039 no_alias = self.no_alias
1040 1040 for k in self.alias_table.keys():
1041 1041 if k in no_alias:
1042 1042 del self.alias_table[k]
1043 1043 if verbose:
1044 1044 print ("Deleting alias <%s>, it's a Python "
1045 1045 "keyword or builtin." % k)
1046 1046
1047 1047 def set_autoindent(self,value=None):
1048 1048 """Set the autoindent flag, checking for readline support.
1049 1049
1050 1050 If called with no arguments, it acts as a toggle."""
1051 1051
1052 1052 if not self.has_readline:
1053 1053 if os.name == 'posix':
1054 1054 warn("The auto-indent feature requires the readline library")
1055 1055 self.autoindent = 0
1056 1056 return
1057 1057 if value is None:
1058 1058 self.autoindent = not self.autoindent
1059 1059 else:
1060 1060 self.autoindent = value
1061 1061
1062 1062 def rc_set_toggle(self,rc_field,value=None):
1063 1063 """Set or toggle a field in IPython's rc config. structure.
1064 1064
1065 1065 If called with no arguments, it acts as a toggle.
1066 1066
1067 1067 If called with a non-existent field, the resulting AttributeError
1068 1068 exception will propagate out."""
1069 1069
1070 1070 rc_val = getattr(self.rc,rc_field)
1071 1071 if value is None:
1072 1072 value = not rc_val
1073 1073 setattr(self.rc,rc_field,value)
1074 1074
1075 1075 def user_setup(self,ipythondir,rc_suffix,mode='install'):
1076 1076 """Install the user configuration directory.
1077 1077
1078 1078 Can be called when running for the first time or to upgrade the user's
1079 1079 .ipython/ directory with the mode parameter. Valid modes are 'install'
1080 1080 and 'upgrade'."""
1081 1081
1082 1082 def wait():
1083 1083 try:
1084 1084 raw_input("Please press <RETURN> to start IPython.")
1085 1085 except EOFError:
1086 1086 print >> Term.cout
1087 1087 print '*'*70
1088 1088
1089 1089 cwd = os.getcwd() # remember where we started
1090 1090 glb = glob.glob
1091 1091 print '*'*70
1092 1092 if mode == 'install':
1093 1093 print \
1094 1094 """Welcome to IPython. I will try to create a personal configuration directory
1095 1095 where you can customize many aspects of IPython's functionality in:\n"""
1096 1096 else:
1097 1097 print 'I am going to upgrade your configuration in:'
1098 1098
1099 1099 print ipythondir
1100 1100
1101 1101 rcdirend = os.path.join('IPython','UserConfig')
1102 1102 cfg = lambda d: os.path.join(d,rcdirend)
1103 1103 try:
1104 1104 rcdir = filter(os.path.isdir,map(cfg,sys.path))[0]
1105 1105 except IOError:
1106 1106 warning = """
1107 1107 Installation error. IPython's directory was not found.
1108 1108
1109 1109 Check the following:
1110 1110
1111 1111 The ipython/IPython directory should be in a directory belonging to your
1112 1112 PYTHONPATH environment variable (that is, it should be in a directory
1113 1113 belonging to sys.path). You can copy it explicitly there or just link to it.
1114 1114
1115 1115 IPython will proceed with builtin defaults.
1116 1116 """
1117 1117 warn(warning)
1118 1118 wait()
1119 1119 return
1120 1120
1121 1121 if mode == 'install':
1122 1122 try:
1123 1123 shutil.copytree(rcdir,ipythondir)
1124 1124 os.chdir(ipythondir)
1125 1125 rc_files = glb("ipythonrc*")
1126 1126 for rc_file in rc_files:
1127 1127 os.rename(rc_file,rc_file+rc_suffix)
1128 1128 except:
1129 1129 warning = """
1130 1130
1131 1131 There was a problem with the installation:
1132 1132 %s
1133 1133 Try to correct it or contact the developers if you think it's a bug.
1134 1134 IPython will proceed with builtin defaults.""" % sys.exc_info()[1]
1135 1135 warn(warning)
1136 1136 wait()
1137 1137 return
1138 1138
1139 1139 elif mode == 'upgrade':
1140 1140 try:
1141 1141 os.chdir(ipythondir)
1142 1142 except:
1143 1143 print """
1144 1144 Can not upgrade: changing to directory %s failed. Details:
1145 1145 %s
1146 1146 """ % (ipythondir,sys.exc_info()[1])
1147 1147 wait()
1148 1148 return
1149 1149 else:
1150 1150 sources = glb(os.path.join(rcdir,'[A-Za-z]*'))
1151 1151 for new_full_path in sources:
1152 1152 new_filename = os.path.basename(new_full_path)
1153 1153 if new_filename.startswith('ipythonrc'):
1154 1154 new_filename = new_filename + rc_suffix
1155 1155 # The config directory should only contain files, skip any
1156 1156 # directories which may be there (like CVS)
1157 1157 if os.path.isdir(new_full_path):
1158 1158 continue
1159 1159 if os.path.exists(new_filename):
1160 1160 old_file = new_filename+'.old'
1161 1161 if os.path.exists(old_file):
1162 1162 os.remove(old_file)
1163 1163 os.rename(new_filename,old_file)
1164 1164 shutil.copy(new_full_path,new_filename)
1165 1165 else:
1166 1166 raise ValueError,'unrecognized mode for install:',`mode`
1167 1167
1168 1168 # Fix line-endings to those native to each platform in the config
1169 1169 # directory.
1170 1170 try:
1171 1171 os.chdir(ipythondir)
1172 1172 except:
1173 1173 print """
1174 1174 Problem: changing to directory %s failed.
1175 1175 Details:
1176 1176 %s
1177 1177
1178 1178 Some configuration files may have incorrect line endings. This should not
1179 1179 cause any problems during execution. """ % (ipythondir,sys.exc_info()[1])
1180 1180 wait()
1181 1181 else:
1182 1182 for fname in glb('ipythonrc*'):
1183 1183 try:
1184 1184 native_line_ends(fname,backup=0)
1185 1185 except IOError:
1186 1186 pass
1187 1187
1188 1188 if mode == 'install':
1189 1189 print """
1190 1190 Successful installation!
1191 1191
1192 1192 Please read the sections 'Initial Configuration' and 'Quick Tips' in the
1193 1193 IPython manual (there are both HTML and PDF versions supplied with the
1194 1194 distribution) to make sure that your system environment is properly configured
1195 1195 to take advantage of IPython's features.
1196 1196
1197 1197 Important note: the configuration system has changed! The old system is
1198 1198 still in place, but its setting may be partly overridden by the settings in
1199 1199 "~/.ipython/ipy_user_conf.py" config file. Please take a look at the file
1200 1200 if some of the new settings bother you.
1201 1201
1202 1202 """
1203 1203 else:
1204 1204 print """
1205 1205 Successful upgrade!
1206 1206
1207 1207 All files in your directory:
1208 1208 %(ipythondir)s
1209 1209 which would have been overwritten by the upgrade were backed up with a .old
1210 1210 extension. If you had made particular customizations in those files you may
1211 1211 want to merge them back into the new files.""" % locals()
1212 1212 wait()
1213 1213 os.chdir(cwd)
1214 1214 # end user_setup()
1215 1215
1216 1216 def atexit_operations(self):
1217 1217 """This will be executed at the time of exit.
1218 1218
1219 1219 Saving of persistent data should be performed here. """
1220 1220
1221 1221 #print '*** IPython exit cleanup ***' # dbg
1222 1222 # input history
1223 1223 self.savehist()
1224 1224
1225 1225 # Cleanup all tempfiles left around
1226 1226 for tfile in self.tempfiles:
1227 1227 try:
1228 1228 os.unlink(tfile)
1229 1229 except OSError:
1230 1230 pass
1231 1231
1232 1232 # save the "persistent data" catch-all dictionary
1233 1233 self.hooks.shutdown_hook()
1234 1234
1235 1235 def savehist(self):
1236 1236 """Save input history to a file (via readline library)."""
1237 1237 try:
1238 1238 self.readline.write_history_file(self.histfile)
1239 1239 except:
1240 1240 print 'Unable to save IPython command history to file: ' + \
1241 1241 `self.histfile`
1242 1242
1243 1243 def history_saving_wrapper(self, func):
1244 1244 """ Wrap func for readline history saving
1245 1245
1246 1246 Convert func into callable that saves & restores
1247 1247 history around the call """
1248 1248
1249 1249 if not self.has_readline:
1250 1250 return func
1251 1251
1252 1252 def wrapper():
1253 1253 self.savehist()
1254 1254 try:
1255 1255 func()
1256 1256 finally:
1257 1257 readline.read_history_file(self.histfile)
1258 1258 return wrapper
1259 1259
1260 1260
1261 1261 def pre_readline(self):
1262 1262 """readline hook to be used at the start of each line.
1263 1263
1264 1264 Currently it handles auto-indent only."""
1265 1265
1266 1266 #debugx('self.indent_current_nsp','pre_readline:')
1267 1267 self.readline.insert_text(self.indent_current_str())
1268 1268
1269 1269 def init_readline(self):
1270 1270 """Command history completion/saving/reloading."""
1271 1271
1272 1272 import IPython.rlineimpl as readline
1273 1273 if not readline.have_readline:
1274 1274 self.has_readline = 0
1275 1275 self.readline = None
1276 1276 # no point in bugging windows users with this every time:
1277 1277 warn('Readline services not available on this platform.')
1278 1278 else:
1279 1279 sys.modules['readline'] = readline
1280 1280 import atexit
1281 1281 from IPython.completer import IPCompleter
1282 1282 self.Completer = IPCompleter(self,
1283 1283 self.user_ns,
1284 1284 self.user_global_ns,
1285 1285 self.rc.readline_omit__names,
1286 1286 self.alias_table)
1287 1287 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1288 1288 self.strdispatchers['complete_command'] = sdisp
1289 1289 self.Completer.custom_completers = sdisp
1290 1290 # Platform-specific configuration
1291 1291 if os.name == 'nt':
1292 1292 self.readline_startup_hook = readline.set_pre_input_hook
1293 1293 else:
1294 1294 self.readline_startup_hook = readline.set_startup_hook
1295 1295
1296 1296 # Load user's initrc file (readline config)
1297 1297 inputrc_name = os.environ.get('INPUTRC')
1298 1298 if inputrc_name is None:
1299 1299 home_dir = get_home_dir()
1300 1300 if home_dir is not None:
1301 1301 inputrc_name = os.path.join(home_dir,'.inputrc')
1302 1302 if os.path.isfile(inputrc_name):
1303 1303 try:
1304 1304 readline.read_init_file(inputrc_name)
1305 1305 except:
1306 1306 warn('Problems reading readline initialization file <%s>'
1307 1307 % inputrc_name)
1308 1308
1309 1309 self.has_readline = 1
1310 1310 self.readline = readline
1311 1311 # save this in sys so embedded copies can restore it properly
1312 1312 sys.ipcompleter = self.Completer.complete
1313 1313 readline.set_completer(self.Completer.complete)
1314 1314
1315 1315 # Configure readline according to user's prefs
1316 1316 for rlcommand in self.rc.readline_parse_and_bind:
1317 1317 readline.parse_and_bind(rlcommand)
1318 1318
1319 1319 # remove some chars from the delimiters list
1320 1320 delims = readline.get_completer_delims()
1321 1321 delims = delims.translate(string._idmap,
1322 1322 self.rc.readline_remove_delims)
1323 1323 readline.set_completer_delims(delims)
1324 1324 # otherwise we end up with a monster history after a while:
1325 1325 readline.set_history_length(1000)
1326 1326 try:
1327 1327 #print '*** Reading readline history' # dbg
1328 1328 readline.read_history_file(self.histfile)
1329 1329 except IOError:
1330 1330 pass # It doesn't exist yet.
1331 1331
1332 1332 atexit.register(self.atexit_operations)
1333 1333 del atexit
1334 1334
1335 1335 # Configure auto-indent for all platforms
1336 1336 self.set_autoindent(self.rc.autoindent)
1337 1337
1338 1338 def ask_yes_no(self,prompt,default=True):
1339 1339 if self.rc.quiet:
1340 1340 return True
1341 1341 return ask_yes_no(prompt,default)
1342 1342
1343 1343 def _should_recompile(self,e):
1344 1344 """Utility routine for edit_syntax_error"""
1345 1345
1346 1346 if e.filename in ('<ipython console>','<input>','<string>',
1347 1347 '<console>','<BackgroundJob compilation>',
1348 1348 None):
1349 1349
1350 1350 return False
1351 1351 try:
1352 1352 if (self.rc.autoedit_syntax and
1353 1353 not self.ask_yes_no('Return to editor to correct syntax error? '
1354 1354 '[Y/n] ','y')):
1355 1355 return False
1356 1356 except EOFError:
1357 1357 return False
1358 1358
1359 1359 def int0(x):
1360 1360 try:
1361 1361 return int(x)
1362 1362 except TypeError:
1363 1363 return 0
1364 1364 # always pass integer line and offset values to editor hook
1365 1365 self.hooks.fix_error_editor(e.filename,
1366 1366 int0(e.lineno),int0(e.offset),e.msg)
1367 1367 return True
1368 1368
1369 1369 def edit_syntax_error(self):
1370 1370 """The bottom half of the syntax error handler called in the main loop.
1371 1371
1372 1372 Loop until syntax error is fixed or user cancels.
1373 1373 """
1374 1374
1375 1375 while self.SyntaxTB.last_syntax_error:
1376 1376 # copy and clear last_syntax_error
1377 1377 err = self.SyntaxTB.clear_err_state()
1378 1378 if not self._should_recompile(err):
1379 1379 return
1380 1380 try:
1381 1381 # may set last_syntax_error again if a SyntaxError is raised
1382 1382 self.safe_execfile(err.filename,self.user_ns)
1383 1383 except:
1384 1384 self.showtraceback()
1385 1385 else:
1386 1386 try:
1387 1387 f = file(err.filename)
1388 1388 try:
1389 1389 sys.displayhook(f.read())
1390 1390 finally:
1391 1391 f.close()
1392 1392 except:
1393 1393 self.showtraceback()
1394 1394
1395 1395 def showsyntaxerror(self, filename=None):
1396 1396 """Display the syntax error that just occurred.
1397 1397
1398 1398 This doesn't display a stack trace because there isn't one.
1399 1399
1400 1400 If a filename is given, it is stuffed in the exception instead
1401 1401 of what was there before (because Python's parser always uses
1402 1402 "<string>" when reading from a string).
1403 1403 """
1404 1404 etype, value, last_traceback = sys.exc_info()
1405 1405
1406 1406 # See note about these variables in showtraceback() below
1407 1407 sys.last_type = etype
1408 1408 sys.last_value = value
1409 1409 sys.last_traceback = last_traceback
1410 1410
1411 1411 if filename and etype is SyntaxError:
1412 1412 # Work hard to stuff the correct filename in the exception
1413 1413 try:
1414 1414 msg, (dummy_filename, lineno, offset, line) = value
1415 1415 except:
1416 1416 # Not the format we expect; leave it alone
1417 1417 pass
1418 1418 else:
1419 1419 # Stuff in the right filename
1420 1420 try:
1421 1421 # Assume SyntaxError is a class exception
1422 1422 value = SyntaxError(msg, (filename, lineno, offset, line))
1423 1423 except:
1424 1424 # If that failed, assume SyntaxError is a string
1425 1425 value = msg, (filename, lineno, offset, line)
1426 1426 self.SyntaxTB(etype,value,[])
1427 1427
1428 1428 def debugger(self,force=False):
1429 1429 """Call the pydb/pdb debugger.
1430 1430
1431 1431 Keywords:
1432 1432
1433 1433 - force(False): by default, this routine checks the instance call_pdb
1434 1434 flag and does not actually invoke the debugger if the flag is false.
1435 1435 The 'force' option forces the debugger to activate even if the flag
1436 1436 is false.
1437 1437 """
1438 1438
1439 1439 if not (force or self.call_pdb):
1440 1440 return
1441 1441
1442 1442 if not hasattr(sys,'last_traceback'):
1443 1443 error('No traceback has been produced, nothing to debug.')
1444 1444 return
1445 1445
1446 1446 have_pydb = False
1447 1447 # use pydb if available
1448 1448 try:
1449 1449 from pydb import pm
1450 1450 have_pydb = True
1451 1451 except ImportError:
1452 1452 pass
1453 1453 if not have_pydb:
1454 1454 # fallback to our internal debugger
1455 1455 pm = lambda : self.InteractiveTB.debugger(force=True)
1456 1456 self.history_saving_wrapper(pm)()
1457 1457
1458 1458 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None):
1459 1459 """Display the exception that just occurred.
1460 1460
1461 1461 If nothing is known about the exception, this is the method which
1462 1462 should be used throughout the code for presenting user tracebacks,
1463 1463 rather than directly invoking the InteractiveTB object.
1464 1464
1465 1465 A specific showsyntaxerror() also exists, but this method can take
1466 1466 care of calling it if needed, so unless you are explicitly catching a
1467 1467 SyntaxError exception, don't try to analyze the stack manually and
1468 1468 simply call this method."""
1469 1469
1470 1470 # Though this won't be called by syntax errors in the input line,
1471 1471 # there may be SyntaxError cases whith imported code.
1472 1472 if exc_tuple is None:
1473 1473 etype, value, tb = sys.exc_info()
1474 1474 else:
1475 1475 etype, value, tb = exc_tuple
1476 1476
1477 1477 if etype is SyntaxError:
1478 1478 self.showsyntaxerror(filename)
1479 1479 else:
1480 1480 # WARNING: these variables are somewhat deprecated and not
1481 1481 # necessarily safe to use in a threaded environment, but tools
1482 1482 # like pdb depend on their existence, so let's set them. If we
1483 1483 # find problems in the field, we'll need to revisit their use.
1484 1484 sys.last_type = etype
1485 1485 sys.last_value = value
1486 1486 sys.last_traceback = tb
1487 1487
1488 1488 if etype in self.custom_exceptions:
1489 1489 self.CustomTB(etype,value,tb)
1490 1490 else:
1491 1491 self.InteractiveTB(etype,value,tb,tb_offset=tb_offset)
1492 1492 if self.InteractiveTB.call_pdb and self.has_readline:
1493 1493 # pdb mucks up readline, fix it back
1494 1494 self.readline.set_completer(self.Completer.complete)
1495 1495
1496 1496 def mainloop(self,banner=None):
1497 1497 """Creates the local namespace and starts the mainloop.
1498 1498
1499 1499 If an optional banner argument is given, it will override the
1500 1500 internally created default banner."""
1501 1501
1502 1502 if self.rc.c: # Emulate Python's -c option
1503 1503 self.exec_init_cmd()
1504 1504 if banner is None:
1505 1505 if not self.rc.banner:
1506 1506 banner = ''
1507 1507 # banner is string? Use it directly!
1508 1508 elif isinstance(self.rc.banner,basestring):
1509 1509 banner = self.rc.banner
1510 1510 else:
1511 1511 banner = self.BANNER+self.banner2
1512 1512
1513 1513 self.interact(banner)
1514 1514
1515 1515 def exec_init_cmd(self):
1516 1516 """Execute a command given at the command line.
1517 1517
1518 1518 This emulates Python's -c option."""
1519 1519
1520 1520 #sys.argv = ['-c']
1521 1521 self.push(self.rc.c)
1522 1522
1523 1523 def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0):
1524 1524 """Embeds IPython into a running python program.
1525 1525
1526 1526 Input:
1527 1527
1528 1528 - header: An optional header message can be specified.
1529 1529
1530 1530 - local_ns, global_ns: working namespaces. If given as None, the
1531 1531 IPython-initialized one is updated with __main__.__dict__, so that
1532 1532 program variables become visible but user-specific configuration
1533 1533 remains possible.
1534 1534
1535 1535 - stack_depth: specifies how many levels in the stack to go to
1536 1536 looking for namespaces (when local_ns and global_ns are None). This
1537 1537 allows an intermediate caller to make sure that this function gets
1538 1538 the namespace from the intended level in the stack. By default (0)
1539 1539 it will get its locals and globals from the immediate caller.
1540 1540
1541 1541 Warning: it's possible to use this in a program which is being run by
1542 1542 IPython itself (via %run), but some funny things will happen (a few
1543 1543 globals get overwritten). In the future this will be cleaned up, as
1544 1544 there is no fundamental reason why it can't work perfectly."""
1545 1545
1546 1546 # Get locals and globals from caller
1547 1547 if local_ns is None or global_ns is None:
1548 1548 call_frame = sys._getframe(stack_depth).f_back
1549 1549
1550 1550 if local_ns is None:
1551 1551 local_ns = call_frame.f_locals
1552 1552 if global_ns is None:
1553 1553 global_ns = call_frame.f_globals
1554 1554
1555 1555 # Update namespaces and fire up interpreter
1556 1556
1557 1557 # The global one is easy, we can just throw it in
1558 1558 self.user_global_ns = global_ns
1559 1559
1560 1560 # but the user/local one is tricky: ipython needs it to store internal
1561 1561 # data, but we also need the locals. We'll copy locals in the user
1562 1562 # one, but will track what got copied so we can delete them at exit.
1563 1563 # This is so that a later embedded call doesn't see locals from a
1564 1564 # previous call (which most likely existed in a separate scope).
1565 1565 local_varnames = local_ns.keys()
1566 1566 self.user_ns.update(local_ns)
1567 1567
1568 1568 # Patch for global embedding to make sure that things don't overwrite
1569 1569 # user globals accidentally. Thanks to Richard <rxe@renre-europe.com>
1570 1570 # FIXME. Test this a bit more carefully (the if.. is new)
1571 1571 if local_ns is None and global_ns is None:
1572 1572 self.user_global_ns.update(__main__.__dict__)
1573 1573
1574 1574 # make sure the tab-completer has the correct frame information, so it
1575 1575 # actually completes using the frame's locals/globals
1576 1576 self.set_completer_frame()
1577 1577
1578 1578 # before activating the interactive mode, we need to make sure that
1579 1579 # all names in the builtin namespace needed by ipython point to
1580 1580 # ourselves, and not to other instances.
1581 1581 self.add_builtins()
1582 1582
1583 1583 self.interact(header)
1584 1584
1585 1585 # now, purge out the user namespace from anything we might have added
1586 1586 # from the caller's local namespace
1587 1587 delvar = self.user_ns.pop
1588 1588 for var in local_varnames:
1589 1589 delvar(var,None)
1590 1590 # and clean builtins we may have overridden
1591 1591 self.clean_builtins()
1592 1592
1593 1593 def interact(self, banner=None):
1594 1594 """Closely emulate the interactive Python console.
1595 1595
1596 1596 The optional banner argument specify the banner to print
1597 1597 before the first interaction; by default it prints a banner
1598 1598 similar to the one printed by the real Python interpreter,
1599 1599 followed by the current class name in parentheses (so as not
1600 1600 to confuse this with the real interpreter -- since it's so
1601 1601 close!).
1602 1602
1603 1603 """
1604 1604
1605 1605 if self.exit_now:
1606 1606 # batch run -> do not interact
1607 1607 return
1608 1608 cprt = 'Type "copyright", "credits" or "license" for more information.'
1609 1609 if banner is None:
1610 1610 self.write("Python %s on %s\n%s\n(%s)\n" %
1611 1611 (sys.version, sys.platform, cprt,
1612 1612 self.__class__.__name__))
1613 1613 else:
1614 1614 self.write(banner)
1615 1615
1616 1616 more = 0
1617 1617
1618 1618 # Mark activity in the builtins
1619 1619 __builtin__.__dict__['__IPYTHON__active'] += 1
1620 1620
1621 1621 # exit_now is set by a call to %Exit or %Quit
1622 1622 while not self.exit_now:
1623 1623 if more:
1624 1624 prompt = self.hooks.generate_prompt(True)
1625 1625 if self.autoindent:
1626 1626 self.readline_startup_hook(self.pre_readline)
1627 1627 else:
1628 1628 prompt = self.hooks.generate_prompt(False)
1629 1629 try:
1630 1630 line = self.raw_input(prompt,more)
1631 1631 if self.exit_now:
1632 1632 # quick exit on sys.std[in|out] close
1633 1633 break
1634 1634 if self.autoindent:
1635 1635 self.readline_startup_hook(None)
1636 1636 except KeyboardInterrupt:
1637 1637 self.write('\nKeyboardInterrupt\n')
1638 1638 self.resetbuffer()
1639 1639 # keep cache in sync with the prompt counter:
1640 1640 self.outputcache.prompt_count -= 1
1641 1641
1642 1642 if self.autoindent:
1643 1643 self.indent_current_nsp = 0
1644 1644 more = 0
1645 1645 except EOFError:
1646 1646 if self.autoindent:
1647 1647 self.readline_startup_hook(None)
1648 1648 self.write('\n')
1649 1649 self.exit()
1650 1650 except bdb.BdbQuit:
1651 1651 warn('The Python debugger has exited with a BdbQuit exception.\n'
1652 1652 'Because of how pdb handles the stack, it is impossible\n'
1653 1653 'for IPython to properly format this particular exception.\n'
1654 1654 'IPython will resume normal operation.')
1655 1655 except:
1656 1656 # exceptions here are VERY RARE, but they can be triggered
1657 1657 # asynchronously by signal handlers, for example.
1658 1658 self.showtraceback()
1659 1659 else:
1660 1660 more = self.push(line)
1661 1661 if (self.SyntaxTB.last_syntax_error and
1662 1662 self.rc.autoedit_syntax):
1663 1663 self.edit_syntax_error()
1664 1664
1665 1665 # We are off again...
1666 1666 __builtin__.__dict__['__IPYTHON__active'] -= 1
1667 1667
1668 1668 def excepthook(self, etype, value, tb):
1669 1669 """One more defense for GUI apps that call sys.excepthook.
1670 1670
1671 1671 GUI frameworks like wxPython trap exceptions and call
1672 1672 sys.excepthook themselves. I guess this is a feature that
1673 1673 enables them to keep running after exceptions that would
1674 1674 otherwise kill their mainloop. This is a bother for IPython
1675 1675 which excepts to catch all of the program exceptions with a try:
1676 1676 except: statement.
1677 1677
1678 1678 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1679 1679 any app directly invokes sys.excepthook, it will look to the user like
1680 1680 IPython crashed. In order to work around this, we can disable the
1681 1681 CrashHandler and replace it with this excepthook instead, which prints a
1682 1682 regular traceback using our InteractiveTB. In this fashion, apps which
1683 1683 call sys.excepthook will generate a regular-looking exception from
1684 1684 IPython, and the CrashHandler will only be triggered by real IPython
1685 1685 crashes.
1686 1686
1687 1687 This hook should be used sparingly, only in places which are not likely
1688 1688 to be true IPython errors.
1689 1689 """
1690 1690 self.showtraceback((etype,value,tb),tb_offset=0)
1691 1691
1692 1692 def expand_aliases(self,fn,rest):
1693 1693 """ Expand multiple levels of aliases:
1694 1694
1695 1695 if:
1696 1696
1697 1697 alias foo bar /tmp
1698 1698 alias baz foo
1699 1699
1700 1700 then:
1701 1701
1702 1702 baz huhhahhei -> bar /tmp huhhahhei
1703 1703
1704 1704 """
1705 1705 line = fn + " " + rest
1706 1706
1707 1707 done = Set()
1708 1708 while 1:
1709 1709 pre,fn,rest = self.split_user_input(line, pattern = self.shell_line_split)
1710 1710 # print "!",fn,"!",rest # dbg
1711 1711 if fn in self.alias_table:
1712 1712 if fn in done:
1713 1713 warn("Cyclic alias definition, repeated '%s'" % fn)
1714 1714 return ""
1715 1715 done.add(fn)
1716 1716
1717 1717 l2 = self.transform_alias(fn,rest)
1718 1718 # dir -> dir
1719 1719 # print "alias",line, "->",l2 #dbg
1720 1720 if l2 == line:
1721 1721 break
1722 1722 # ls -> ls -F should not recurse forever
1723 1723 if l2.split(None,1)[0] == line.split(None,1)[0]:
1724 1724 line = l2
1725 1725 break
1726 1726
1727 1727 line=l2
1728 1728
1729 1729
1730 1730 # print "al expand to",line #dbg
1731 1731 else:
1732 1732 break
1733 1733
1734 1734 return line
1735 1735
1736 1736 def transform_alias(self, alias,rest=''):
1737 1737 """ Transform alias to system command string.
1738 1738 """
1739 1739 nargs,cmd = self.alias_table[alias]
1740 1740 if ' ' in cmd and os.path.isfile(cmd):
1741 1741 cmd = '"%s"' % cmd
1742 1742
1743 1743 # Expand the %l special to be the user's input line
1744 1744 if cmd.find('%l') >= 0:
1745 1745 cmd = cmd.replace('%l',rest)
1746 1746 rest = ''
1747 1747 if nargs==0:
1748 1748 # Simple, argument-less aliases
1749 1749 cmd = '%s %s' % (cmd,rest)
1750 1750 else:
1751 1751 # Handle aliases with positional arguments
1752 1752 args = rest.split(None,nargs)
1753 1753 if len(args)< nargs:
1754 1754 error('Alias <%s> requires %s arguments, %s given.' %
1755 1755 (alias,nargs,len(args)))
1756 1756 return None
1757 1757 cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
1758 1758 # Now call the macro, evaluating in the user's namespace
1759 1759 #print 'new command: <%r>' % cmd # dbg
1760 1760 return cmd
1761 1761
1762 1762 def call_alias(self,alias,rest=''):
1763 1763 """Call an alias given its name and the rest of the line.
1764 1764
1765 1765 This is only used to provide backwards compatibility for users of
1766 1766 ipalias(), use of which is not recommended for anymore."""
1767 1767
1768 1768 # Now call the macro, evaluating in the user's namespace
1769 1769 cmd = self.transform_alias(alias, rest)
1770 1770 try:
1771 1771 self.system(cmd)
1772 1772 except:
1773 1773 self.showtraceback()
1774 1774
1775 1775 def indent_current_str(self):
1776 1776 """return the current level of indentation as a string"""
1777 1777 return self.indent_current_nsp * ' '
1778 1778
1779 1779 def autoindent_update(self,line):
1780 1780 """Keep track of the indent level."""
1781 1781
1782 1782 #debugx('line')
1783 1783 #debugx('self.indent_current_nsp')
1784 1784 if self.autoindent:
1785 1785 if line:
1786 1786 inisp = num_ini_spaces(line)
1787 1787 if inisp < self.indent_current_nsp:
1788 1788 self.indent_current_nsp = inisp
1789 1789
1790 1790 if line[-1] == ':':
1791 1791 self.indent_current_nsp += 4
1792 1792 elif dedent_re.match(line):
1793 1793 self.indent_current_nsp -= 4
1794 1794 else:
1795 1795 self.indent_current_nsp = 0
1796 1796
1797 1797 def runlines(self,lines):
1798 1798 """Run a string of one or more lines of source.
1799 1799
1800 1800 This method is capable of running a string containing multiple source
1801 1801 lines, as if they had been entered at the IPython prompt. Since it
1802 1802 exposes IPython's processing machinery, the given strings can contain
1803 1803 magic calls (%magic), special shell access (!cmd), etc."""
1804 1804
1805 1805 # We must start with a clean buffer, in case this is run from an
1806 1806 # interactive IPython session (via a magic, for example).
1807 1807 self.resetbuffer()
1808 1808 lines = lines.split('\n')
1809 1809 more = 0
1810 1810 for line in lines:
1811 1811 # skip blank lines so we don't mess up the prompt counter, but do
1812 1812 # NOT skip even a blank line if we are in a code block (more is
1813 1813 # true)
1814 1814 if line or more:
1815 1815 more = self.push(self.prefilter(line,more))
1816 1816 # IPython's runsource returns None if there was an error
1817 1817 # compiling the code. This allows us to stop processing right
1818 1818 # away, so the user gets the error message at the right place.
1819 1819 if more is None:
1820 1820 break
1821 1821 # final newline in case the input didn't have it, so that the code
1822 1822 # actually does get executed
1823 1823 if more:
1824 1824 self.push('\n')
1825 1825
1826 1826 def runsource(self, source, filename='<input>', symbol='single'):
1827 1827 """Compile and run some source in the interpreter.
1828 1828
1829 1829 Arguments are as for compile_command().
1830 1830
1831 1831 One several things can happen:
1832 1832
1833 1833 1) The input is incorrect; compile_command() raised an
1834 1834 exception (SyntaxError or OverflowError). A syntax traceback
1835 1835 will be printed by calling the showsyntaxerror() method.
1836 1836
1837 1837 2) The input is incomplete, and more input is required;
1838 1838 compile_command() returned None. Nothing happens.
1839 1839
1840 1840 3) The input is complete; compile_command() returned a code
1841 1841 object. The code is executed by calling self.runcode() (which
1842 1842 also handles run-time exceptions, except for SystemExit).
1843 1843
1844 1844 The return value is:
1845 1845
1846 1846 - True in case 2
1847 1847
1848 1848 - False in the other cases, unless an exception is raised, where
1849 1849 None is returned instead. This can be used by external callers to
1850 1850 know whether to continue feeding input or not.
1851 1851
1852 1852 The return value can be used to decide whether to use sys.ps1 or
1853 1853 sys.ps2 to prompt the next line."""
1854 1854
1855 1855 # if the source code has leading blanks, add 'if 1:\n' to it
1856 1856 # this allows execution of indented pasted code. It is tempting
1857 1857 # to add '\n' at the end of source to run commands like ' a=1'
1858 1858 # directly, but this fails for more complicated scenarios
1859 1859 if source[:1] in [' ', '\t']:
1860 1860 source = 'if 1:\n%s' % source
1861 1861
1862 1862 try:
1863 1863 code = self.compile(source,filename,symbol)
1864 1864 except (OverflowError, SyntaxError, ValueError):
1865 1865 # Case 1
1866 1866 self.showsyntaxerror(filename)
1867 1867 return None
1868 1868
1869 1869 if code is None:
1870 1870 # Case 2
1871 1871 return True
1872 1872
1873 1873 # Case 3
1874 1874 # We store the code object so that threaded shells and
1875 1875 # custom exception handlers can access all this info if needed.
1876 1876 # The source corresponding to this can be obtained from the
1877 1877 # buffer attribute as '\n'.join(self.buffer).
1878 1878 self.code_to_run = code
1879 1879 # now actually execute the code object
1880 1880 if self.runcode(code) == 0:
1881 1881 return False
1882 1882 else:
1883 1883 return None
1884 1884
1885 1885 def runcode(self,code_obj):
1886 1886 """Execute a code object.
1887 1887
1888 1888 When an exception occurs, self.showtraceback() is called to display a
1889 1889 traceback.
1890 1890
1891 1891 Return value: a flag indicating whether the code to be run completed
1892 1892 successfully:
1893 1893
1894 1894 - 0: successful execution.
1895 1895 - 1: an error occurred.
1896 1896 """
1897 1897
1898 1898 # Set our own excepthook in case the user code tries to call it
1899 1899 # directly, so that the IPython crash handler doesn't get triggered
1900 1900 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
1901 1901
1902 1902 # we save the original sys.excepthook in the instance, in case config
1903 1903 # code (such as magics) needs access to it.
1904 1904 self.sys_excepthook = old_excepthook
1905 1905 outflag = 1 # happens in more places, so it's easier as default
1906 1906 try:
1907 1907 try:
1908 1908 # Embedded instances require separate global/local namespaces
1909 1909 # so they can see both the surrounding (local) namespace and
1910 1910 # the module-level globals when called inside another function.
1911 1911 if self.embedded:
1912 1912 exec code_obj in self.user_global_ns, self.user_ns
1913 1913 # Normal (non-embedded) instances should only have a single
1914 1914 # namespace for user code execution, otherwise functions won't
1915 1915 # see interactive top-level globals.
1916 1916 else:
1917 1917 exec code_obj in self.user_ns
1918 1918 finally:
1919 1919 # Reset our crash handler in place
1920 1920 sys.excepthook = old_excepthook
1921 1921 except SystemExit:
1922 1922 self.resetbuffer()
1923 1923 self.showtraceback()
1924 1924 warn("Type %exit or %quit to exit IPython "
1925 1925 "(%Exit or %Quit do so unconditionally).",level=1)
1926 1926 except self.custom_exceptions:
1927 1927 etype,value,tb = sys.exc_info()
1928 1928 self.CustomTB(etype,value,tb)
1929 1929 except:
1930 1930 self.showtraceback()
1931 1931 else:
1932 1932 outflag = 0
1933 1933 if softspace(sys.stdout, 0):
1934 1934 print
1935 1935 # Flush out code object which has been run (and source)
1936 1936 self.code_to_run = None
1937 1937 return outflag
1938 1938
1939 1939 def push(self, line):
1940 1940 """Push a line to the interpreter.
1941 1941
1942 1942 The line should not have a trailing newline; it may have
1943 1943 internal newlines. The line is appended to a buffer and the
1944 1944 interpreter's runsource() method is called with the
1945 1945 concatenated contents of the buffer as source. If this
1946 1946 indicates that the command was executed or invalid, the buffer
1947 1947 is reset; otherwise, the command is incomplete, and the buffer
1948 1948 is left as it was after the line was appended. The return
1949 1949 value is 1 if more input is required, 0 if the line was dealt
1950 1950 with in some way (this is the same as runsource()).
1951 1951 """
1952 1952
1953 1953 # autoindent management should be done here, and not in the
1954 1954 # interactive loop, since that one is only seen by keyboard input. We
1955 1955 # need this done correctly even for code run via runlines (which uses
1956 1956 # push).
1957 1957
1958 1958 #print 'push line: <%s>' % line # dbg
1959 1959 for subline in line.splitlines():
1960 1960 self.autoindent_update(subline)
1961 1961 self.buffer.append(line)
1962 1962 more = self.runsource('\n'.join(self.buffer), self.filename)
1963 1963 if not more:
1964 1964 self.resetbuffer()
1965 1965 return more
1966 1966
1967 1967 def resetbuffer(self):
1968 1968 """Reset the input buffer."""
1969 1969 self.buffer[:] = []
1970 1970
1971 1971 def raw_input(self,prompt='',continue_prompt=False):
1972 1972 """Write a prompt and read a line.
1973 1973
1974 1974 The returned line does not include the trailing newline.
1975 1975 When the user enters the EOF key sequence, EOFError is raised.
1976 1976
1977 1977 Optional inputs:
1978 1978
1979 1979 - prompt(''): a string to be printed to prompt the user.
1980 1980
1981 1981 - continue_prompt(False): whether this line is the first one or a
1982 1982 continuation in a sequence of inputs.
1983 1983 """
1984 1984
1985 1985 try:
1986 1986 line = raw_input_original(prompt).decode(sys.stdin.encoding)
1987 #line = raw_input_original(prompt)
1987 1988 except ValueError:
1988 1989 warn("\n********\nYou or a %run:ed script called sys.stdin.close() or sys.stdout.close()!\nExiting IPython!")
1989 1990 self.exit_now = True
1990 1991 return ""
1991 1992
1992 1993
1993 1994 # Try to be reasonably smart about not re-indenting pasted input more
1994 1995 # than necessary. We do this by trimming out the auto-indent initial
1995 1996 # spaces, if the user's actual input started itself with whitespace.
1996 1997 #debugx('self.buffer[-1]')
1997 1998
1998 1999 if self.autoindent:
1999 2000 if num_ini_spaces(line) > self.indent_current_nsp:
2000 2001 line = line[self.indent_current_nsp:]
2001 2002 self.indent_current_nsp = 0
2002 2003
2003 2004 # store the unfiltered input before the user has any chance to modify
2004 2005 # it.
2005 2006 if line.strip():
2006 2007 if continue_prompt:
2007 2008 self.input_hist_raw[-1] += '%s\n' % line
2008 2009 if self.has_readline: # and some config option is set?
2009 2010 try:
2010 2011 histlen = self.readline.get_current_history_length()
2011 2012 newhist = self.input_hist_raw[-1].rstrip()
2012 2013 self.readline.remove_history_item(histlen-1)
2013 2014 self.readline.replace_history_item(histlen-2,newhist)
2014 2015 except AttributeError:
2015 2016 pass # re{move,place}_history_item are new in 2.4.
2016 2017 else:
2017 2018 self.input_hist_raw.append('%s\n' % line)
2018 2019
2019 2020 try:
2020 2021 lineout = self.prefilter(line,continue_prompt)
2021 2022 except:
2022 2023 # blanket except, in case a user-defined prefilter crashes, so it
2023 2024 # can't take all of ipython with it.
2024 2025 self.showtraceback()
2025 2026 return ''
2026 2027 else:
2027 2028 return lineout
2028 2029
2029 2030 def split_user_input(self,line, pattern = None):
2030 2031 """Split user input into pre-char, function part and rest."""
2031 2032
2032 2033 if pattern is None:
2033 2034 pattern = self.line_split
2034 2035
2035 2036 lsplit = pattern.match(line)
2036 2037 if lsplit is None: # no regexp match returns None
2037 2038 #print "match failed for line '%s'" % line # dbg
2038 2039 try:
2039 2040 iFun,theRest = line.split(None,1)
2040 2041 except ValueError:
2041 2042 #print "split failed for line '%s'" % line # dbg
2042 2043 iFun,theRest = line,''
2043 2044 pre = re.match('^(\s*)(.*)',line).groups()[0]
2044 2045 else:
2045 2046 pre,iFun,theRest = lsplit.groups()
2046 2047
2047 2048 #print 'line:<%s>' % line # dbg
2048 2049 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun.strip(),theRest) # dbg
2049 2050 return pre,iFun.strip(),theRest
2050 2051
2051 2052 # THIS VERSION IS BROKEN!!! It was intended to prevent spurious attribute
2052 2053 # accesses with a more stringent check of inputs, but it introduced other
2053 2054 # bugs. Disable it for now until I can properly fix it.
2054 2055 def split_user_inputBROKEN(self,line):
2055 2056 """Split user input into pre-char, function part and rest."""
2056 2057
2057 2058 lsplit = self.line_split.match(line)
2058 2059 if lsplit is None: # no regexp match returns None
2059 2060 lsplit = self.line_split_fallback.match(line)
2060 2061
2061 2062 #pre,iFun,theRest = lsplit.groups() # dbg
2062 2063 #print 'line:<%s>' % line # dbg
2063 2064 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun.strip(),theRest) # dbg
2064 2065 #return pre,iFun.strip(),theRest # dbg
2065 2066
2066 2067 return lsplit.groups()
2067 2068
2068 2069 def _prefilter(self, line, continue_prompt):
2069 2070 """Calls different preprocessors, depending on the form of line."""
2070 2071
2071 2072 # All handlers *must* return a value, even if it's blank ('').
2072 2073
2073 2074 # Lines are NOT logged here. Handlers should process the line as
2074 2075 # needed, update the cache AND log it (so that the input cache array
2075 2076 # stays synced).
2076 2077
2077 2078 # This function is _very_ delicate, and since it's also the one which
2078 2079 # determines IPython's response to user input, it must be as efficient
2079 2080 # as possible. For this reason it has _many_ returns in it, trying
2080 2081 # always to exit as quickly as it can figure out what it needs to do.
2081 2082
2082 2083 # This function is the main responsible for maintaining IPython's
2083 2084 # behavior respectful of Python's semantics. So be _very_ careful if
2084 2085 # making changes to anything here.
2085 2086
2086 2087 #.....................................................................
2087 2088 # Code begins
2088 2089
2089 2090 #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg
2090 2091
2091 2092 # save the line away in case we crash, so the post-mortem handler can
2092 2093 # record it
2093 2094 self._last_input_line = line
2094 2095
2095 2096 #print '***line: <%s>' % line # dbg
2096 2097
2097 2098 # the input history needs to track even empty lines
2098 2099 stripped = line.strip()
2099 2100
2100 2101 if not stripped:
2101 2102 if not continue_prompt:
2102 2103 self.outputcache.prompt_count -= 1
2103 2104 return self.handle_normal(line,continue_prompt)
2104 2105 #return self.handle_normal('',continue_prompt)
2105 2106
2106 2107 # print '***cont',continue_prompt # dbg
2107 2108 # special handlers are only allowed for single line statements
2108 2109 if continue_prompt and not self.rc.multi_line_specials:
2109 2110 return self.handle_normal(line,continue_prompt)
2110 2111
2111 2112
2112 2113 # For the rest, we need the structure of the input
2113 2114 pre,iFun,theRest = self.split_user_input(line)
2114 2115
2115 2116 # See whether any pre-existing handler can take care of it
2116 2117
2117 2118 rewritten = self.hooks.input_prefilter(stripped)
2118 2119 if rewritten != stripped: # ok, some prefilter did something
2119 2120 rewritten = pre + rewritten # add indentation
2120 2121 return self.handle_normal(rewritten)
2121 2122
2122 2123 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
2123 2124
2124 2125 # Next, check if we can automatically execute this thing
2125 2126
2126 2127 # Allow ! in multi-line statements if multi_line_specials is on:
2127 2128 if continue_prompt and self.rc.multi_line_specials and \
2128 2129 iFun.startswith(self.ESC_SHELL):
2129 2130 return self.handle_shell_escape(line,continue_prompt,
2130 2131 pre=pre,iFun=iFun,
2131 2132 theRest=theRest)
2132 2133
2133 2134 # First check for explicit escapes in the last/first character
2134 2135 handler = None
2135 2136 if line[-1] == self.ESC_HELP:
2136 2137 handler = self.esc_handlers.get(line[-1]) # the ? can be at the end
2137 2138 if handler is None:
2138 2139 # look at the first character of iFun, NOT of line, so we skip
2139 2140 # leading whitespace in multiline input
2140 2141 handler = self.esc_handlers.get(iFun[0:1])
2141 2142 if handler is not None:
2142 2143 return handler(line,continue_prompt,pre,iFun,theRest)
2143 2144 # Emacs ipython-mode tags certain input lines
2144 2145 if line.endswith('# PYTHON-MODE'):
2145 2146 return self.handle_emacs(line,continue_prompt)
2146 2147
2147 2148 # Let's try to find if the input line is a magic fn
2148 2149 oinfo = None
2149 2150 if hasattr(self,'magic_'+iFun):
2150 2151 # WARNING: _ofind uses getattr(), so it can consume generators and
2151 2152 # cause other side effects.
2152 2153 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
2153 2154 if oinfo['ismagic']:
2154 2155 # Be careful not to call magics when a variable assignment is
2155 2156 # being made (ls='hi', for example)
2156 2157 if self.rc.automagic and \
2157 2158 (len(theRest)==0 or theRest[0] not in '!=()<>,') and \
2158 2159 (self.rc.multi_line_specials or not continue_prompt):
2159 2160 return self.handle_magic(line,continue_prompt,
2160 2161 pre,iFun,theRest)
2161 2162 else:
2162 2163 return self.handle_normal(line,continue_prompt)
2163 2164
2164 2165 # If the rest of the line begins with an (in)equality, assginment or
2165 2166 # function call, we should not call _ofind but simply execute it.
2166 2167 # This avoids spurious geattr() accesses on objects upon assignment.
2167 2168 #
2168 2169 # It also allows users to assign to either alias or magic names true
2169 2170 # python variables (the magic/alias systems always take second seat to
2170 2171 # true python code).
2171 2172 if theRest and theRest[0] in '!=()':
2172 2173 return self.handle_normal(line,continue_prompt)
2173 2174
2174 2175 if oinfo is None:
2175 2176 # let's try to ensure that _oinfo is ONLY called when autocall is
2176 2177 # on. Since it has inevitable potential side effects, at least
2177 2178 # having autocall off should be a guarantee to the user that no
2178 2179 # weird things will happen.
2179 2180
2180 2181 if self.rc.autocall:
2181 2182 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
2182 2183 else:
2183 2184 # in this case, all that's left is either an alias or
2184 2185 # processing the line normally.
2185 2186 if iFun in self.alias_table:
2186 2187 # if autocall is off, by not running _ofind we won't know
2187 2188 # whether the given name may also exist in one of the
2188 2189 # user's namespace. At this point, it's best to do a
2189 2190 # quick check just to be sure that we don't let aliases
2190 2191 # shadow variables.
2191 2192 head = iFun.split('.',1)[0]
2192 2193 if head in self.user_ns or head in self.internal_ns \
2193 2194 or head in __builtin__.__dict__:
2194 2195 return self.handle_normal(line,continue_prompt)
2195 2196 else:
2196 2197 return self.handle_alias(line,continue_prompt,
2197 2198 pre,iFun,theRest)
2198 2199
2199 2200 else:
2200 2201 return self.handle_normal(line,continue_prompt)
2201 2202
2202 2203 if not oinfo['found']:
2203 2204 return self.handle_normal(line,continue_prompt)
2204 2205 else:
2205 2206 #print 'pre<%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
2206 2207 if oinfo['isalias']:
2207 2208 return self.handle_alias(line,continue_prompt,
2208 2209 pre,iFun,theRest)
2209 2210
2210 2211 if (self.rc.autocall
2211 2212 and
2212 2213 (
2213 2214 #only consider exclusion re if not "," or ";" autoquoting
2214 2215 (pre == self.ESC_QUOTE or pre == self.ESC_QUOTE2
2215 2216 or pre == self.ESC_PAREN) or
2216 2217 (not self.re_exclude_auto.match(theRest)))
2217 2218 and
2218 2219 self.re_fun_name.match(iFun) and
2219 2220 callable(oinfo['obj'])) :
2220 2221 #print 'going auto' # dbg
2221 2222 return self.handle_auto(line,continue_prompt,
2222 2223 pre,iFun,theRest,oinfo['obj'])
2223 2224 else:
2224 2225 #print 'was callable?', callable(oinfo['obj']) # dbg
2225 2226 return self.handle_normal(line,continue_prompt)
2226 2227
2227 2228 # If we get here, we have a normal Python line. Log and return.
2228 2229 return self.handle_normal(line,continue_prompt)
2229 2230
2230 2231 def _prefilter_dumb(self, line, continue_prompt):
2231 2232 """simple prefilter function, for debugging"""
2232 2233 return self.handle_normal(line,continue_prompt)
2233 2234
2234 2235
2235 2236 def multiline_prefilter(self, line, continue_prompt):
2236 2237 """ Run _prefilter for each line of input
2237 2238
2238 2239 Covers cases where there are multiple lines in the user entry,
2239 2240 which is the case when the user goes back to a multiline history
2240 2241 entry and presses enter.
2241 2242
2242 2243 """
2243 2244 out = []
2244 2245 for l in line.rstrip('\n').split('\n'):
2245 2246 out.append(self._prefilter(l, continue_prompt))
2246 2247 return '\n'.join(out)
2247 2248
2248 2249 # Set the default prefilter() function (this can be user-overridden)
2249 2250 prefilter = multiline_prefilter
2250 2251
2251 2252 def handle_normal(self,line,continue_prompt=None,
2252 2253 pre=None,iFun=None,theRest=None):
2253 2254 """Handle normal input lines. Use as a template for handlers."""
2254 2255
2255 2256 # With autoindent on, we need some way to exit the input loop, and I
2256 2257 # don't want to force the user to have to backspace all the way to
2257 2258 # clear the line. The rule will be in this case, that either two
2258 2259 # lines of pure whitespace in a row, or a line of pure whitespace but
2259 2260 # of a size different to the indent level, will exit the input loop.
2260 2261
2261 2262 if (continue_prompt and self.autoindent and line.isspace() and
2262 2263 (0 < abs(len(line) - self.indent_current_nsp) <= 2 or
2263 2264 (self.buffer[-1]).isspace() )):
2264 2265 line = ''
2265 2266
2266 2267 self.log(line,line,continue_prompt)
2267 2268 return line
2268 2269
2269 2270 def handle_alias(self,line,continue_prompt=None,
2270 2271 pre=None,iFun=None,theRest=None):
2271 2272 """Handle alias input lines. """
2272 2273
2273 2274 # pre is needed, because it carries the leading whitespace. Otherwise
2274 2275 # aliases won't work in indented sections.
2275 2276 transformed = self.expand_aliases(iFun, theRest)
2276 2277 line_out = '%s_ip.system(%s)' % (pre, make_quoted_expr( transformed ))
2277 2278 self.log(line,line_out,continue_prompt)
2278 2279 #print 'line out:',line_out # dbg
2279 2280 return line_out
2280 2281
2281 2282 def handle_shell_escape(self, line, continue_prompt=None,
2282 2283 pre=None,iFun=None,theRest=None):
2283 2284 """Execute the line in a shell, empty return value"""
2284 2285
2285 2286 #print 'line in :', `line` # dbg
2286 2287 # Example of a special handler. Others follow a similar pattern.
2287 2288 if line.lstrip().startswith('!!'):
2288 2289 # rewrite iFun/theRest to properly hold the call to %sx and
2289 2290 # the actual command to be executed, so handle_magic can work
2290 2291 # correctly
2291 2292 theRest = '%s %s' % (iFun[2:],theRest)
2292 2293 iFun = 'sx'
2293 2294 return self.handle_magic('%ssx %s' % (self.ESC_MAGIC,
2294 2295 line.lstrip()[2:]),
2295 2296 continue_prompt,pre,iFun,theRest)
2296 2297 else:
2297 2298 cmd=line.lstrip().lstrip('!')
2298 2299 line_out = '%s_ip.system(%s)' % (pre,make_quoted_expr(cmd))
2299 2300 # update cache/log and return
2300 2301 self.log(line,line_out,continue_prompt)
2301 2302 return line_out
2302 2303
2303 2304 def handle_magic(self, line, continue_prompt=None,
2304 2305 pre=None,iFun=None,theRest=None):
2305 2306 """Execute magic functions."""
2306 2307
2307 2308
2308 2309 cmd = '%s_ip.magic(%s)' % (pre,make_quoted_expr(iFun + " " + theRest))
2309 2310 self.log(line,cmd,continue_prompt)
2310 2311 #print 'in handle_magic, cmd=<%s>' % cmd # dbg
2311 2312 return cmd
2312 2313
2313 2314 def handle_auto(self, line, continue_prompt=None,
2314 2315 pre=None,iFun=None,theRest=None,obj=None):
2315 2316 """Hande lines which can be auto-executed, quoting if requested."""
2316 2317
2317 2318 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
2318 2319
2319 2320 # This should only be active for single-line input!
2320 2321 if continue_prompt:
2321 2322 self.log(line,line,continue_prompt)
2322 2323 return line
2323 2324
2324 2325 auto_rewrite = True
2325 2326
2326 2327 if pre == self.ESC_QUOTE:
2327 2328 # Auto-quote splitting on whitespace
2328 2329 newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) )
2329 2330 elif pre == self.ESC_QUOTE2:
2330 2331 # Auto-quote whole string
2331 2332 newcmd = '%s("%s")' % (iFun,theRest)
2332 2333 elif pre == self.ESC_PAREN:
2333 2334 newcmd = '%s(%s)' % (iFun,",".join(theRest.split()))
2334 2335 else:
2335 2336 # Auto-paren.
2336 2337 # We only apply it to argument-less calls if the autocall
2337 2338 # parameter is set to 2. We only need to check that autocall is <
2338 2339 # 2, since this function isn't called unless it's at least 1.
2339 2340 if not theRest and (self.rc.autocall < 2):
2340 2341 newcmd = '%s %s' % (iFun,theRest)
2341 2342 auto_rewrite = False
2342 2343 else:
2343 2344 if theRest.startswith('['):
2344 2345 if hasattr(obj,'__getitem__'):
2345 2346 # Don't autocall in this case: item access for an object
2346 2347 # which is BOTH callable and implements __getitem__.
2347 2348 newcmd = '%s %s' % (iFun,theRest)
2348 2349 auto_rewrite = False
2349 2350 else:
2350 2351 # if the object doesn't support [] access, go ahead and
2351 2352 # autocall
2352 2353 newcmd = '%s(%s)' % (iFun.rstrip(),theRest)
2353 2354 elif theRest.endswith(';'):
2354 2355 newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1])
2355 2356 else:
2356 2357 newcmd = '%s(%s)' % (iFun.rstrip(), theRest)
2357 2358
2358 2359 if auto_rewrite:
2359 2360 print >>Term.cout, self.outputcache.prompt1.auto_rewrite() + newcmd
2360 2361 # log what is now valid Python, not the actual user input (without the
2361 2362 # final newline)
2362 2363 self.log(line,newcmd,continue_prompt)
2363 2364 return newcmd
2364 2365
2365 2366 def handle_help(self, line, continue_prompt=None,
2366 2367 pre=None,iFun=None,theRest=None):
2367 2368 """Try to get some help for the object.
2368 2369
2369 2370 obj? or ?obj -> basic information.
2370 2371 obj?? or ??obj -> more details.
2371 2372 """
2372 2373
2373 2374 # We need to make sure that we don't process lines which would be
2374 2375 # otherwise valid python, such as "x=1 # what?"
2375 2376 try:
2376 2377 codeop.compile_command(line)
2377 2378 except SyntaxError:
2378 2379 # We should only handle as help stuff which is NOT valid syntax
2379 2380 if line[0]==self.ESC_HELP:
2380 2381 line = line[1:]
2381 2382 elif line[-1]==self.ESC_HELP:
2382 2383 line = line[:-1]
2383 2384 self.log(line,'#?'+line,continue_prompt)
2384 2385 if line:
2385 2386 #print 'line:<%r>' % line # dbg
2386 2387 self.magic_pinfo(line)
2387 2388 else:
2388 2389 page(self.usage,screen_lines=self.rc.screen_length)
2389 2390 return '' # Empty string is needed here!
2390 2391 except:
2391 2392 # Pass any other exceptions through to the normal handler
2392 2393 return self.handle_normal(line,continue_prompt)
2393 2394 else:
2394 2395 # If the code compiles ok, we should handle it normally
2395 2396 return self.handle_normal(line,continue_prompt)
2396 2397
2397 2398 def getapi(self):
2398 2399 """ Get an IPApi object for this shell instance
2399 2400
2400 2401 Getting an IPApi object is always preferable to accessing the shell
2401 2402 directly, but this holds true especially for extensions.
2402 2403
2403 2404 It should always be possible to implement an extension with IPApi
2404 2405 alone. If not, contact maintainer to request an addition.
2405 2406
2406 2407 """
2407 2408 return self.api
2408 2409
2409 2410 def handle_emacs(self,line,continue_prompt=None,
2410 2411 pre=None,iFun=None,theRest=None):
2411 2412 """Handle input lines marked by python-mode."""
2412 2413
2413 2414 # Currently, nothing is done. Later more functionality can be added
2414 2415 # here if needed.
2415 2416
2416 2417 # The input cache shouldn't be updated
2417 2418
2418 2419 return line
2419 2420
2420 2421 def mktempfile(self,data=None):
2421 2422 """Make a new tempfile and return its filename.
2422 2423
2423 2424 This makes a call to tempfile.mktemp, but it registers the created
2424 2425 filename internally so ipython cleans it up at exit time.
2425 2426
2426 2427 Optional inputs:
2427 2428
2428 2429 - data(None): if data is given, it gets written out to the temp file
2429 2430 immediately, and the file is closed again."""
2430 2431
2431 2432 filename = tempfile.mktemp('.py','ipython_edit_')
2432 2433 self.tempfiles.append(filename)
2433 2434
2434 2435 if data:
2435 2436 tmp_file = open(filename,'w')
2436 2437 tmp_file.write(data)
2437 2438 tmp_file.close()
2438 2439 return filename
2439 2440
2440 2441 def write(self,data):
2441 2442 """Write a string to the default output"""
2442 2443 Term.cout.write(data)
2443 2444
2444 2445 def write_err(self,data):
2445 2446 """Write a string to the default error output"""
2446 2447 Term.cerr.write(data)
2447 2448
2448 2449 def exit(self):
2449 2450 """Handle interactive exit.
2450 2451
2451 2452 This method sets the exit_now attribute."""
2452 2453
2453 2454 if self.rc.confirm_exit:
2454 2455 if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'):
2455 2456 self.exit_now = True
2456 2457 else:
2457 2458 self.exit_now = True
2458 2459
2459 2460 def safe_execfile(self,fname,*where,**kw):
2460 2461 """A safe version of the builtin execfile().
2461 2462
2462 2463 This version will never throw an exception, and knows how to handle
2463 2464 ipython logs as well."""
2464 2465
2465 2466 def syspath_cleanup():
2466 2467 """Internal cleanup routine for sys.path."""
2467 2468 if add_dname:
2468 2469 try:
2469 2470 sys.path.remove(dname)
2470 2471 except ValueError:
2471 2472 # For some reason the user has already removed it, ignore.
2472 2473 pass
2473 2474
2474 2475 fname = os.path.expanduser(fname)
2475 2476
2476 2477 # Find things also in current directory. This is needed to mimic the
2477 2478 # behavior of running a script from the system command line, where
2478 2479 # Python inserts the script's directory into sys.path
2479 2480 dname = os.path.dirname(os.path.abspath(fname))
2480 2481 add_dname = False
2481 2482 if dname not in sys.path:
2482 2483 sys.path.insert(0,dname)
2483 2484 add_dname = True
2484 2485
2485 2486 try:
2486 2487 xfile = open(fname)
2487 2488 except:
2488 2489 print >> Term.cerr, \
2489 2490 'Could not open file <%s> for safe execution.' % fname
2490 2491 syspath_cleanup()
2491 2492 return None
2492 2493
2493 2494 kw.setdefault('islog',0)
2494 2495 kw.setdefault('quiet',1)
2495 2496 kw.setdefault('exit_ignore',0)
2496 2497 first = xfile.readline()
2497 2498 loghead = str(self.loghead_tpl).split('\n',1)[0].strip()
2498 2499 xfile.close()
2499 2500 # line by line execution
2500 2501 if first.startswith(loghead) or kw['islog']:
2501 2502 print 'Loading log file <%s> one line at a time...' % fname
2502 2503 if kw['quiet']:
2503 2504 stdout_save = sys.stdout
2504 2505 sys.stdout = StringIO.StringIO()
2505 2506 try:
2506 2507 globs,locs = where[0:2]
2507 2508 except:
2508 2509 try:
2509 2510 globs = locs = where[0]
2510 2511 except:
2511 2512 globs = locs = globals()
2512 2513 badblocks = []
2513 2514
2514 2515 # we also need to identify indented blocks of code when replaying
2515 2516 # logs and put them together before passing them to an exec
2516 2517 # statement. This takes a bit of regexp and look-ahead work in the
2517 2518 # file. It's easiest if we swallow the whole thing in memory
2518 2519 # first, and manually walk through the lines list moving the
2519 2520 # counter ourselves.
2520 2521 indent_re = re.compile('\s+\S')
2521 2522 xfile = open(fname)
2522 2523 filelines = xfile.readlines()
2523 2524 xfile.close()
2524 2525 nlines = len(filelines)
2525 2526 lnum = 0
2526 2527 while lnum < nlines:
2527 2528 line = filelines[lnum]
2528 2529 lnum += 1
2529 2530 # don't re-insert logger status info into cache
2530 2531 if line.startswith('#log#'):
2531 2532 continue
2532 2533 else:
2533 2534 # build a block of code (maybe a single line) for execution
2534 2535 block = line
2535 2536 try:
2536 2537 next = filelines[lnum] # lnum has already incremented
2537 2538 except:
2538 2539 next = None
2539 2540 while next and indent_re.match(next):
2540 2541 block += next
2541 2542 lnum += 1
2542 2543 try:
2543 2544 next = filelines[lnum]
2544 2545 except:
2545 2546 next = None
2546 2547 # now execute the block of one or more lines
2547 2548 try:
2548 2549 exec block in globs,locs
2549 2550 except SystemExit:
2550 2551 pass
2551 2552 except:
2552 2553 badblocks.append(block.rstrip())
2553 2554 if kw['quiet']: # restore stdout
2554 2555 sys.stdout.close()
2555 2556 sys.stdout = stdout_save
2556 2557 print 'Finished replaying log file <%s>' % fname
2557 2558 if badblocks:
2558 2559 print >> sys.stderr, ('\nThe following lines/blocks in file '
2559 2560 '<%s> reported errors:' % fname)
2560 2561
2561 2562 for badline in badblocks:
2562 2563 print >> sys.stderr, badline
2563 2564 else: # regular file execution
2564 2565 try:
2565 2566 execfile(fname,*where)
2566 2567 except SyntaxError:
2567 2568 self.showsyntaxerror()
2568 2569 warn('Failure executing file: <%s>' % fname)
2569 2570 except SystemExit,status:
2570 2571 if not kw['exit_ignore']:
2571 2572 self.showtraceback()
2572 2573 warn('Failure executing file: <%s>' % fname)
2573 2574 except:
2574 2575 self.showtraceback()
2575 2576 warn('Failure executing file: <%s>' % fname)
2576 2577
2577 2578 syspath_cleanup()
2578 2579
2579 2580 #************************* end of file <iplib.py> *****************************
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
General Comments 0
You need to be logged in to leave comments. Login now