##// END OF EJS Templates
- Add autocall 'smart' mode....
fperez -
Show More

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

@@ -1,2706 +1,2707 b''
1 1 # -*- coding: utf-8 -*-
2 2 """Magic functions for InteractiveShell.
3 3
4 $Id: Magic.py 988 2006-01-02 21:21:47Z fperez $"""
4 $Id: Magic.py 990 2006-01-04 06:59:02Z fperez $"""
5 5
6 6 #*****************************************************************************
7 7 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
8 8 # Copyright (C) 2001-2004 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 from cStringIO import StringIO
35 35 from getopt import getopt
36 36 from pprint import pprint, pformat
37 37
38 38 # profile isn't bundled by default in Debian for license reasons
39 39 try:
40 40 import profile,pstats
41 41 except ImportError:
42 42 profile = pstats = None
43 43
44 44 # Homebrewed
45 45 from IPython import Debugger, OInspect, wildcard
46 46 from IPython.FakeModule import FakeModule
47 47 from IPython.Itpl import Itpl, itpl, printpl,itplns
48 48 from IPython.PyColorize import Parser
49 49 from IPython.Struct import Struct
50 50 from IPython.macro import Macro
51 51 from IPython.genutils import *
52 52
53 53 #***************************************************************************
54 54 # Utility functions
55 55 def on_off(tag):
56 56 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
57 57 return ['OFF','ON'][tag]
58 58
59 59
60 60 #***************************************************************************
61 61 # Main class implementing Magic functionality
62 62 class Magic:
63 63 """Magic functions for InteractiveShell.
64 64
65 65 Shell functions which can be reached as %function_name. All magic
66 66 functions should accept a string, which they can parse for their own
67 67 needs. This can make some functions easier to type, eg `%cd ../`
68 68 vs. `%cd("../")`
69 69
70 70 ALL definitions MUST begin with the prefix magic_. The user won't need it
71 71 at the command line, but it is is needed in the definition. """
72 72
73 73 # class globals
74 74 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
75 75 'Automagic is ON, % prefix NOT needed for magic functions.']
76 76
77 77 #......................................................................
78 78 # some utility functions
79 79
80 80 def __init__(self,shell):
81 81
82 82 self.options_table = {}
83 83 if profile is None:
84 84 self.magic_prun = self.profile_missing_notice
85 85 self.shell = shell
86 86
87 87 def profile_missing_notice(self, *args, **kwargs):
88 88 error("""\
89 89 The profile module could not be found. If you are a Debian user,
90 90 it has been removed from the standard Debian package because of its non-free
91 91 license. To use profiling, please install"python2.3-profiler" from non-free.""")
92 92
93 93 def default_option(self,fn,optstr):
94 94 """Make an entry in the options_table for fn, with value optstr"""
95 95
96 96 if fn not in self.lsmagic():
97 97 error("%s is not a magic function" % fn)
98 98 self.options_table[fn] = optstr
99 99
100 100 def lsmagic(self):
101 101 """Return a list of currently available magic functions.
102 102
103 103 Gives a list of the bare names after mangling (['ls','cd', ...], not
104 104 ['magic_ls','magic_cd',...]"""
105 105
106 106 # FIXME. This needs a cleanup, in the way the magics list is built.
107 107
108 108 # magics in class definition
109 109 class_magic = lambda fn: fn.startswith('magic_') and \
110 110 callable(Magic.__dict__[fn])
111 111 # in instance namespace (run-time user additions)
112 112 inst_magic = lambda fn: fn.startswith('magic_') and \
113 113 callable(self.__dict__[fn])
114 114 # and bound magics by user (so they can access self):
115 115 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
116 116 callable(self.__class__.__dict__[fn])
117 117 magics = filter(class_magic,Magic.__dict__.keys()) + \
118 118 filter(inst_magic,self.__dict__.keys()) + \
119 119 filter(inst_bound_magic,self.__class__.__dict__.keys())
120 120 out = []
121 121 for fn in magics:
122 122 out.append(fn.replace('magic_','',1))
123 123 out.sort()
124 124 return out
125 125
126 126 def extract_input_slices(self,slices):
127 127 """Return as a string a set of input history slices.
128 128
129 129 The set of slices is given as a list of strings (like ['1','4:8','9'],
130 130 since this function is for use by magic functions which get their
131 131 arguments as strings.
132 132
133 133 Note that slices can be called with two notations:
134 134
135 135 N:M -> standard python form, means including items N...(M-1).
136 136
137 137 N-M -> include items N..M (closed endpoint)."""
138 138
139 139 cmds = []
140 140 for chunk in slices:
141 141 if ':' in chunk:
142 142 ini,fin = map(int,chunk.split(':'))
143 143 elif '-' in chunk:
144 144 ini,fin = map(int,chunk.split('-'))
145 145 fin += 1
146 146 else:
147 147 ini = int(chunk)
148 148 fin = ini+1
149 149 cmds.append(self.shell.input_hist[ini:fin])
150 150 return cmds
151 151
152 152 def _ofind(self,oname):
153 153 """Find an object in the available namespaces.
154 154
155 155 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
156 156
157 157 Has special code to detect magic functions.
158 158 """
159 159
160 160 oname = oname.strip()
161 161
162 162 # Namespaces to search in:
163 163 user_ns = self.shell.user_ns
164 164 internal_ns = self.shell.internal_ns
165 165 builtin_ns = __builtin__.__dict__
166 166 alias_ns = self.shell.alias_table
167 167
168 168 # Put them in a list. The order is important so that we find things in
169 169 # the same order that Python finds them.
170 170 namespaces = [ ('Interactive',user_ns),
171 171 ('IPython internal',internal_ns),
172 172 ('Python builtin',builtin_ns),
173 173 ('Alias',alias_ns),
174 174 ]
175 175
176 176 # initialize results to 'null'
177 177 found = 0; obj = None; ospace = None; ds = None;
178 178 ismagic = 0; isalias = 0
179 179
180 180 # Look for the given name by splitting it in parts. If the head is
181 181 # found, then we look for all the remaining parts as members, and only
182 182 # declare success if we can find them all.
183 183 oname_parts = oname.split('.')
184 184 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
185 185 for nsname,ns in namespaces:
186 186 try:
187 187 obj = ns[oname_head]
188 188 except KeyError:
189 189 continue
190 190 else:
191 191 for part in oname_rest:
192 192 try:
193 193 obj = getattr(obj,part)
194 194 except:
195 195 # Blanket except b/c some badly implemented objects
196 196 # allow __getattr__ to raise exceptions other than
197 197 # AttributeError, which then crashes IPython.
198 198 break
199 199 else:
200 200 # If we finish the for loop (no break), we got all members
201 201 found = 1
202 202 ospace = nsname
203 203 if ns == alias_ns:
204 204 isalias = 1
205 205 break # namespace loop
206 206
207 207 # Try to see if it's magic
208 208 if not found:
209 209 if oname.startswith(self.shell.ESC_MAGIC):
210 210 oname = oname[1:]
211 211 obj = getattr(self,'magic_'+oname,None)
212 212 if obj is not None:
213 213 found = 1
214 214 ospace = 'IPython internal'
215 215 ismagic = 1
216 216
217 217 # Last try: special-case some literals like '', [], {}, etc:
218 218 if not found and oname_head in ["''",'""','[]','{}','()']:
219 219 obj = eval(oname_head)
220 220 found = 1
221 221 ospace = 'Interactive'
222 222
223 223 return {'found':found, 'obj':obj, 'namespace':ospace,
224 224 'ismagic':ismagic, 'isalias':isalias}
225 225
226 226 def arg_err(self,func):
227 227 """Print docstring if incorrect arguments were passed"""
228 228 print 'Error in arguments:'
229 229 print OInspect.getdoc(func)
230 230
231 231 def format_latex(self,strng):
232 232 """Format a string for latex inclusion."""
233 233
234 234 # Characters that need to be escaped for latex:
235 235 escape_re = re.compile(r'(%|_|\$|#)',re.MULTILINE)
236 236 # Magic command names as headers:
237 237 cmd_name_re = re.compile(r'^(%s.*?):' % self.shell.ESC_MAGIC,
238 238 re.MULTILINE)
239 239 # Magic commands
240 240 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % self.shell.ESC_MAGIC,
241 241 re.MULTILINE)
242 242 # Paragraph continue
243 243 par_re = re.compile(r'\\$',re.MULTILINE)
244 244
245 245 # The "\n" symbol
246 246 newline_re = re.compile(r'\\n')
247 247
248 248 # Now build the string for output:
249 249 strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
250 250 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
251 251 strng = par_re.sub(r'\\\\',strng)
252 252 strng = escape_re.sub(r'\\\1',strng)
253 253 strng = newline_re.sub(r'\\textbackslash{}n',strng)
254 254 return strng
255 255
256 256 def format_screen(self,strng):
257 257 """Format a string for screen printing.
258 258
259 259 This removes some latex-type format codes."""
260 260 # Paragraph continue
261 261 par_re = re.compile(r'\\$',re.MULTILINE)
262 262 strng = par_re.sub('',strng)
263 263 return strng
264 264
265 265 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
266 266 """Parse options passed to an argument string.
267 267
268 268 The interface is similar to that of getopt(), but it returns back a
269 269 Struct with the options as keys and the stripped argument string still
270 270 as a string.
271 271
272 272 arg_str is quoted as a true sys.argv vector by using shlex.split.
273 273 This allows us to easily expand variables, glob files, quote
274 274 arguments, etc.
275 275
276 276 Options:
277 277 -mode: default 'string'. If given as 'list', the argument string is
278 278 returned as a list (split on whitespace) instead of a string.
279 279
280 280 -list_all: put all option values in lists. Normally only options
281 281 appearing more than once are put in a list."""
282 282
283 283 # inject default options at the beginning of the input line
284 284 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
285 285 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
286 286
287 287 mode = kw.get('mode','string')
288 288 if mode not in ['string','list']:
289 289 raise ValueError,'incorrect mode given: %s' % mode
290 290 # Get options
291 291 list_all = kw.get('list_all',0)
292 292
293 293 # Check if we have more than one argument to warrant extra processing:
294 294 odict = {} # Dictionary with options
295 295 args = arg_str.split()
296 296 if len(args) >= 1:
297 297 # If the list of inputs only has 0 or 1 thing in it, there's no
298 298 # need to look for options
299 299 argv = shlex_split(arg_str)
300 300 # Do regular option processing
301 301 opts,args = getopt(argv,opt_str,*long_opts)
302 302 for o,a in opts:
303 303 if o.startswith('--'):
304 304 o = o[2:]
305 305 else:
306 306 o = o[1:]
307 307 try:
308 308 odict[o].append(a)
309 309 except AttributeError:
310 310 odict[o] = [odict[o],a]
311 311 except KeyError:
312 312 if list_all:
313 313 odict[o] = [a]
314 314 else:
315 315 odict[o] = a
316 316
317 317 # Prepare opts,args for return
318 318 opts = Struct(odict)
319 319 if mode == 'string':
320 320 args = ' '.join(args)
321 321
322 322 return opts,args
323 323
324 324 #......................................................................
325 325 # And now the actual magic functions
326 326
327 327 # Functions for IPython shell work (vars,funcs, config, etc)
328 328 def magic_lsmagic(self, parameter_s = ''):
329 329 """List currently available magic functions."""
330 330 mesc = self.shell.ESC_MAGIC
331 331 print 'Available magic functions:\n'+mesc+\
332 332 (' '+mesc).join(self.lsmagic())
333 333 print '\n' + Magic.auto_status[self.shell.rc.automagic]
334 334 return None
335 335
336 336 def magic_magic(self, parameter_s = ''):
337 337 """Print information about the magic function system."""
338 338
339 339 mode = ''
340 340 try:
341 341 if parameter_s.split()[0] == '-latex':
342 342 mode = 'latex'
343 343 except:
344 344 pass
345 345
346 346 magic_docs = []
347 347 for fname in self.lsmagic():
348 348 mname = 'magic_' + fname
349 349 for space in (Magic,self,self.__class__):
350 350 try:
351 351 fn = space.__dict__[mname]
352 352 except KeyError:
353 353 pass
354 354 else:
355 355 break
356 356 magic_docs.append('%s%s:\n\t%s\n' %(self.shell.ESC_MAGIC,
357 357 fname,fn.__doc__))
358 358 magic_docs = ''.join(magic_docs)
359 359
360 360 if mode == 'latex':
361 361 print self.format_latex(magic_docs)
362 362 return
363 363 else:
364 364 magic_docs = self.format_screen(magic_docs)
365 365
366 366 outmsg = """
367 367 IPython's 'magic' functions
368 368 ===========================
369 369
370 370 The magic function system provides a series of functions which allow you to
371 371 control the behavior of IPython itself, plus a lot of system-type
372 372 features. All these functions are prefixed with a % character, but parameters
373 373 are given without parentheses or quotes.
374 374
375 375 NOTE: If you have 'automagic' enabled (via the command line option or with the
376 376 %automagic function), you don't need to type in the % explicitly. By default,
377 377 IPython ships with automagic on, so you should only rarely need the % escape.
378 378
379 379 Example: typing '%cd mydir' (without the quotes) changes you working directory
380 380 to 'mydir', if it exists.
381 381
382 382 You can define your own magic functions to extend the system. See the supplied
383 383 ipythonrc and example-magic.py files for details (in your ipython
384 384 configuration directory, typically $HOME/.ipython/).
385 385
386 386 You can also define your own aliased names for magic functions. In your
387 387 ipythonrc file, placing a line like:
388 388
389 389 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
390 390
391 391 will define %pf as a new name for %profile.
392 392
393 393 You can also call magics in code using the ipmagic() function, which IPython
394 394 automatically adds to the builtin namespace. Type 'ipmagic?' for details.
395 395
396 396 For a list of the available magic functions, use %lsmagic. For a description
397 397 of any of them, type %magic_name?, e.g. '%cd?'.
398 398
399 399 Currently the magic system has the following functions:\n"""
400 400
401 401 mesc = self.shell.ESC_MAGIC
402 402 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
403 403 "\n\n%s%s\n\n%s" % (outmsg,
404 404 magic_docs,mesc,mesc,
405 405 (' '+mesc).join(self.lsmagic()),
406 406 Magic.auto_status[self.shell.rc.automagic] ) )
407 407
408 408 page(outmsg,screen_lines=self.shell.rc.screen_length)
409 409
410 410 def magic_automagic(self, parameter_s = ''):
411 411 """Make magic functions callable without having to type the initial %.
412 412
413 413 Toggles on/off (when off, you must call it as %automagic, of
414 414 course). Note that magic functions have lowest priority, so if there's
415 415 a variable whose name collides with that of a magic fn, automagic
416 416 won't work for that function (you get the variable instead). However,
417 417 if you delete the variable (del var), the previously shadowed magic
418 418 function becomes visible to automagic again."""
419 419
420 420 rc = self.shell.rc
421 421 rc.automagic = not rc.automagic
422 422 print '\n' + Magic.auto_status[rc.automagic]
423 423
424 424 def magic_autocall(self, parameter_s = ''):
425 425 """Make functions callable without having to type parentheses.
426 426
427 This toggles the autocall command line option on and off."""
427 This cycles the autocall command line through its three valid values
428 (0->Off, 1->Smart, 2->Full)"""
428 429
429 430 rc = self.shell.rc
430 431 rc.autocall = not rc.autocall
431 print "Automatic calling is:",['OFF','ON'][rc.autocall]
432 print "Automatic calling is:",['OFF','Smart','Full'][rc.autocall]
432 433
433 434 def magic_autoindent(self, parameter_s = ''):
434 435 """Toggle autoindent on/off (if available)."""
435 436
436 437 self.shell.set_autoindent()
437 438 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
438 439
439 440 def magic_system_verbose(self, parameter_s = ''):
440 441 """Toggle verbose printing of system calls on/off."""
441 442
442 443 self.shell.rc_set_toggle('system_verbose')
443 444 print "System verbose printing is:",\
444 445 ['OFF','ON'][self.shell.rc.system_verbose]
445 446
446 447 def magic_history(self, parameter_s = ''):
447 448 """Print input history (_i<n> variables), with most recent last.
448 449
449 450 %history [-n] -> print at most 40 inputs (some may be multi-line)\\
450 451 %history [-n] n -> print at most n inputs\\
451 452 %history [-n] n1 n2 -> print inputs between n1 and n2 (n2 not included)\\
452 453
453 454 Each input's number <n> is shown, and is accessible as the
454 455 automatically generated variable _i<n>. Multi-line statements are
455 456 printed starting at a new line for easy copy/paste.
456 457
457 458 If option -n is used, input numbers are not printed. This is useful if
458 459 you want to get a printout of many lines which can be directly pasted
459 460 into a text editor.
460 461
461 462 This feature is only available if numbered prompts are in use."""
462 463
463 464 shell = self.shell
464 465 if not shell.outputcache.do_full_cache:
465 466 print 'This feature is only available if numbered prompts are in use.'
466 467 return
467 468 opts,args = self.parse_options(parameter_s,'n',mode='list')
468 469
469 470 input_hist = shell.input_hist
470 471 default_length = 40
471 472 if len(args) == 0:
472 473 final = len(input_hist)
473 474 init = max(1,final-default_length)
474 475 elif len(args) == 1:
475 476 final = len(input_hist)
476 477 init = max(1,final-int(args[0]))
477 478 elif len(args) == 2:
478 479 init,final = map(int,args)
479 480 else:
480 481 warn('%hist takes 0, 1 or 2 arguments separated by spaces.')
481 482 print self.magic_hist.__doc__
482 483 return
483 484 width = len(str(final))
484 485 line_sep = ['','\n']
485 486 print_nums = not opts.has_key('n')
486 487 for in_num in range(init,final):
487 488 inline = input_hist[in_num]
488 489 multiline = int(inline.count('\n') > 1)
489 490 if print_nums:
490 491 print '%s:%s' % (str(in_num).ljust(width),line_sep[multiline]),
491 492 print inline,
492 493
493 494 def magic_hist(self, parameter_s=''):
494 495 """Alternate name for %history."""
495 496 return self.magic_history(parameter_s)
496 497
497 498 def magic_p(self, parameter_s=''):
498 499 """Just a short alias for Python's 'print'."""
499 500 exec 'print ' + parameter_s in self.shell.user_ns
500 501
501 502 def magic_r(self, parameter_s=''):
502 503 """Repeat previous input.
503 504
504 505 If given an argument, repeats the previous command which starts with
505 506 the same string, otherwise it just repeats the previous input.
506 507
507 508 Shell escaped commands (with ! as first character) are not recognized
508 509 by this system, only pure python code and magic commands.
509 510 """
510 511
511 512 start = parameter_s.strip()
512 513 esc_magic = self.shell.ESC_MAGIC
513 514 # Identify magic commands even if automagic is on (which means
514 515 # the in-memory version is different from that typed by the user).
515 516 if self.shell.rc.automagic:
516 517 start_magic = esc_magic+start
517 518 else:
518 519 start_magic = start
519 520 # Look through the input history in reverse
520 521 for n in range(len(self.shell.input_hist)-2,0,-1):
521 522 input = self.shell.input_hist[n]
522 523 # skip plain 'r' lines so we don't recurse to infinity
523 524 if input != 'ipmagic("r")\n' and \
524 525 (input.startswith(start) or input.startswith(start_magic)):
525 526 #print 'match',`input` # dbg
526 527 print 'Executing:',input,
527 528 self.shell.runlines(input)
528 529 return
529 530 print 'No previous input matching `%s` found.' % start
530 531
531 532 def magic_page(self, parameter_s=''):
532 533 """Pretty print the object and display it through a pager.
533 534
534 535 If no parameter is given, use _ (last output)."""
535 536 # After a function contributed by Olivier Aubert, slightly modified.
536 537
537 538 oname = parameter_s and parameter_s or '_'
538 539 info = self._ofind(oname)
539 540 if info['found']:
540 541 page(pformat(info['obj']))
541 542 else:
542 543 print 'Object `%s` not found' % oname
543 544
544 545 def magic_profile(self, parameter_s=''):
545 546 """Print your currently active IPyhton profile."""
546 547 if self.shell.rc.profile:
547 548 printpl('Current IPython profile: $self.shell.rc.profile.')
548 549 else:
549 550 print 'No profile active.'
550 551
551 552 def _inspect(self,meth,oname,**kw):
552 553 """Generic interface to the inspector system.
553 554
554 555 This function is meant to be called by pdef, pdoc & friends."""
555 556
556 557 oname = oname.strip()
557 558 info = Struct(self._ofind(oname))
558 559 if info.found:
559 560 pmethod = getattr(self.shell.inspector,meth)
560 561 formatter = info.ismagic and self.format_screen or None
561 562 if meth == 'pdoc':
562 563 pmethod(info.obj,oname,formatter)
563 564 elif meth == 'pinfo':
564 565 pmethod(info.obj,oname,formatter,info,**kw)
565 566 else:
566 567 pmethod(info.obj,oname)
567 568 else:
568 569 print 'Object `%s` not found.' % oname
569 570 return 'not found' # so callers can take other action
570 571
571 572 def magic_pdef(self, parameter_s=''):
572 573 """Print the definition header for any callable object.
573 574
574 575 If the object is a class, print the constructor information."""
575 576 self._inspect('pdef',parameter_s)
576 577
577 578 def magic_pdoc(self, parameter_s=''):
578 579 """Print the docstring for an object.
579 580
580 581 If the given object is a class, it will print both the class and the
581 582 constructor docstrings."""
582 583 self._inspect('pdoc',parameter_s)
583 584
584 585 def magic_psource(self, parameter_s=''):
585 586 """Print (or run through pager) the source code for an object."""
586 587 self._inspect('psource',parameter_s)
587 588
588 589 def magic_pfile(self, parameter_s=''):
589 590 """Print (or run through pager) the file where an object is defined.
590 591
591 592 The file opens at the line where the object definition begins. IPython
592 593 will honor the environment variable PAGER if set, and otherwise will
593 594 do its best to print the file in a convenient form.
594 595
595 596 If the given argument is not an object currently defined, IPython will
596 597 try to interpret it as a filename (automatically adding a .py extension
597 598 if needed). You can thus use %pfile as a syntax highlighting code
598 599 viewer."""
599 600
600 601 # first interpret argument as an object name
601 602 out = self._inspect('pfile',parameter_s)
602 603 # if not, try the input as a filename
603 604 if out == 'not found':
604 605 try:
605 606 filename = get_py_filename(parameter_s)
606 607 except IOError,msg:
607 608 print msg
608 609 return
609 610 page(self.shell.inspector.format(file(filename).read()))
610 611
611 612 def magic_pinfo(self, parameter_s=''):
612 613 """Provide detailed information about an object.
613 614
614 615 '%pinfo object' is just a synonym for object? or ?object."""
615 616
616 617 #print 'pinfo par: <%s>' % parameter_s # dbg
617 618
618 619 # detail_level: 0 -> obj? , 1 -> obj??
619 620 detail_level = 0
620 621 # We need to detect if we got called as 'pinfo pinfo foo', which can
621 622 # happen if the user types 'pinfo foo?' at the cmd line.
622 623 pinfo,qmark1,oname,qmark2 = \
623 624 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
624 625 if pinfo or qmark1 or qmark2:
625 626 detail_level = 1
626 627 if "*" in oname:
627 628 self.magic_psearch(oname)
628 629 else:
629 630 self._inspect('pinfo',oname,detail_level=detail_level)
630 631
631 632 def magic_psearch(self, parameter_s=''):
632 633 """Search for object in namespaces by wildcard.
633 634
634 635 %psearch [options] PATTERN [OBJECT TYPE]
635 636
636 637 Note: ? can be used as a synonym for %psearch, at the beginning or at
637 638 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
638 639 rest of the command line must be unchanged (options come first), so
639 640 for example the following forms are equivalent
640 641
641 642 %psearch -i a* function
642 643 -i a* function?
643 644 ?-i a* function
644 645
645 646 Arguments:
646 647
647 648 PATTERN
648 649
649 650 where PATTERN is a string containing * as a wildcard similar to its
650 651 use in a shell. The pattern is matched in all namespaces on the
651 652 search path. By default objects starting with a single _ are not
652 653 matched, many IPython generated objects have a single
653 654 underscore. The default is case insensitive matching. Matching is
654 655 also done on the attributes of objects and not only on the objects
655 656 in a module.
656 657
657 658 [OBJECT TYPE]
658 659
659 660 Is the name of a python type from the types module. The name is
660 661 given in lowercase without the ending type, ex. StringType is
661 662 written string. By adding a type here only objects matching the
662 663 given type are matched. Using all here makes the pattern match all
663 664 types (this is the default).
664 665
665 666 Options:
666 667
667 668 -a: makes the pattern match even objects whose names start with a
668 669 single underscore. These names are normally ommitted from the
669 670 search.
670 671
671 672 -i/-c: make the pattern case insensitive/sensitive. If neither of
672 673 these options is given, the default is read from your ipythonrc
673 674 file. The option name which sets this value is
674 675 'wildcards_case_sensitive'. If this option is not specified in your
675 676 ipythonrc file, IPython's internal default is to do a case sensitive
676 677 search.
677 678
678 679 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
679 680 specifiy can be searched in any of the following namespaces:
680 681 'builtin', 'user', 'user_global','internal', 'alias', where
681 682 'builtin' and 'user' are the search defaults. Note that you should
682 683 not use quotes when specifying namespaces.
683 684
684 685 'Builtin' contains the python module builtin, 'user' contains all
685 686 user data, 'alias' only contain the shell aliases and no python
686 687 objects, 'internal' contains objects used by IPython. The
687 688 'user_global' namespace is only used by embedded IPython instances,
688 689 and it contains module-level globals. You can add namespaces to the
689 690 search with -s or exclude them with -e (these options can be given
690 691 more than once).
691 692
692 693 Examples:
693 694
694 695 %psearch a* -> objects beginning with an a
695 696 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
696 697 %psearch a* function -> all functions beginning with an a
697 698 %psearch re.e* -> objects beginning with an e in module re
698 699 %psearch r*.e* -> objects that start with e in modules starting in r
699 700 %psearch r*.* string -> all strings in modules beginning with r
700 701
701 702 Case sensitve search:
702 703
703 704 %psearch -c a* list all object beginning with lower case a
704 705
705 706 Show objects beginning with a single _:
706 707
707 708 %psearch -a _* list objects beginning with a single underscore"""
708 709
709 710 # default namespaces to be searched
710 711 def_search = ['user','builtin']
711 712
712 713 # Process options/args
713 714 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
714 715 opt = opts.get
715 716 shell = self.shell
716 717 psearch = shell.inspector.psearch
717 718
718 719 # select case options
719 720 if opts.has_key('i'):
720 721 ignore_case = True
721 722 elif opts.has_key('c'):
722 723 ignore_case = False
723 724 else:
724 725 ignore_case = not shell.rc.wildcards_case_sensitive
725 726
726 727 # Build list of namespaces to search from user options
727 728 def_search.extend(opt('s',[]))
728 729 ns_exclude = ns_exclude=opt('e',[])
729 730 ns_search = [nm for nm in def_search if nm not in ns_exclude]
730 731
731 732 # Call the actual search
732 733 try:
733 734 psearch(args,shell.ns_table,ns_search,
734 735 show_all=opt('a'),ignore_case=ignore_case)
735 736 except:
736 737 shell.showtraceback()
737 738
738 739 def magic_who_ls(self, parameter_s=''):
739 740 """Return a sorted list of all interactive variables.
740 741
741 742 If arguments are given, only variables of types matching these
742 743 arguments are returned."""
743 744
744 745 user_ns = self.shell.user_ns
745 746 internal_ns = self.shell.internal_ns
746 747 user_config_ns = self.shell.user_config_ns
747 748 out = []
748 749 typelist = parameter_s.split()
749 750
750 751 for i in user_ns:
751 752 if not (i.startswith('_') or i.startswith('_i')) \
752 753 and not (i in internal_ns or i in user_config_ns):
753 754 if typelist:
754 755 if type(user_ns[i]).__name__ in typelist:
755 756 out.append(i)
756 757 else:
757 758 out.append(i)
758 759 out.sort()
759 760 return out
760 761
761 762 def magic_who(self, parameter_s=''):
762 763 """Print all interactive variables, with some minimal formatting.
763 764
764 765 If any arguments are given, only variables whose type matches one of
765 766 these are printed. For example:
766 767
767 768 %who function str
768 769
769 770 will only list functions and strings, excluding all other types of
770 771 variables. To find the proper type names, simply use type(var) at a
771 772 command line to see how python prints type names. For example:
772 773
773 774 In [1]: type('hello')\\
774 775 Out[1]: <type 'str'>
775 776
776 777 indicates that the type name for strings is 'str'.
777 778
778 779 %who always excludes executed names loaded through your configuration
779 780 file and things which are internal to IPython.
780 781
781 782 This is deliberate, as typically you may load many modules and the
782 783 purpose of %who is to show you only what you've manually defined."""
783 784
784 785 varlist = self.magic_who_ls(parameter_s)
785 786 if not varlist:
786 787 print 'Interactive namespace is empty.'
787 788 return
788 789
789 790 # if we have variables, move on...
790 791
791 792 # stupid flushing problem: when prompts have no separators, stdout is
792 793 # getting lost. I'm starting to think this is a python bug. I'm having
793 794 # to force a flush with a print because even a sys.stdout.flush
794 795 # doesn't seem to do anything!
795 796
796 797 count = 0
797 798 for i in varlist:
798 799 print i+'\t',
799 800 count += 1
800 801 if count > 8:
801 802 count = 0
802 803 print
803 804 sys.stdout.flush() # FIXME. Why the hell isn't this flushing???
804 805
805 806 print # well, this does force a flush at the expense of an extra \n
806 807
807 808 def magic_whos(self, parameter_s=''):
808 809 """Like %who, but gives some extra information about each variable.
809 810
810 811 The same type filtering of %who can be applied here.
811 812
812 813 For all variables, the type is printed. Additionally it prints:
813 814
814 815 - For {},[],(): their length.
815 816
816 817 - For Numeric arrays, a summary with shape, number of elements,
817 818 typecode and size in memory.
818 819
819 820 - Everything else: a string representation, snipping their middle if
820 821 too long."""
821 822
822 823 varnames = self.magic_who_ls(parameter_s)
823 824 if not varnames:
824 825 print 'Interactive namespace is empty.'
825 826 return
826 827
827 828 # if we have variables, move on...
828 829
829 830 # for these types, show len() instead of data:
830 831 seq_types = [types.DictType,types.ListType,types.TupleType]
831 832
832 833 # for Numeric arrays, display summary info
833 834 try:
834 835 import Numeric
835 836 except ImportError:
836 837 array_type = None
837 838 else:
838 839 array_type = Numeric.ArrayType.__name__
839 840
840 841 # Find all variable names and types so we can figure out column sizes
841 842 get_vars = lambda i: self.shell.user_ns[i]
842 843 type_name = lambda v: type(v).__name__
843 844 varlist = map(get_vars,varnames)
844 845
845 846 typelist = []
846 847 for vv in varlist:
847 848 tt = type_name(vv)
848 849 if tt=='instance':
849 850 typelist.append(str(vv.__class__))
850 851 else:
851 852 typelist.append(tt)
852 853
853 854 # column labels and # of spaces as separator
854 855 varlabel = 'Variable'
855 856 typelabel = 'Type'
856 857 datalabel = 'Data/Info'
857 858 colsep = 3
858 859 # variable format strings
859 860 vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
860 861 vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
861 862 aformat = "%s: %s elems, type `%s`, %s bytes"
862 863 # find the size of the columns to format the output nicely
863 864 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
864 865 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
865 866 # table header
866 867 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
867 868 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
868 869 # and the table itself
869 870 kb = 1024
870 871 Mb = 1048576 # kb**2
871 872 for vname,var,vtype in zip(varnames,varlist,typelist):
872 873 print itpl(vformat),
873 874 if vtype in seq_types:
874 875 print len(var)
875 876 elif vtype==array_type:
876 877 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
877 878 vsize = Numeric.size(var)
878 879 vbytes = vsize*var.itemsize()
879 880 if vbytes < 100000:
880 881 print aformat % (vshape,vsize,var.typecode(),vbytes)
881 882 else:
882 883 print aformat % (vshape,vsize,var.typecode(),vbytes),
883 884 if vbytes < Mb:
884 885 print '(%s kb)' % (vbytes/kb,)
885 886 else:
886 887 print '(%s Mb)' % (vbytes/Mb,)
887 888 else:
888 889 vstr = str(var).replace('\n','\\n')
889 890 if len(vstr) < 50:
890 891 print vstr
891 892 else:
892 893 printpl(vfmt_short)
893 894
894 895 def magic_reset(self, parameter_s=''):
895 896 """Resets the namespace by removing all names defined by the user.
896 897
897 898 Input/Output history are left around in case you need them."""
898 899
899 900 ans = raw_input(
900 901 "Once deleted, variables cannot be recovered. Proceed (y/n)? ")
901 902 if not ans.lower() == 'y':
902 903 print 'Nothing done.'
903 904 return
904 905 user_ns = self.shell.user_ns
905 906 for i in self.magic_who_ls():
906 907 del(user_ns[i])
907 908
908 909 def magic_config(self,parameter_s=''):
909 910 """Show IPython's internal configuration."""
910 911
911 912 page('Current configuration structure:\n'+
912 913 pformat(self.shell.rc.dict()))
913 914
914 915 def magic_logstart(self,parameter_s=''):
915 916 """Start logging anywhere in a session.
916 917
917 918 %logstart [-o|-t] [log_name [log_mode]]
918 919
919 920 If no name is given, it defaults to a file named 'ipython_log.py' in your
920 921 current directory, in 'rotate' mode (see below).
921 922
922 923 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
923 924 history up to that point and then continues logging.
924 925
925 926 %logstart takes a second optional parameter: logging mode. This can be one
926 927 of (note that the modes are given unquoted):\\
927 928 append: well, that says it.\\
928 929 backup: rename (if exists) to name~ and start name.\\
929 930 global: single logfile in your home dir, appended to.\\
930 931 over : overwrite existing log.\\
931 932 rotate: create rotating logs name.1~, name.2~, etc.
932 933
933 934 Options:
934 935
935 936 -o: log also IPython's output. In this mode, all commands which
936 937 generate an Out[NN] prompt are recorded to the logfile, right after
937 938 their corresponding input line. The output lines are always
938 939 prepended with a '#[Out]# ' marker, so that the log remains valid
939 940 Python code.
940 941
941 942 Since this marker is always the same, filtering only the output from
942 943 a log is very easy, using for example a simple awk call:
943 944
944 945 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
945 946
946 947 -t: put timestamps before each input line logged (these are put in
947 948 comments)."""
948 949
949 950 opts,par = self.parse_options(parameter_s,'ot')
950 951 log_output = 'o' in opts
951 952 timestamp = 't' in opts
952 953
953 954 rc = self.shell.rc
954 955 logger = self.shell.logger
955 956
956 957 # if no args are given, the defaults set in the logger constructor by
957 958 # ipytohn remain valid
958 959 if par:
959 960 try:
960 961 logfname,logmode = par.split()
961 962 except:
962 963 logfname = par
963 964 logmode = 'backup'
964 965 else:
965 966 logfname = logger.logfname
966 967 logmode = logger.logmode
967 968 # put logfname into rc struct as if it had been called on the command
968 969 # line, so it ends up saved in the log header Save it in case we need
969 970 # to restore it...
970 971 old_logfile = rc.opts.get('logfile','')
971 972 if logfname:
972 973 logfname = os.path.expanduser(logfname)
973 974 rc.opts.logfile = logfname
974 975 loghead = self.shell.loghead_tpl % (rc.opts,rc.args)
975 976 try:
976 977 started = logger.logstart(logfname,loghead,logmode,
977 978 log_output,timestamp)
978 979 except:
979 980 rc.opts.logfile = old_logfile
980 981 warn("Couldn't start log: %s" % sys.exc_info()[1])
981 982 else:
982 983 # log input history up to this point, optionally interleaving
983 984 # output if requested
984 985
985 986 if timestamp:
986 987 # disable timestamping for the previous history, since we've
987 988 # lost those already (no time machine here).
988 989 logger.timestamp = False
989 990 if log_output:
990 991 log_write = logger.log_write
991 992 input_hist = self.shell.input_hist
992 993 output_hist = self.shell.output_hist
993 994 for n in range(1,len(input_hist)-1):
994 995 log_write(input_hist[n].rstrip())
995 996 if n in output_hist:
996 997 log_write(repr(output_hist[n]),'output')
997 998 else:
998 999 logger.log_write(self.shell.input_hist[1:])
999 1000 if timestamp:
1000 1001 # re-enable timestamping
1001 1002 logger.timestamp = True
1002 1003
1003 1004 print ('Activating auto-logging. '
1004 1005 'Current session state plus future input saved.')
1005 1006 logger.logstate()
1006 1007
1007 1008 def magic_logoff(self,parameter_s=''):
1008 1009 """Temporarily stop logging.
1009 1010
1010 1011 You must have previously started logging."""
1011 1012 self.shell.logger.switch_log(0)
1012 1013
1013 1014 def magic_logon(self,parameter_s=''):
1014 1015 """Restart logging.
1015 1016
1016 1017 This function is for restarting logging which you've temporarily
1017 1018 stopped with %logoff. For starting logging for the first time, you
1018 1019 must use the %logstart function, which allows you to specify an
1019 1020 optional log filename."""
1020 1021
1021 1022 self.shell.logger.switch_log(1)
1022 1023
1023 1024 def magic_logstate(self,parameter_s=''):
1024 1025 """Print the status of the logging system."""
1025 1026
1026 1027 self.shell.logger.logstate()
1027 1028
1028 1029 def magic_pdb(self, parameter_s=''):
1029 1030 """Control the calling of the pdb interactive debugger.
1030 1031
1031 1032 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1032 1033 argument it works as a toggle.
1033 1034
1034 1035 When an exception is triggered, IPython can optionally call the
1035 1036 interactive pdb debugger after the traceback printout. %pdb toggles
1036 1037 this feature on and off."""
1037 1038
1038 1039 par = parameter_s.strip().lower()
1039 1040
1040 1041 if par:
1041 1042 try:
1042 1043 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1043 1044 except KeyError:
1044 1045 print ('Incorrect argument. Use on/1, off/0, '
1045 1046 'or nothing for a toggle.')
1046 1047 return
1047 1048 else:
1048 1049 # toggle
1049 1050 new_pdb = not self.shell.InteractiveTB.call_pdb
1050 1051
1051 1052 # set on the shell
1052 1053 self.shell.call_pdb = new_pdb
1053 1054 print 'Automatic pdb calling has been turned',on_off(new_pdb)
1054 1055
1055 1056 def magic_prun(self, parameter_s ='',user_mode=1,
1056 1057 opts=None,arg_lst=None,prog_ns=None):
1057 1058
1058 1059 """Run a statement through the python code profiler.
1059 1060
1060 1061 Usage:\\
1061 1062 %prun [options] statement
1062 1063
1063 1064 The given statement (which doesn't require quote marks) is run via the
1064 1065 python profiler in a manner similar to the profile.run() function.
1065 1066 Namespaces are internally managed to work correctly; profile.run
1066 1067 cannot be used in IPython because it makes certain assumptions about
1067 1068 namespaces which do not hold under IPython.
1068 1069
1069 1070 Options:
1070 1071
1071 1072 -l <limit>: you can place restrictions on what or how much of the
1072 1073 profile gets printed. The limit value can be:
1073 1074
1074 1075 * A string: only information for function names containing this string
1075 1076 is printed.
1076 1077
1077 1078 * An integer: only these many lines are printed.
1078 1079
1079 1080 * A float (between 0 and 1): this fraction of the report is printed
1080 1081 (for example, use a limit of 0.4 to see the topmost 40% only).
1081 1082
1082 1083 You can combine several limits with repeated use of the option. For
1083 1084 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1084 1085 information about class constructors.
1085 1086
1086 1087 -r: return the pstats.Stats object generated by the profiling. This
1087 1088 object has all the information about the profile in it, and you can
1088 1089 later use it for further analysis or in other functions.
1089 1090
1090 1091 Since magic functions have a particular form of calling which prevents
1091 1092 you from writing something like:\\
1092 1093 In [1]: p = %prun -r print 4 # invalid!\\
1093 1094 you must instead use IPython's automatic variables to assign this:\\
1094 1095 In [1]: %prun -r print 4 \\
1095 1096 Out[1]: <pstats.Stats instance at 0x8222cec>\\
1096 1097 In [2]: stats = _
1097 1098
1098 1099 If you really need to assign this value via an explicit function call,
1099 1100 you can always tap directly into the true name of the magic function
1100 1101 by using the ipmagic function (which IPython automatically adds to the
1101 1102 builtins):\\
1102 1103 In [3]: stats = ipmagic('prun','-r print 4')
1103 1104
1104 1105 You can type ipmagic? for more details on ipmagic.
1105 1106
1106 1107 -s <key>: sort profile by given key. You can provide more than one key
1107 1108 by using the option several times: '-s key1 -s key2 -s key3...'. The
1108 1109 default sorting key is 'time'.
1109 1110
1110 1111 The following is copied verbatim from the profile documentation
1111 1112 referenced below:
1112 1113
1113 1114 When more than one key is provided, additional keys are used as
1114 1115 secondary criteria when the there is equality in all keys selected
1115 1116 before them.
1116 1117
1117 1118 Abbreviations can be used for any key names, as long as the
1118 1119 abbreviation is unambiguous. The following are the keys currently
1119 1120 defined:
1120 1121
1121 1122 Valid Arg Meaning\\
1122 1123 "calls" call count\\
1123 1124 "cumulative" cumulative time\\
1124 1125 "file" file name\\
1125 1126 "module" file name\\
1126 1127 "pcalls" primitive call count\\
1127 1128 "line" line number\\
1128 1129 "name" function name\\
1129 1130 "nfl" name/file/line\\
1130 1131 "stdname" standard name\\
1131 1132 "time" internal time
1132 1133
1133 1134 Note that all sorts on statistics are in descending order (placing
1134 1135 most time consuming items first), where as name, file, and line number
1135 1136 searches are in ascending order (i.e., alphabetical). The subtle
1136 1137 distinction between "nfl" and "stdname" is that the standard name is a
1137 1138 sort of the name as printed, which means that the embedded line
1138 1139 numbers get compared in an odd way. For example, lines 3, 20, and 40
1139 1140 would (if the file names were the same) appear in the string order
1140 1141 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1141 1142 line numbers. In fact, sort_stats("nfl") is the same as
1142 1143 sort_stats("name", "file", "line").
1143 1144
1144 1145 -T <filename>: save profile results as shown on screen to a text
1145 1146 file. The profile is still shown on screen.
1146 1147
1147 1148 -D <filename>: save (via dump_stats) profile statistics to given
1148 1149 filename. This data is in a format understod by the pstats module, and
1149 1150 is generated by a call to the dump_stats() method of profile
1150 1151 objects. The profile is still shown on screen.
1151 1152
1152 1153 If you want to run complete programs under the profiler's control, use
1153 1154 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1154 1155 contains profiler specific options as described here.
1155 1156
1156 1157 You can read the complete documentation for the profile module with:\\
1157 1158 In [1]: import profile; profile.help() """
1158 1159
1159 1160 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1160 1161 # protect user quote marks
1161 1162 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1162 1163
1163 1164 if user_mode: # regular user call
1164 1165 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1165 1166 list_all=1)
1166 1167 namespace = self.shell.user_ns
1167 1168 else: # called to run a program by %run -p
1168 1169 try:
1169 1170 filename = get_py_filename(arg_lst[0])
1170 1171 except IOError,msg:
1171 1172 error(msg)
1172 1173 return
1173 1174
1174 1175 arg_str = 'execfile(filename,prog_ns)'
1175 1176 namespace = locals()
1176 1177
1177 1178 opts.merge(opts_def)
1178 1179
1179 1180 prof = profile.Profile()
1180 1181 try:
1181 1182 prof = prof.runctx(arg_str,namespace,namespace)
1182 1183 sys_exit = ''
1183 1184 except SystemExit:
1184 1185 sys_exit = """*** SystemExit exception caught in code being profiled."""
1185 1186
1186 1187 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1187 1188
1188 1189 lims = opts.l
1189 1190 if lims:
1190 1191 lims = [] # rebuild lims with ints/floats/strings
1191 1192 for lim in opts.l:
1192 1193 try:
1193 1194 lims.append(int(lim))
1194 1195 except ValueError:
1195 1196 try:
1196 1197 lims.append(float(lim))
1197 1198 except ValueError:
1198 1199 lims.append(lim)
1199 1200
1200 1201 # trap output
1201 1202 sys_stdout = sys.stdout
1202 1203 stdout_trap = StringIO()
1203 1204 try:
1204 1205 sys.stdout = stdout_trap
1205 1206 stats.print_stats(*lims)
1206 1207 finally:
1207 1208 sys.stdout = sys_stdout
1208 1209 output = stdout_trap.getvalue()
1209 1210 output = output.rstrip()
1210 1211
1211 1212 page(output,screen_lines=self.shell.rc.screen_length)
1212 1213 print sys_exit,
1213 1214
1214 1215 dump_file = opts.D[0]
1215 1216 text_file = opts.T[0]
1216 1217 if dump_file:
1217 1218 prof.dump_stats(dump_file)
1218 1219 print '\n*** Profile stats marshalled to file',\
1219 1220 `dump_file`+'.',sys_exit
1220 1221 if text_file:
1221 1222 file(text_file,'w').write(output)
1222 1223 print '\n*** Profile printout saved to text file',\
1223 1224 `text_file`+'.',sys_exit
1224 1225
1225 1226 if opts.has_key('r'):
1226 1227 return stats
1227 1228 else:
1228 1229 return None
1229 1230
1230 1231 def magic_run(self, parameter_s ='',runner=None):
1231 1232 """Run the named file inside IPython as a program.
1232 1233
1233 1234 Usage:\\
1234 1235 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1235 1236
1236 1237 Parameters after the filename are passed as command-line arguments to
1237 1238 the program (put in sys.argv). Then, control returns to IPython's
1238 1239 prompt.
1239 1240
1240 1241 This is similar to running at a system prompt:\\
1241 1242 $ python file args\\
1242 1243 but with the advantage of giving you IPython's tracebacks, and of
1243 1244 loading all variables into your interactive namespace for further use
1244 1245 (unless -p is used, see below).
1245 1246
1246 1247 The file is executed in a namespace initially consisting only of
1247 1248 __name__=='__main__' and sys.argv constructed as indicated. It thus
1248 1249 sees its environment as if it were being run as a stand-alone
1249 1250 program. But after execution, the IPython interactive namespace gets
1250 1251 updated with all variables defined in the program (except for __name__
1251 1252 and sys.argv). This allows for very convenient loading of code for
1252 1253 interactive work, while giving each program a 'clean sheet' to run in.
1253 1254
1254 1255 Options:
1255 1256
1256 1257 -n: __name__ is NOT set to '__main__', but to the running file's name
1257 1258 without extension (as python does under import). This allows running
1258 1259 scripts and reloading the definitions in them without calling code
1259 1260 protected by an ' if __name__ == "__main__" ' clause.
1260 1261
1261 1262 -i: run the file in IPython's namespace instead of an empty one. This
1262 1263 is useful if you are experimenting with code written in a text editor
1263 1264 which depends on variables defined interactively.
1264 1265
1265 1266 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1266 1267 being run. This is particularly useful if IPython is being used to
1267 1268 run unittests, which always exit with a sys.exit() call. In such
1268 1269 cases you are interested in the output of the test results, not in
1269 1270 seeing a traceback of the unittest module.
1270 1271
1271 1272 -t: print timing information at the end of the run. IPython will give
1272 1273 you an estimated CPU time consumption for your script, which under
1273 1274 Unix uses the resource module to avoid the wraparound problems of
1274 1275 time.clock(). Under Unix, an estimate of time spent on system tasks
1275 1276 is also given (for Windows platforms this is reported as 0.0).
1276 1277
1277 1278 If -t is given, an additional -N<N> option can be given, where <N>
1278 1279 must be an integer indicating how many times you want the script to
1279 1280 run. The final timing report will include total and per run results.
1280 1281
1281 1282 For example (testing the script uniq_stable.py):
1282 1283
1283 1284 In [1]: run -t uniq_stable
1284 1285
1285 1286 IPython CPU timings (estimated):\\
1286 1287 User : 0.19597 s.\\
1287 1288 System: 0.0 s.\\
1288 1289
1289 1290 In [2]: run -t -N5 uniq_stable
1290 1291
1291 1292 IPython CPU timings (estimated):\\
1292 1293 Total runs performed: 5\\
1293 1294 Times : Total Per run\\
1294 1295 User : 0.910862 s, 0.1821724 s.\\
1295 1296 System: 0.0 s, 0.0 s.
1296 1297
1297 1298 -d: run your program under the control of pdb, the Python debugger.
1298 1299 This allows you to execute your program step by step, watch variables,
1299 1300 etc. Internally, what IPython does is similar to calling:
1300 1301
1301 1302 pdb.run('execfile("YOURFILENAME")')
1302 1303
1303 1304 with a breakpoint set on line 1 of your file. You can change the line
1304 1305 number for this automatic breakpoint to be <N> by using the -bN option
1305 1306 (where N must be an integer). For example:
1306 1307
1307 1308 %run -d -b40 myscript
1308 1309
1309 1310 will set the first breakpoint at line 40 in myscript.py. Note that
1310 1311 the first breakpoint must be set on a line which actually does
1311 1312 something (not a comment or docstring) for it to stop execution.
1312 1313
1313 1314 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1314 1315 first enter 'c' (without qoutes) to start execution up to the first
1315 1316 breakpoint.
1316 1317
1317 1318 Entering 'help' gives information about the use of the debugger. You
1318 1319 can easily see pdb's full documentation with "import pdb;pdb.help()"
1319 1320 at a prompt.
1320 1321
1321 1322 -p: run program under the control of the Python profiler module (which
1322 1323 prints a detailed report of execution times, function calls, etc).
1323 1324
1324 1325 You can pass other options after -p which affect the behavior of the
1325 1326 profiler itself. See the docs for %prun for details.
1326 1327
1327 1328 In this mode, the program's variables do NOT propagate back to the
1328 1329 IPython interactive namespace (because they remain in the namespace
1329 1330 where the profiler executes them).
1330 1331
1331 1332 Internally this triggers a call to %prun, see its documentation for
1332 1333 details on the options available specifically for profiling."""
1333 1334
1334 1335 # get arguments and set sys.argv for program to be run.
1335 1336 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1336 1337 mode='list',list_all=1)
1337 1338
1338 1339 try:
1339 1340 filename = get_py_filename(arg_lst[0])
1340 1341 except IndexError:
1341 1342 warn('you must provide at least a filename.')
1342 1343 print '\n%run:\n',OInspect.getdoc(self.magic_run)
1343 1344 return
1344 1345 except IOError,msg:
1345 1346 error(msg)
1346 1347 return
1347 1348
1348 1349 # Control the response to exit() calls made by the script being run
1349 1350 exit_ignore = opts.has_key('e')
1350 1351
1351 1352 # Make sure that the running script gets a proper sys.argv as if it
1352 1353 # were run from a system shell.
1353 1354 save_argv = sys.argv # save it for later restoring
1354 1355 sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
1355 1356
1356 1357 if opts.has_key('i'):
1357 1358 prog_ns = self.shell.user_ns
1358 1359 __name__save = self.shell.user_ns['__name__']
1359 1360 prog_ns['__name__'] = '__main__'
1360 1361 else:
1361 1362 if opts.has_key('n'):
1362 1363 name = os.path.splitext(os.path.basename(filename))[0]
1363 1364 else:
1364 1365 name = '__main__'
1365 1366 prog_ns = {'__name__':name}
1366 1367
1367 1368 # pickle fix. See iplib for an explanation. But we need to make sure
1368 1369 # that, if we overwrite __main__, we replace it at the end
1369 1370 if prog_ns['__name__'] == '__main__':
1370 1371 restore_main = sys.modules['__main__']
1371 1372 else:
1372 1373 restore_main = False
1373 1374
1374 1375 sys.modules[prog_ns['__name__']] = FakeModule(prog_ns)
1375 1376
1376 1377 stats = None
1377 1378 try:
1378 1379 if opts.has_key('p'):
1379 1380 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1380 1381 else:
1381 1382 if opts.has_key('d'):
1382 1383 deb = Debugger.Pdb(self.shell.rc.colors)
1383 1384 # reset Breakpoint state, which is moronically kept
1384 1385 # in a class
1385 1386 bdb.Breakpoint.next = 1
1386 1387 bdb.Breakpoint.bplist = {}
1387 1388 bdb.Breakpoint.bpbynumber = [None]
1388 1389 # Set an initial breakpoint to stop execution
1389 1390 maxtries = 10
1390 1391 bp = int(opts.get('b',[1])[0])
1391 1392 checkline = deb.checkline(filename,bp)
1392 1393 if not checkline:
1393 1394 for bp in range(bp+1,bp+maxtries+1):
1394 1395 if deb.checkline(filename,bp):
1395 1396 break
1396 1397 else:
1397 1398 msg = ("\nI failed to find a valid line to set "
1398 1399 "a breakpoint\n"
1399 1400 "after trying up to line: %s.\n"
1400 1401 "Please set a valid breakpoint manually "
1401 1402 "with the -b option." % bp)
1402 1403 error(msg)
1403 1404 return
1404 1405 # if we find a good linenumber, set the breakpoint
1405 1406 deb.do_break('%s:%s' % (filename,bp))
1406 1407 # Start file run
1407 1408 print "NOTE: Enter 'c' at the",
1408 1409 print "ipdb> prompt to start your script."
1409 1410 try:
1410 1411 deb.run('execfile("%s")' % filename,prog_ns)
1411 1412 except:
1412 1413 etype, value, tb = sys.exc_info()
1413 1414 # Skip three frames in the traceback: the %run one,
1414 1415 # one inside bdb.py, and the command-line typed by the
1415 1416 # user (run by exec in pdb itself).
1416 1417 self.shell.InteractiveTB(etype,value,tb,tb_offset=3)
1417 1418 else:
1418 1419 if runner is None:
1419 1420 runner = self.shell.safe_execfile
1420 1421 if opts.has_key('t'):
1421 1422 try:
1422 1423 nruns = int(opts['N'][0])
1423 1424 if nruns < 1:
1424 1425 error('Number of runs must be >=1')
1425 1426 return
1426 1427 except (KeyError):
1427 1428 nruns = 1
1428 1429 if nruns == 1:
1429 1430 t0 = clock2()
1430 1431 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1431 1432 t1 = clock2()
1432 1433 t_usr = t1[0]-t0[0]
1433 1434 t_sys = t1[1]-t1[1]
1434 1435 print "\nIPython CPU timings (estimated):"
1435 1436 print " User : %10s s." % t_usr
1436 1437 print " System: %10s s." % t_sys
1437 1438 else:
1438 1439 runs = range(nruns)
1439 1440 t0 = clock2()
1440 1441 for nr in runs:
1441 1442 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1442 1443 t1 = clock2()
1443 1444 t_usr = t1[0]-t0[0]
1444 1445 t_sys = t1[1]-t1[1]
1445 1446 print "\nIPython CPU timings (estimated):"
1446 1447 print "Total runs performed:",nruns
1447 1448 print " Times : %10s %10s" % ('Total','Per run')
1448 1449 print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
1449 1450 print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
1450 1451
1451 1452 else:
1452 1453 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1453 1454 if opts.has_key('i'):
1454 1455 self.shell.user_ns['__name__'] = __name__save
1455 1456 else:
1456 1457 # update IPython interactive namespace
1457 1458 del prog_ns['__name__']
1458 1459 self.shell.user_ns.update(prog_ns)
1459 1460 finally:
1460 1461 sys.argv = save_argv
1461 1462 if restore_main:
1462 1463 sys.modules['__main__'] = restore_main
1463 1464 return stats
1464 1465
1465 1466 def magic_runlog(self, parameter_s =''):
1466 1467 """Run files as logs.
1467 1468
1468 1469 Usage:\\
1469 1470 %runlog file1 file2 ...
1470 1471
1471 1472 Run the named files (treating them as log files) in sequence inside
1472 1473 the interpreter, and return to the prompt. This is much slower than
1473 1474 %run because each line is executed in a try/except block, but it
1474 1475 allows running files with syntax errors in them.
1475 1476
1476 1477 Normally IPython will guess when a file is one of its own logfiles, so
1477 1478 you can typically use %run even for logs. This shorthand allows you to
1478 1479 force any file to be treated as a log file."""
1479 1480
1480 1481 for f in parameter_s.split():
1481 1482 self.shell.safe_execfile(f,self.shell.user_ns,
1482 1483 self.shell.user_ns,islog=1)
1483 1484
1484 1485 def magic_time(self,parameter_s = ''):
1485 1486 """Time execution of a Python statement or expression.
1486 1487
1487 1488 The CPU and wall clock times are printed, and the value of the
1488 1489 expression (if any) is returned. Note that under Win32, system time
1489 1490 is always reported as 0, since it can not be measured.
1490 1491
1491 1492 This function provides very basic timing functionality. In Python
1492 1493 2.3, the timeit module offers more control and sophistication, but for
1493 1494 now IPython supports Python 2.2, so we can not rely on timeit being
1494 1495 present.
1495 1496
1496 1497 Some examples:
1497 1498
1498 1499 In [1]: time 2**128
1499 1500 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1500 1501 Wall time: 0.00
1501 1502 Out[1]: 340282366920938463463374607431768211456L
1502 1503
1503 1504 In [2]: n = 1000000
1504 1505
1505 1506 In [3]: time sum(range(n))
1506 1507 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1507 1508 Wall time: 1.37
1508 1509 Out[3]: 499999500000L
1509 1510
1510 1511 In [4]: time print 'hello world'
1511 1512 hello world
1512 1513 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1513 1514 Wall time: 0.00
1514 1515 """
1515 1516
1516 1517 # fail immediately if the given expression can't be compiled
1517 1518 try:
1518 1519 mode = 'eval'
1519 1520 code = compile(parameter_s,'<timed eval>',mode)
1520 1521 except SyntaxError:
1521 1522 mode = 'exec'
1522 1523 code = compile(parameter_s,'<timed exec>',mode)
1523 1524 # skew measurement as little as possible
1524 1525 glob = self.shell.user_ns
1525 1526 clk = clock2
1526 1527 wtime = time.time
1527 1528 # time execution
1528 1529 wall_st = wtime()
1529 1530 if mode=='eval':
1530 1531 st = clk()
1531 1532 out = eval(code,glob)
1532 1533 end = clk()
1533 1534 else:
1534 1535 st = clk()
1535 1536 exec code in glob
1536 1537 end = clk()
1537 1538 out = None
1538 1539 wall_end = wtime()
1539 1540 # Compute actual times and report
1540 1541 wall_time = wall_end-wall_st
1541 1542 cpu_user = end[0]-st[0]
1542 1543 cpu_sys = end[1]-st[1]
1543 1544 cpu_tot = cpu_user+cpu_sys
1544 1545 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
1545 1546 (cpu_user,cpu_sys,cpu_tot)
1546 1547 print "Wall time: %.2f" % wall_time
1547 1548 return out
1548 1549
1549 1550 def magic_macro(self,parameter_s = ''):
1550 1551 """Define a set of input lines as a macro for future re-execution.
1551 1552
1552 1553 Usage:\\
1553 1554 %macro name n1-n2 n3-n4 ... n5 .. n6 ...
1554 1555
1555 1556 This will define a global variable called `name` which is a string
1556 1557 made of joining the slices and lines you specify (n1,n2,... numbers
1557 1558 above) from your input history into a single string. This variable
1558 1559 acts like an automatic function which re-executes those lines as if
1559 1560 you had typed them. You just type 'name' at the prompt and the code
1560 1561 executes.
1561 1562
1562 1563 The notation for indicating number ranges is: n1-n2 means 'use line
1563 1564 numbers n1,...n2' (the endpoint is included). That is, '5-7' means
1564 1565 using the lines numbered 5,6 and 7.
1565 1566
1566 1567 Note: as a 'hidden' feature, you can also use traditional python slice
1567 1568 notation, where N:M means numbers N through M-1.
1568 1569
1569 1570 For example, if your history contains (%hist prints it):
1570 1571
1571 1572 44: x=1\\
1572 1573 45: y=3\\
1573 1574 46: z=x+y\\
1574 1575 47: print x\\
1575 1576 48: a=5\\
1576 1577 49: print 'x',x,'y',y\\
1577 1578
1578 1579 you can create a macro with lines 44 through 47 (included) and line 49
1579 1580 called my_macro with:
1580 1581
1581 1582 In [51]: %macro my_macro 44-47 49
1582 1583
1583 1584 Now, typing `my_macro` (without quotes) will re-execute all this code
1584 1585 in one pass.
1585 1586
1586 1587 You don't need to give the line-numbers in order, and any given line
1587 1588 number can appear multiple times. You can assemble macros with any
1588 1589 lines from your input history in any order.
1589 1590
1590 1591 The macro is a simple object which holds its value in an attribute,
1591 1592 but IPython's display system checks for macros and executes them as
1592 1593 code instead of printing them when you type their name.
1593 1594
1594 1595 You can view a macro's contents by explicitly printing it with:
1595 1596
1596 1597 'print macro_name'.
1597 1598
1598 1599 For one-off cases which DON'T contain magic function calls in them you
1599 1600 can obtain similar results by explicitly executing slices from your
1600 1601 input history with:
1601 1602
1602 1603 In [60]: exec In[44:48]+In[49]"""
1603 1604
1604 1605 args = parameter_s.split()
1605 1606 name,ranges = args[0], args[1:]
1606 1607 #print 'rng',ranges # dbg
1607 1608 lines = self.extract_input_slices(ranges)
1608 1609 macro = Macro(lines)
1609 1610 self.shell.user_ns.update({name:macro})
1610 1611 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
1611 1612 print 'Macro contents:'
1612 1613 print macro,
1613 1614
1614 1615 def magic_save(self,parameter_s = ''):
1615 1616 """Save a set of lines to a given filename.
1616 1617
1617 1618 Usage:\\
1618 1619 %save filename n1-n2 n3-n4 ... n5 .. n6 ...
1619 1620
1620 1621 This function uses the same syntax as %macro for line extraction, but
1621 1622 instead of creating a macro it saves the resulting string to the
1622 1623 filename you specify.
1623 1624
1624 1625 It adds a '.py' extension to the file if you don't do so yourself, and
1625 1626 it asks for confirmation before overwriting existing files."""
1626 1627
1627 1628 args = parameter_s.split()
1628 1629 fname,ranges = args[0], args[1:]
1629 1630 if not fname.endswith('.py'):
1630 1631 fname += '.py'
1631 1632 if os.path.isfile(fname):
1632 1633 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
1633 1634 if ans.lower() not in ['y','yes']:
1634 1635 print 'Operation cancelled.'
1635 1636 return
1636 1637 cmds = ''.join(self.extract_input_slices(ranges))
1637 1638 f = file(fname,'w')
1638 1639 f.write(cmds)
1639 1640 f.close()
1640 1641 print 'The following commands were written to file `%s`:' % fname
1641 1642 print cmds
1642 1643
1643 1644 def _edit_macro(self,mname,macro):
1644 1645 """open an editor with the macro data in a file"""
1645 1646 filename = self.shell.mktempfile(macro.value)
1646 1647 self.shell.hooks.editor(filename)
1647 1648
1648 1649 # and make a new macro object, to replace the old one
1649 1650 mfile = open(filename)
1650 1651 mvalue = mfile.read()
1651 1652 mfile.close()
1652 1653 self.shell.user_ns[mname] = Macro(mvalue)
1653 1654
1654 1655 def magic_ed(self,parameter_s=''):
1655 1656 """Alias to %edit."""
1656 1657 return self.magic_edit(parameter_s)
1657 1658
1658 1659 def magic_edit(self,parameter_s='',last_call=['','']):
1659 1660 """Bring up an editor and execute the resulting code.
1660 1661
1661 1662 Usage:
1662 1663 %edit [options] [args]
1663 1664
1664 1665 %edit runs IPython's editor hook. The default version of this hook is
1665 1666 set to call the __IPYTHON__.rc.editor command. This is read from your
1666 1667 environment variable $EDITOR. If this isn't found, it will default to
1667 1668 vi under Linux/Unix and to notepad under Windows. See the end of this
1668 1669 docstring for how to change the editor hook.
1669 1670
1670 1671 You can also set the value of this editor via the command line option
1671 1672 '-editor' or in your ipythonrc file. This is useful if you wish to use
1672 1673 specifically for IPython an editor different from your typical default
1673 1674 (and for Windows users who typically don't set environment variables).
1674 1675
1675 1676 This command allows you to conveniently edit multi-line code right in
1676 1677 your IPython session.
1677 1678
1678 1679 If called without arguments, %edit opens up an empty editor with a
1679 1680 temporary file and will execute the contents of this file when you
1680 1681 close it (don't forget to save it!).
1681 1682
1682 1683 Options:
1683 1684
1684 1685 -p: this will call the editor with the same data as the previous time
1685 1686 it was used, regardless of how long ago (in your current session) it
1686 1687 was.
1687 1688
1688 1689 -x: do not execute the edited code immediately upon exit. This is
1689 1690 mainly useful if you are editing programs which need to be called with
1690 1691 command line arguments, which you can then do using %run.
1691 1692
1692 1693 Arguments:
1693 1694
1694 1695 If arguments are given, the following possibilites exist:
1695 1696
1696 1697 - The arguments are numbers or pairs of colon-separated numbers (like
1697 1698 1 4:8 9). These are interpreted as lines of previous input to be
1698 1699 loaded into the editor. The syntax is the same of the %macro command.
1699 1700
1700 1701 - If the argument doesn't start with a number, it is evaluated as a
1701 1702 variable and its contents loaded into the editor. You can thus edit
1702 1703 any string which contains python code (including the result of
1703 1704 previous edits).
1704 1705
1705 1706 - If the argument is the name of an object (other than a string),
1706 1707 IPython will try to locate the file where it was defined and open the
1707 1708 editor at the point where it is defined. You can use `%edit function`
1708 1709 to load an editor exactly at the point where 'function' is defined,
1709 1710 edit it and have the file be executed automatically.
1710 1711
1711 1712 If the object is a macro (see %macro for details), this opens up your
1712 1713 specified editor with a temporary file containing the macro's data.
1713 1714 Upon exit, the macro is reloaded with the contents of the file.
1714 1715
1715 1716 Note: opening at an exact line is only supported under Unix, and some
1716 1717 editors (like kedit and gedit up to Gnome 2.8) do not understand the
1717 1718 '+NUMBER' parameter necessary for this feature. Good editors like
1718 1719 (X)Emacs, vi, jed, pico and joe all do.
1719 1720
1720 1721 - If the argument is not found as a variable, IPython will look for a
1721 1722 file with that name (adding .py if necessary) and load it into the
1722 1723 editor. It will execute its contents with execfile() when you exit,
1723 1724 loading any code in the file into your interactive namespace.
1724 1725
1725 1726 After executing your code, %edit will return as output the code you
1726 1727 typed in the editor (except when it was an existing file). This way
1727 1728 you can reload the code in further invocations of %edit as a variable,
1728 1729 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
1729 1730 the output.
1730 1731
1731 1732 Note that %edit is also available through the alias %ed.
1732 1733
1733 1734 This is an example of creating a simple function inside the editor and
1734 1735 then modifying it. First, start up the editor:
1735 1736
1736 1737 In [1]: ed\\
1737 1738 Editing... done. Executing edited code...\\
1738 1739 Out[1]: 'def foo():\\n print "foo() was defined in an editing session"\\n'
1739 1740
1740 1741 We can then call the function foo():
1741 1742
1742 1743 In [2]: foo()\\
1743 1744 foo() was defined in an editing session
1744 1745
1745 1746 Now we edit foo. IPython automatically loads the editor with the
1746 1747 (temporary) file where foo() was previously defined:
1747 1748
1748 1749 In [3]: ed foo\\
1749 1750 Editing... done. Executing edited code...
1750 1751
1751 1752 And if we call foo() again we get the modified version:
1752 1753
1753 1754 In [4]: foo()\\
1754 1755 foo() has now been changed!
1755 1756
1756 1757 Here is an example of how to edit a code snippet successive
1757 1758 times. First we call the editor:
1758 1759
1759 1760 In [8]: ed\\
1760 1761 Editing... done. Executing edited code...\\
1761 1762 hello\\
1762 1763 Out[8]: "print 'hello'\\n"
1763 1764
1764 1765 Now we call it again with the previous output (stored in _):
1765 1766
1766 1767 In [9]: ed _\\
1767 1768 Editing... done. Executing edited code...\\
1768 1769 hello world\\
1769 1770 Out[9]: "print 'hello world'\\n"
1770 1771
1771 1772 Now we call it with the output #8 (stored in _8, also as Out[8]):
1772 1773
1773 1774 In [10]: ed _8\\
1774 1775 Editing... done. Executing edited code...\\
1775 1776 hello again\\
1776 1777 Out[10]: "print 'hello again'\\n"
1777 1778
1778 1779
1779 1780 Changing the default editor hook:
1780 1781
1781 1782 If you wish to write your own editor hook, you can put it in a
1782 1783 configuration file which you load at startup time. The default hook
1783 1784 is defined in the IPython.hooks module, and you can use that as a
1784 1785 starting example for further modifications. That file also has
1785 1786 general instructions on how to set a new hook for use once you've
1786 1787 defined it."""
1787 1788
1788 1789 # FIXME: This function has become a convoluted mess. It needs a
1789 1790 # ground-up rewrite with clean, simple logic.
1790 1791
1791 1792 def make_filename(arg):
1792 1793 "Make a filename from the given args"
1793 1794 try:
1794 1795 filename = get_py_filename(arg)
1795 1796 except IOError:
1796 1797 if args.endswith('.py'):
1797 1798 filename = arg
1798 1799 else:
1799 1800 filename = None
1800 1801 return filename
1801 1802
1802 1803 # custom exceptions
1803 1804 class DataIsObject(Exception): pass
1804 1805
1805 1806 opts,args = self.parse_options(parameter_s,'px')
1806 1807
1807 1808 # Default line number value
1808 1809 lineno = None
1809 1810 if opts.has_key('p'):
1810 1811 args = '_%s' % last_call[0]
1811 1812 if not self.shell.user_ns.has_key(args):
1812 1813 args = last_call[1]
1813 1814
1814 1815 # use last_call to remember the state of the previous call, but don't
1815 1816 # let it be clobbered by successive '-p' calls.
1816 1817 try:
1817 1818 last_call[0] = self.shell.outputcache.prompt_count
1818 1819 if not opts.has_key('p'):
1819 1820 last_call[1] = parameter_s
1820 1821 except:
1821 1822 pass
1822 1823
1823 1824 # by default this is done with temp files, except when the given
1824 1825 # arg is a filename
1825 1826 use_temp = 1
1826 1827
1827 1828 if re.match(r'\d',args):
1828 1829 # Mode where user specifies ranges of lines, like in %macro.
1829 1830 # This means that you can't edit files whose names begin with
1830 1831 # numbers this way. Tough.
1831 1832 ranges = args.split()
1832 1833 data = ''.join(self.extract_input_slices(ranges))
1833 1834 elif args.endswith('.py'):
1834 1835 filename = make_filename(args)
1835 1836 data = ''
1836 1837 use_temp = 0
1837 1838 elif args:
1838 1839 try:
1839 1840 # Load the parameter given as a variable. If not a string,
1840 1841 # process it as an object instead (below)
1841 1842
1842 1843 #print '*** args',args,'type',type(args) # dbg
1843 1844 data = eval(args,self.shell.user_ns)
1844 1845 if not type(data) in StringTypes:
1845 1846 raise DataIsObject
1846 1847
1847 1848 except (NameError,SyntaxError):
1848 1849 # given argument is not a variable, try as a filename
1849 1850 filename = make_filename(args)
1850 1851 if filename is None:
1851 1852 warn("Argument given (%s) can't be found as a variable "
1852 1853 "or as a filename." % args)
1853 1854 return
1854 1855
1855 1856 data = ''
1856 1857 use_temp = 0
1857 1858 except DataIsObject:
1858 1859
1859 1860 # macros have a special edit function
1860 1861 if isinstance(data,Macro):
1861 1862 self._edit_macro(args,data)
1862 1863 return
1863 1864
1864 1865 # For objects, try to edit the file where they are defined
1865 1866 try:
1866 1867 filename = inspect.getabsfile(data)
1867 1868 datafile = 1
1868 1869 except TypeError:
1869 1870 filename = make_filename(args)
1870 1871 datafile = 1
1871 1872 warn('Could not find file where `%s` is defined.\n'
1872 1873 'Opening a file named `%s`' % (args,filename))
1873 1874 # Now, make sure we can actually read the source (if it was in
1874 1875 # a temp file it's gone by now).
1875 1876 if datafile:
1876 1877 try:
1877 1878 lineno = inspect.getsourcelines(data)[1]
1878 1879 except IOError:
1879 1880 filename = make_filename(args)
1880 1881 if filename is None:
1881 1882 warn('The file `%s` where `%s` was defined cannot '
1882 1883 'be read.' % (filename,data))
1883 1884 return
1884 1885 use_temp = 0
1885 1886 else:
1886 1887 data = ''
1887 1888
1888 1889 if use_temp:
1889 1890 filename = self.shell.mktempfile(data)
1890 1891
1891 1892 # do actual editing here
1892 1893 print 'Editing...',
1893 1894 sys.stdout.flush()
1894 1895 self.shell.hooks.editor(filename,lineno)
1895 1896 if opts.has_key('x'): # -x prevents actual execution
1896 1897 print
1897 1898 else:
1898 1899 print 'done. Executing edited code...'
1899 1900 try:
1900 1901 self.shell.safe_execfile(filename,self.shell.user_ns)
1901 1902 except IOError,msg:
1902 1903 if msg.filename == filename:
1903 1904 warn('File not found. Did you forget to save?')
1904 1905 return
1905 1906 else:
1906 1907 self.shell.showtraceback()
1907 1908 except:
1908 1909 self.shell.showtraceback()
1909 1910
1910 1911 def magic_xmode(self,parameter_s = ''):
1911 1912 """Switch modes for the exception handlers.
1912 1913
1913 1914 Valid modes: Plain, Context and Verbose.
1914 1915
1915 1916 If called without arguments, acts as a toggle."""
1916 1917
1917 1918 def xmode_switch_err(name):
1918 1919 warn('Error changing %s exception modes.\n%s' %
1919 1920 (name,sys.exc_info()[1]))
1920 1921
1921 1922 shell = self.shell
1922 1923 new_mode = parameter_s.strip().capitalize()
1923 1924 try:
1924 1925 shell.InteractiveTB.set_mode(mode=new_mode)
1925 1926 print 'Exception reporting mode:',shell.InteractiveTB.mode
1926 1927 except:
1927 1928 xmode_switch_err('user')
1928 1929
1929 1930 # threaded shells use a special handler in sys.excepthook
1930 1931 if shell.isthreaded:
1931 1932 try:
1932 1933 shell.sys_excepthook.set_mode(mode=new_mode)
1933 1934 except:
1934 1935 xmode_switch_err('threaded')
1935 1936
1936 1937 def magic_colors(self,parameter_s = ''):
1937 1938 """Switch color scheme for prompts, info system and exception handlers.
1938 1939
1939 1940 Currently implemented schemes: NoColor, Linux, LightBG.
1940 1941
1941 1942 Color scheme names are not case-sensitive."""
1942 1943
1943 1944 def color_switch_err(name):
1944 1945 warn('Error changing %s color schemes.\n%s' %
1945 1946 (name,sys.exc_info()[1]))
1946 1947
1947 1948
1948 1949 new_scheme = parameter_s.strip()
1949 1950 if not new_scheme:
1950 1951 print 'You must specify a color scheme.'
1951 1952 return
1952 1953 # Under Windows, check for Gary Bishop's readline, which is necessary
1953 1954 # for ANSI coloring
1954 1955 if os.name in ['nt','dos']:
1955 1956 try:
1956 1957 import readline
1957 1958 except ImportError:
1958 1959 has_readline = 0
1959 1960 else:
1960 1961 try:
1961 1962 readline.GetOutputFile()
1962 1963 except AttributeError:
1963 1964 has_readline = 0
1964 1965 else:
1965 1966 has_readline = 1
1966 1967 if not has_readline:
1967 1968 msg = """\
1968 1969 Proper color support under MS Windows requires Gary Bishop's readline library.
1969 1970 You can find it at:
1970 1971 http://sourceforge.net/projects/uncpythontools
1971 1972 Gary's readline needs the ctypes module, from:
1972 1973 http://starship.python.net/crew/theller/ctypes
1973 1974
1974 1975 Defaulting color scheme to 'NoColor'"""
1975 1976 new_scheme = 'NoColor'
1976 1977 warn(msg)
1977 1978 # local shortcut
1978 1979 shell = self.shell
1979 1980
1980 1981 # Set prompt colors
1981 1982 try:
1982 1983 shell.outputcache.set_colors(new_scheme)
1983 1984 except:
1984 1985 color_switch_err('prompt')
1985 1986 else:
1986 1987 shell.rc.colors = \
1987 1988 shell.outputcache.color_table.active_scheme_name
1988 1989 # Set exception colors
1989 1990 try:
1990 1991 shell.InteractiveTB.set_colors(scheme = new_scheme)
1991 1992 shell.SyntaxTB.set_colors(scheme = new_scheme)
1992 1993 except:
1993 1994 color_switch_err('exception')
1994 1995
1995 1996 # threaded shells use a verbose traceback in sys.excepthook
1996 1997 if shell.isthreaded:
1997 1998 try:
1998 1999 shell.sys_excepthook.set_colors(scheme=new_scheme)
1999 2000 except:
2000 2001 color_switch_err('system exception handler')
2001 2002
2002 2003 # Set info (for 'object?') colors
2003 2004 if shell.rc.color_info:
2004 2005 try:
2005 2006 shell.inspector.set_active_scheme(new_scheme)
2006 2007 except:
2007 2008 color_switch_err('object inspector')
2008 2009 else:
2009 2010 shell.inspector.set_active_scheme('NoColor')
2010 2011
2011 2012 def magic_color_info(self,parameter_s = ''):
2012 2013 """Toggle color_info.
2013 2014
2014 2015 The color_info configuration parameter controls whether colors are
2015 2016 used for displaying object details (by things like %psource, %pfile or
2016 2017 the '?' system). This function toggles this value with each call.
2017 2018
2018 2019 Note that unless you have a fairly recent pager (less works better
2019 2020 than more) in your system, using colored object information displays
2020 2021 will not work properly. Test it and see."""
2021 2022
2022 2023 self.shell.rc.color_info = 1 - self.shell.rc.color_info
2023 2024 self.magic_colors(self.shell.rc.colors)
2024 2025 print 'Object introspection functions have now coloring:',
2025 2026 print ['OFF','ON'][self.shell.rc.color_info]
2026 2027
2027 2028 def magic_Pprint(self, parameter_s=''):
2028 2029 """Toggle pretty printing on/off."""
2029 2030
2030 2031 self.shell.outputcache.Pprint = 1 - self.shell.outputcache.Pprint
2031 2032 print 'Pretty printing has been turned', \
2032 2033 ['OFF','ON'][self.shell.outputcache.Pprint]
2033 2034
2034 2035 def magic_exit(self, parameter_s=''):
2035 2036 """Exit IPython, confirming if configured to do so.
2036 2037
2037 2038 You can configure whether IPython asks for confirmation upon exit by
2038 2039 setting the confirm_exit flag in the ipythonrc file."""
2039 2040
2040 2041 self.shell.exit()
2041 2042
2042 2043 def magic_quit(self, parameter_s=''):
2043 2044 """Exit IPython, confirming if configured to do so (like %exit)"""
2044 2045
2045 2046 self.shell.exit()
2046 2047
2047 2048 def magic_Exit(self, parameter_s=''):
2048 2049 """Exit IPython without confirmation."""
2049 2050
2050 2051 self.shell.exit_now = True
2051 2052
2052 2053 def magic_Quit(self, parameter_s=''):
2053 2054 """Exit IPython without confirmation (like %Exit)."""
2054 2055
2055 2056 self.shell.exit_now = True
2056 2057
2057 2058 #......................................................................
2058 2059 # Functions to implement unix shell-type things
2059 2060
2060 2061 def magic_alias(self, parameter_s = ''):
2061 2062 """Define an alias for a system command.
2062 2063
2063 2064 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2064 2065
2065 2066 Then, typing 'alias_name params' will execute the system command 'cmd
2066 2067 params' (from your underlying operating system).
2067 2068
2068 2069 Aliases have lower precedence than magic functions and Python normal
2069 2070 variables, so if 'foo' is both a Python variable and an alias, the
2070 2071 alias can not be executed until 'del foo' removes the Python variable.
2071 2072
2072 2073 You can use the %l specifier in an alias definition to represent the
2073 2074 whole line when the alias is called. For example:
2074 2075
2075 2076 In [2]: alias all echo "Input in brackets: <%l>"\\
2076 2077 In [3]: all hello world\\
2077 2078 Input in brackets: <hello world>
2078 2079
2079 2080 You can also define aliases with parameters using %s specifiers (one
2080 2081 per parameter):
2081 2082
2082 2083 In [1]: alias parts echo first %s second %s\\
2083 2084 In [2]: %parts A B\\
2084 2085 first A second B\\
2085 2086 In [3]: %parts A\\
2086 2087 Incorrect number of arguments: 2 expected.\\
2087 2088 parts is an alias to: 'echo first %s second %s'
2088 2089
2089 2090 Note that %l and %s are mutually exclusive. You can only use one or
2090 2091 the other in your aliases.
2091 2092
2092 2093 Aliases expand Python variables just like system calls using ! or !!
2093 2094 do: all expressions prefixed with '$' get expanded. For details of
2094 2095 the semantic rules, see PEP-215:
2095 2096 http://www.python.org/peps/pep-0215.html. This is the library used by
2096 2097 IPython for variable expansion. If you want to access a true shell
2097 2098 variable, an extra $ is necessary to prevent its expansion by IPython:
2098 2099
2099 2100 In [6]: alias show echo\\
2100 2101 In [7]: PATH='A Python string'\\
2101 2102 In [8]: show $PATH\\
2102 2103 A Python string\\
2103 2104 In [9]: show $$PATH\\
2104 2105 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2105 2106
2106 2107 You can use the alias facility to acess all of $PATH. See the %rehash
2107 2108 and %rehashx functions, which automatically create aliases for the
2108 2109 contents of your $PATH.
2109 2110
2110 2111 If called with no parameters, %alias prints the current alias table."""
2111 2112
2112 2113 par = parameter_s.strip()
2113 2114 if not par:
2114 2115 if self.shell.rc.automagic:
2115 2116 prechar = ''
2116 2117 else:
2117 2118 prechar = self.shell.ESC_MAGIC
2118 2119 print 'Alias\t\tSystem Command\n'+'-'*30
2119 2120 atab = self.shell.alias_table
2120 2121 aliases = atab.keys()
2121 2122 aliases.sort()
2122 2123 for alias in aliases:
2123 2124 print prechar+alias+'\t\t'+atab[alias][1]
2124 2125 print '-'*30+'\nTotal number of aliases:',len(aliases)
2125 2126 return
2126 2127 try:
2127 2128 alias,cmd = par.split(None,1)
2128 2129 except:
2129 2130 print OInspect.getdoc(self.magic_alias)
2130 2131 else:
2131 2132 nargs = cmd.count('%s')
2132 2133 if nargs>0 and cmd.find('%l')>=0:
2133 2134 error('The %s and %l specifiers are mutually exclusive '
2134 2135 'in alias definitions.')
2135 2136 else: # all looks OK
2136 2137 self.shell.alias_table[alias] = (nargs,cmd)
2137 2138 self.shell.alias_table_validate(verbose=1)
2138 2139 # end magic_alias
2139 2140
2140 2141 def magic_unalias(self, parameter_s = ''):
2141 2142 """Remove an alias"""
2142 2143
2143 2144 aname = parameter_s.strip()
2144 2145 if aname in self.shell.alias_table:
2145 2146 del self.shell.alias_table[aname]
2146 2147
2147 2148 def magic_rehash(self, parameter_s = ''):
2148 2149 """Update the alias table with all entries in $PATH.
2149 2150
2150 2151 This version does no checks on execute permissions or whether the
2151 2152 contents of $PATH are truly files (instead of directories or something
2152 2153 else). For such a safer (but slower) version, use %rehashx."""
2153 2154
2154 2155 # This function (and rehashx) manipulate the alias_table directly
2155 2156 # rather than calling magic_alias, for speed reasons. A rehash on a
2156 2157 # typical Linux box involves several thousand entries, so efficiency
2157 2158 # here is a top concern.
2158 2159
2159 2160 path = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep))
2160 2161 alias_table = self.shell.alias_table
2161 2162 for pdir in path:
2162 2163 for ff in os.listdir(pdir):
2163 2164 # each entry in the alias table must be (N,name), where
2164 2165 # N is the number of positional arguments of the alias.
2165 2166 alias_table[ff] = (0,ff)
2166 2167 # Make sure the alias table doesn't contain keywords or builtins
2167 2168 self.shell.alias_table_validate()
2168 2169 # Call again init_auto_alias() so we get 'rm -i' and other modified
2169 2170 # aliases since %rehash will probably clobber them
2170 2171 self.shell.init_auto_alias()
2171 2172
2172 2173 def magic_rehashx(self, parameter_s = ''):
2173 2174 """Update the alias table with all executable files in $PATH.
2174 2175
2175 2176 This version explicitly checks that every entry in $PATH is a file
2176 2177 with execute access (os.X_OK), so it is much slower than %rehash.
2177 2178
2178 2179 Under Windows, it checks executability as a match agains a
2179 2180 '|'-separated string of extensions, stored in the IPython config
2180 2181 variable win_exec_ext. This defaults to 'exe|com|bat'. """
2181 2182
2182 2183 path = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep))
2183 2184 alias_table = self.shell.alias_table
2184 2185
2185 2186 if os.name == 'posix':
2186 2187 isexec = lambda fname:os.path.isfile(fname) and \
2187 2188 os.access(fname,os.X_OK)
2188 2189 else:
2189 2190
2190 2191 try:
2191 2192 winext = os.environ['pathext'].replace(';','|').replace('.','')
2192 2193 except KeyError:
2193 2194 winext = 'exe|com|bat'
2194 2195
2195 2196 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2196 2197 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2197 2198 savedir = os.getcwd()
2198 2199 try:
2199 2200 # write the whole loop for posix/Windows so we don't have an if in
2200 2201 # the innermost part
2201 2202 if os.name == 'posix':
2202 2203 for pdir in path:
2203 2204 os.chdir(pdir)
2204 2205 for ff in os.listdir(pdir):
2205 2206 if isexec(ff):
2206 2207 # each entry in the alias table must be (N,name),
2207 2208 # where N is the number of positional arguments of the
2208 2209 # alias.
2209 2210 alias_table[ff] = (0,ff)
2210 2211 else:
2211 2212 for pdir in path:
2212 2213 os.chdir(pdir)
2213 2214 for ff in os.listdir(pdir):
2214 2215 if isexec(ff):
2215 2216 alias_table[execre.sub(r'\1',ff)] = (0,ff)
2216 2217 # Make sure the alias table doesn't contain keywords or builtins
2217 2218 self.shell.alias_table_validate()
2218 2219 # Call again init_auto_alias() so we get 'rm -i' and other
2219 2220 # modified aliases since %rehashx will probably clobber them
2220 2221 self.shell.init_auto_alias()
2221 2222 finally:
2222 2223 os.chdir(savedir)
2223 2224
2224 2225 def magic_pwd(self, parameter_s = ''):
2225 2226 """Return the current working directory path."""
2226 2227 return os.getcwd()
2227 2228
2228 2229 def magic_cd(self, parameter_s=''):
2229 2230 """Change the current working directory.
2230 2231
2231 2232 This command automatically maintains an internal list of directories
2232 2233 you visit during your IPython session, in the variable _dh. The
2233 2234 command %dhist shows this history nicely formatted.
2234 2235
2235 2236 Usage:
2236 2237
2237 2238 cd 'dir': changes to directory 'dir'.
2238 2239
2239 2240 cd -: changes to the last visited directory.
2240 2241
2241 2242 cd -<n>: changes to the n-th directory in the directory history.
2242 2243
2243 2244 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2244 2245 (note: cd <bookmark_name> is enough if there is no
2245 2246 directory <bookmark_name>, but a bookmark with the name exists.)
2246 2247
2247 2248 Options:
2248 2249
2249 2250 -q: quiet. Do not print the working directory after the cd command is
2250 2251 executed. By default IPython's cd command does print this directory,
2251 2252 since the default prompts do not display path information.
2252 2253
2253 2254 Note that !cd doesn't work for this purpose because the shell where
2254 2255 !command runs is immediately discarded after executing 'command'."""
2255 2256
2256 2257 parameter_s = parameter_s.strip()
2257 2258 bkms = self.shell.persist.get("bookmarks",{})
2258 2259
2259 2260 numcd = re.match(r'(-)(\d+)$',parameter_s)
2260 2261 # jump in directory history by number
2261 2262 if numcd:
2262 2263 nn = int(numcd.group(2))
2263 2264 try:
2264 2265 ps = self.shell.user_ns['_dh'][nn]
2265 2266 except IndexError:
2266 2267 print 'The requested directory does not exist in history.'
2267 2268 return
2268 2269 else:
2269 2270 opts = {}
2270 2271 else:
2271 2272 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2272 2273 # jump to previous
2273 2274 if ps == '-':
2274 2275 try:
2275 2276 ps = self.shell.user_ns['_dh'][-2]
2276 2277 except IndexError:
2277 2278 print 'No previous directory to change to.'
2278 2279 return
2279 2280 # jump to bookmark
2280 2281 elif opts.has_key('b') or (bkms.has_key(ps) and not os.path.isdir(ps)):
2281 2282 if bkms.has_key(ps):
2282 2283 target = bkms[ps]
2283 2284 print '(bookmark:%s) -> %s' % (ps,target)
2284 2285 ps = target
2285 2286 else:
2286 2287 if bkms:
2287 2288 error("Bookmark '%s' not found. "
2288 2289 "Use '%bookmark -l' to see your bookmarks." % ps)
2289 2290 else:
2290 2291 print "Bookmarks not set - use %bookmark <bookmarkname>"
2291 2292 return
2292 2293
2293 2294 # at this point ps should point to the target dir
2294 2295 if ps:
2295 2296 try:
2296 2297 os.chdir(os.path.expanduser(ps))
2297 2298 except OSError:
2298 2299 print sys.exc_info()[1]
2299 2300 else:
2300 2301 self.shell.user_ns['_dh'].append(os.getcwd())
2301 2302 else:
2302 2303 os.chdir(self.shell.home_dir)
2303 2304 self.shell.user_ns['_dh'].append(os.getcwd())
2304 2305 if not 'q' in opts:
2305 2306 print self.shell.user_ns['_dh'][-1]
2306 2307
2307 2308 def magic_dhist(self, parameter_s=''):
2308 2309 """Print your history of visited directories.
2309 2310
2310 2311 %dhist -> print full history\\
2311 2312 %dhist n -> print last n entries only\\
2312 2313 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2313 2314
2314 2315 This history is automatically maintained by the %cd command, and
2315 2316 always available as the global list variable _dh. You can use %cd -<n>
2316 2317 to go to directory number <n>."""
2317 2318
2318 2319 dh = self.shell.user_ns['_dh']
2319 2320 if parameter_s:
2320 2321 try:
2321 2322 args = map(int,parameter_s.split())
2322 2323 except:
2323 2324 self.arg_err(Magic.magic_dhist)
2324 2325 return
2325 2326 if len(args) == 1:
2326 2327 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2327 2328 elif len(args) == 2:
2328 2329 ini,fin = args
2329 2330 else:
2330 2331 self.arg_err(Magic.magic_dhist)
2331 2332 return
2332 2333 else:
2333 2334 ini,fin = 0,len(dh)
2334 2335 nlprint(dh,
2335 2336 header = 'Directory history (kept in _dh)',
2336 2337 start=ini,stop=fin)
2337 2338
2338 2339 def magic_env(self, parameter_s=''):
2339 2340 """List environment variables."""
2340 2341
2341 2342 return os.environ.data
2342 2343
2343 2344 def magic_pushd(self, parameter_s=''):
2344 2345 """Place the current dir on stack and change directory.
2345 2346
2346 2347 Usage:\\
2347 2348 %pushd ['dirname']
2348 2349
2349 2350 %pushd with no arguments does a %pushd to your home directory.
2350 2351 """
2351 2352 if parameter_s == '': parameter_s = '~'
2352 2353 dir_s = self.shell.dir_stack
2353 2354 if len(dir_s)>0 and os.path.expanduser(parameter_s) != \
2354 2355 os.path.expanduser(self.shell.dir_stack[0]):
2355 2356 try:
2356 2357 self.magic_cd(parameter_s)
2357 2358 dir_s.insert(0,os.getcwd().replace(self.home_dir,'~'))
2358 2359 self.magic_dirs()
2359 2360 except:
2360 2361 print 'Invalid directory'
2361 2362 else:
2362 2363 print 'You are already there!'
2363 2364
2364 2365 def magic_popd(self, parameter_s=''):
2365 2366 """Change to directory popped off the top of the stack.
2366 2367 """
2367 2368 if len (self.shell.dir_stack) > 1:
2368 2369 self.shell.dir_stack.pop(0)
2369 2370 self.magic_cd(self.shell.dir_stack[0])
2370 2371 print self.shell.dir_stack[0]
2371 2372 else:
2372 2373 print "You can't remove the starting directory from the stack:",\
2373 2374 self.shell.dir_stack
2374 2375
2375 2376 def magic_dirs(self, parameter_s=''):
2376 2377 """Return the current directory stack."""
2377 2378
2378 2379 return self.shell.dir_stack[:]
2379 2380
2380 2381 def magic_sc(self, parameter_s=''):
2381 2382 """Shell capture - execute a shell command and capture its output.
2382 2383
2383 2384 %sc [options] varname=command
2384 2385
2385 2386 IPython will run the given command using commands.getoutput(), and
2386 2387 will then update the user's interactive namespace with a variable
2387 2388 called varname, containing the value of the call. Your command can
2388 2389 contain shell wildcards, pipes, etc.
2389 2390
2390 2391 The '=' sign in the syntax is mandatory, and the variable name you
2391 2392 supply must follow Python's standard conventions for valid names.
2392 2393
2393 2394 Options:
2394 2395
2395 2396 -l: list output. Split the output on newlines into a list before
2396 2397 assigning it to the given variable. By default the output is stored
2397 2398 as a single string.
2398 2399
2399 2400 -v: verbose. Print the contents of the variable.
2400 2401
2401 2402 In most cases you should not need to split as a list, because the
2402 2403 returned value is a special type of string which can automatically
2403 2404 provide its contents either as a list (split on newlines) or as a
2404 2405 space-separated string. These are convenient, respectively, either
2405 2406 for sequential processing or to be passed to a shell command.
2406 2407
2407 2408 For example:
2408 2409
2409 2410 # Capture into variable a
2410 2411 In [9]: sc a=ls *py
2411 2412
2412 2413 # a is a string with embedded newlines
2413 2414 In [10]: a
2414 2415 Out[10]: 'setup.py\nwin32_manual_post_install.py'
2415 2416
2416 2417 # which can be seen as a list:
2417 2418 In [11]: a.l
2418 2419 Out[11]: ['setup.py', 'win32_manual_post_install.py']
2419 2420
2420 2421 # or as a whitespace-separated string:
2421 2422 In [12]: a.s
2422 2423 Out[12]: 'setup.py win32_manual_post_install.py'
2423 2424
2424 2425 # a.s is useful to pass as a single command line:
2425 2426 In [13]: !wc -l $a.s
2426 2427 146 setup.py
2427 2428 130 win32_manual_post_install.py
2428 2429 276 total
2429 2430
2430 2431 # while the list form is useful to loop over:
2431 2432 In [14]: for f in a.l:
2432 2433 ....: !wc -l $f
2433 2434 ....:
2434 2435 146 setup.py
2435 2436 130 win32_manual_post_install.py
2436 2437
2437 2438 Similiarly, the lists returned by the -l option are also special, in
2438 2439 the sense that you can equally invoke the .s attribute on them to
2439 2440 automatically get a whitespace-separated string from their contents:
2440 2441
2441 2442 In [1]: sc -l b=ls *py
2442 2443
2443 2444 In [2]: b
2444 2445 Out[2]: ['setup.py', 'win32_manual_post_install.py']
2445 2446
2446 2447 In [3]: b.s
2447 2448 Out[3]: 'setup.py win32_manual_post_install.py'
2448 2449
2449 2450 In summary, both the lists and strings used for ouptut capture have
2450 2451 the following special attributes:
2451 2452
2452 2453 .l (or .list) : value as list.
2453 2454 .n (or .nlstr): value as newline-separated string.
2454 2455 .s (or .spstr): value as space-separated string.
2455 2456 """
2456 2457
2457 2458 opts,args = self.parse_options(parameter_s,'lv')
2458 2459 # Try to get a variable name and command to run
2459 2460 try:
2460 2461 # the variable name must be obtained from the parse_options
2461 2462 # output, which uses shlex.split to strip options out.
2462 2463 var,_ = args.split('=',1)
2463 2464 var = var.strip()
2464 2465 # But the the command has to be extracted from the original input
2465 2466 # parameter_s, not on what parse_options returns, to avoid the
2466 2467 # quote stripping which shlex.split performs on it.
2467 2468 _,cmd = parameter_s.split('=',1)
2468 2469 except ValueError:
2469 2470 var,cmd = '',''
2470 2471 if not var:
2471 2472 error('you must specify a variable to assign the command to.')
2472 2473 return
2473 2474 # If all looks ok, proceed
2474 2475 out,err = self.shell.getoutputerror(cmd)
2475 2476 if err:
2476 2477 print >> Term.cerr,err
2477 2478 if opts.has_key('l'):
2478 2479 out = SList(out.split('\n'))
2479 2480 else:
2480 2481 out = LSString(out)
2481 2482 if opts.has_key('v'):
2482 2483 print '%s ==\n%s' % (var,pformat(out))
2483 2484 self.shell.user_ns.update({var:out})
2484 2485
2485 2486 def magic_sx(self, parameter_s=''):
2486 2487 """Shell execute - run a shell command and capture its output.
2487 2488
2488 2489 %sx command
2489 2490
2490 2491 IPython will run the given command using commands.getoutput(), and
2491 2492 return the result formatted as a list (split on '\\n'). Since the
2492 2493 output is _returned_, it will be stored in ipython's regular output
2493 2494 cache Out[N] and in the '_N' automatic variables.
2494 2495
2495 2496 Notes:
2496 2497
2497 2498 1) If an input line begins with '!!', then %sx is automatically
2498 2499 invoked. That is, while:
2499 2500 !ls
2500 2501 causes ipython to simply issue system('ls'), typing
2501 2502 !!ls
2502 2503 is a shorthand equivalent to:
2503 2504 %sx ls
2504 2505
2505 2506 2) %sx differs from %sc in that %sx automatically splits into a list,
2506 2507 like '%sc -l'. The reason for this is to make it as easy as possible
2507 2508 to process line-oriented shell output via further python commands.
2508 2509 %sc is meant to provide much finer control, but requires more
2509 2510 typing.
2510 2511
2511 2512 3) Just like %sc -l, this is a list with special attributes:
2512 2513
2513 2514 .l (or .list) : value as list.
2514 2515 .n (or .nlstr): value as newline-separated string.
2515 2516 .s (or .spstr): value as whitespace-separated string.
2516 2517
2517 2518 This is very useful when trying to use such lists as arguments to
2518 2519 system commands."""
2519 2520
2520 2521 if parameter_s:
2521 2522 out,err = self.shell.getoutputerror(parameter_s)
2522 2523 if err:
2523 2524 print >> Term.cerr,err
2524 2525 return SList(out.split('\n'))
2525 2526
2526 2527 def magic_bg(self, parameter_s=''):
2527 2528 """Run a job in the background, in a separate thread.
2528 2529
2529 2530 For example,
2530 2531
2531 2532 %bg myfunc(x,y,z=1)
2532 2533
2533 2534 will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the
2534 2535 execution starts, a message will be printed indicating the job
2535 2536 number. If your job number is 5, you can use
2536 2537
2537 2538 myvar = jobs.result(5) or myvar = jobs[5].result
2538 2539
2539 2540 to assign this result to variable 'myvar'.
2540 2541
2541 2542 IPython has a job manager, accessible via the 'jobs' object. You can
2542 2543 type jobs? to get more information about it, and use jobs.<TAB> to see
2543 2544 its attributes. All attributes not starting with an underscore are
2544 2545 meant for public use.
2545 2546
2546 2547 In particular, look at the jobs.new() method, which is used to create
2547 2548 new jobs. This magic %bg function is just a convenience wrapper
2548 2549 around jobs.new(), for expression-based jobs. If you want to create a
2549 2550 new job with an explicit function object and arguments, you must call
2550 2551 jobs.new() directly.
2551 2552
2552 2553 The jobs.new docstring also describes in detail several important
2553 2554 caveats associated with a thread-based model for background job
2554 2555 execution. Type jobs.new? for details.
2555 2556
2556 2557 You can check the status of all jobs with jobs.status().
2557 2558
2558 2559 The jobs variable is set by IPython into the Python builtin namespace.
2559 2560 If you ever declare a variable named 'jobs', you will shadow this
2560 2561 name. You can either delete your global jobs variable to regain
2561 2562 access to the job manager, or make a new name and assign it manually
2562 2563 to the manager (stored in IPython's namespace). For example, to
2563 2564 assign the job manager to the Jobs name, use:
2564 2565
2565 2566 Jobs = __builtins__.jobs"""
2566 2567
2567 2568 self.shell.jobs.new(parameter_s,self.shell.user_ns)
2568 2569
2569 2570 def magic_store(self, parameter_s=''):
2570 2571 """Lightweight persistence for python variables.
2571 2572
2572 2573 Example:
2573 2574
2574 2575 ville@badger[~]|1> A = ['hello',10,'world']\\
2575 2576 ville@badger[~]|2> %store A\\
2576 2577 ville@badger[~]|3> Exit
2577 2578
2578 2579 (IPython session is closed and started again...)
2579 2580
2580 2581 ville@badger:~$ ipython -p pysh\\
2581 2582 ville@badger[~]|1> print A
2582 2583
2583 2584 ['hello', 10, 'world']
2584 2585
2585 2586 Usage:
2586 2587
2587 2588 %store - Show list of all variables and their current values\\
2588 2589 %store <var> - Store the *current* value of the variable to disk\\
2589 2590 %store -d <var> - Remove the variable and its value from storage\\
2590 2591 %store -r - Remove all variables from storage
2591 2592
2592 2593 It should be noted that if you change the value of a variable, you
2593 2594 need to %store it again if you want to persist the new value.
2594 2595
2595 2596 Note also that the variables will need to be pickleable; most basic
2596 2597 python types can be safely %stored.
2597 2598 """
2598 2599
2599 2600 opts,args = self.parse_options(parameter_s,'dr',mode='list')
2600 2601 # delete
2601 2602 if opts.has_key('d'):
2602 2603 try:
2603 2604 todel = args[0]
2604 2605 except IndexError:
2605 2606 error('You must provide the variable to forget')
2606 2607 else:
2607 2608 try:
2608 2609 del self.shell.persist['S:' + todel]
2609 2610 except:
2610 2611 error("Can't delete variable '%s'" % todel)
2611 2612 # reset
2612 2613 elif opts.has_key('r'):
2613 2614 for k in self.shell.persist.keys():
2614 2615 if k.startswith('S:'):
2615 2616 del self.shell.persist[k]
2616 2617
2617 2618 # run without arguments -> list variables & values
2618 2619 elif not args:
2619 2620 vars = [v[2:] for v in self.shell.persist.keys()
2620 2621 if v.startswith('S:')]
2621 2622 vars.sort()
2622 2623 if vars:
2623 2624 size = max(map(len,vars))
2624 2625 else:
2625 2626 size = 0
2626 2627
2627 2628 print 'Stored variables and their in-memory values:'
2628 2629 fmt = '%-'+str(size)+'s -> %s'
2629 2630 get = self.shell.user_ns.get
2630 2631 for var in vars:
2631 2632 # print 30 first characters from every var
2632 2633 print fmt % (var,repr(get(var,'<unavailable>'))[:50])
2633 2634
2634 2635 # default action - store the variable
2635 2636 else:
2636 2637 pickled = pickle.dumps(self.shell.user_ns[args[0] ])
2637 2638 self.shell.persist[ 'S:' + args[0] ] = pickled
2638 2639 print "Stored '%s' (%d bytes)" % (args[0], len(pickled))
2639 2640
2640 2641 def magic_bookmark(self, parameter_s=''):
2641 2642 """Manage IPython's bookmark system.
2642 2643
2643 2644 %bookmark <name> - set bookmark to current dir
2644 2645 %bookmark <name> <dir> - set bookmark to <dir>
2645 2646 %bookmark -l - list all bookmarks
2646 2647 %bookmark -d <name> - remove bookmark
2647 2648 %bookmark -r - remove all bookmarks
2648 2649
2649 2650 You can later on access a bookmarked folder with:
2650 2651 %cd -b <name>
2651 2652 or simply '%cd <name>' if there is no directory called <name> AND
2652 2653 there is such a bookmark defined.
2653 2654
2654 2655 Your bookmarks persist through IPython sessions, but they are
2655 2656 associated with each profile."""
2656 2657
2657 2658 opts,args = self.parse_options(parameter_s,'drl',mode='list')
2658 2659 if len(args) > 2:
2659 2660 error('You can only give at most two arguments')
2660 2661 return
2661 2662
2662 2663 bkms = self.shell.persist.get('bookmarks',{})
2663 2664
2664 2665 if opts.has_key('d'):
2665 2666 try:
2666 2667 todel = args[0]
2667 2668 except IndexError:
2668 2669 error('You must provide a bookmark to delete')
2669 2670 else:
2670 2671 try:
2671 2672 del bkms[todel]
2672 2673 except:
2673 2674 error("Can't delete bookmark '%s'" % todel)
2674 2675 elif opts.has_key('r'):
2675 2676 bkms = {}
2676 2677 elif opts.has_key('l'):
2677 2678 bks = bkms.keys()
2678 2679 bks.sort()
2679 2680 if bks:
2680 2681 size = max(map(len,bks))
2681 2682 else:
2682 2683 size = 0
2683 2684 fmt = '%-'+str(size)+'s -> %s'
2684 2685 print 'Current bookmarks:'
2685 2686 for bk in bks:
2686 2687 print fmt % (bk,bkms[bk])
2687 2688 else:
2688 2689 if not args:
2689 2690 error("You must specify the bookmark name")
2690 2691 elif len(args)==1:
2691 2692 bkms[args[0]] = os.getcwd()
2692 2693 elif len(args)==2:
2693 2694 bkms[args[0]] = args[1]
2694 2695 self.shell.persist['bookmarks'] = bkms
2695 2696
2696 2697 def magic_pycat(self, parameter_s=''):
2697 2698 """Show a syntax-highlighted file through a pager.
2698 2699
2699 2700 This magic is similar to the cat utility, but it will assume the file
2700 2701 to be Python source and will show it with syntax highlighting. """
2701 2702
2702 2703 filename = get_py_filename(parameter_s)
2703 2704 page(self.shell.colorize(file_read(filename)),
2704 2705 screen_lines=self.shell.rc.screen_length)
2705 2706
2706 2707 # end Magic
@@ -1,565 +1,587 b''
1 1 # -*- Mode: Shell-Script -*- Not really, but shows comments correctly
2 # $Id: ipythonrc 963 2005-12-28 19:21:29Z fperez $
2 # $Id: ipythonrc 990 2006-01-04 06:59:02Z fperez $
3 3
4 4 #***************************************************************************
5 5 #
6 6 # Configuration file for IPython -- ipythonrc format
7 7 #
8 8 # The format of this file is simply one of 'key value' lines.
9 9 # Lines containing only whitespace at the beginning and then a # are ignored
10 10 # as comments. But comments can NOT be put on lines with data.
11 11
12 12 # The meaning and use of each key are explained below.
13 13
14 14 #---------------------------------------------------------------------------
15 15 # Section: included files
16 16
17 17 # Put one or more *config* files (with the syntax of this file) you want to
18 18 # include. For keys with a unique value the outermost file has precedence. For
19 19 # keys with multiple values, they all get assembled into a list which then
20 20 # gets loaded by IPython.
21 21
22 22 # In this file, all lists of things should simply be space-separated.
23 23
24 24 # This allows you to build hierarchies of files which recursively load
25 25 # lower-level services. If this is your main ~/.ipython/ipythonrc file, you
26 26 # should only keep here basic things you always want available. Then you can
27 27 # include it in every other special-purpose config file you create.
28 28 include
29 29
30 30 #---------------------------------------------------------------------------
31 31 # Section: startup setup
32 32
33 33 # These are mostly things which parallel a command line option of the same
34 34 # name.
35 35
36 36 # Keys in this section should only appear once. If any key from this section
37 37 # is encountered more than once, the last value remains, all earlier ones get
38 38 # discarded.
39 39
40 # Automatic calling of callable objects. If set to true, callable objects are
41 # automatically called when invoked at the command line, even if you don't
40
41 # Automatic calling of callable objects. If set to 1 or 2, callable objects
42 # are automatically called when invoked at the command line, even if you don't
42 43 # type parentheses. IPython adds the parentheses for you. For example:
43 44
44 45 #In [1]: str 45
45 46 #------> str(45)
46 47 #Out[1]: '45'
47 48
48 49 # IPython reprints your line with '---->' indicating that it added
49 50 # parentheses. While this option is very convenient for interactive use, it
50 51 # may occasionally cause problems with objects which have side-effects if
51 # called unexpectedly. Set it to 0 if you want to disable it.
52 # called unexpectedly.
53
54 # The valid values for autocall are:
55
56 # autocall 0 -> disabled (you can toggle it at runtime with the %autocall magic)
57
58 # autocall 1 -> active, but do not apply if there are no arguments on the line.
59
60 # In this mode, you get:
61
62 #In [1]: callable
63 #Out[1]: <built-in function callable>
64
65 #In [2]: callable 'hello'
66 #------> callable('hello')
67 #Out[2]: False
68
69 # 2 -> Active always. Even if no arguments are present, the callable object
70 # is called:
71
72 #In [4]: callable
73 #------> callable()
52 74
53 75 # Note that even with autocall off, you can still use '/' at the start of a
54 76 # line to treat the first argument on the command line as a function and add
55 77 # parentheses to it:
56 78
57 79 #In [8]: /str 43
58 80 #------> str(43)
59 81 #Out[8]: '43'
60 82
61 83 autocall 1
62 84
63 85 # Auto-edit syntax errors. When you use the %edit magic in ipython to edit
64 86 # source code (see the 'editor' variable below), it is possible that you save
65 87 # a file with syntax errors in it. If this variable is true, IPython will ask
66 88 # you whether to re-open the editor immediately to correct such an error.
67 89
68 90 autoedit_syntax 1
69 91
70 92 # Auto-indent. IPython can recognize lines ending in ':' and indent the next
71 93 # line, while also un-indenting automatically after 'raise' or 'return'.
72 94
73 95 # This feature uses the readline library, so it will honor your ~/.inputrc
74 96 # configuration (or whatever file your INPUTRC variable points to). Adding
75 97 # the following lines to your .inputrc file can make indent/unindenting more
76 98 # convenient (M-i indents, M-u unindents):
77 99
78 100 # $if Python
79 101 # "\M-i": " "
80 102 # "\M-u": "\d\d\d\d"
81 103 # $endif
82 104
83 105 # The feature is potentially a bit dangerous, because it can cause problems
84 106 # with pasting of indented code (the pasted code gets re-indented on each
85 107 # line). But it's a huge time-saver when working interactively. The magic
86 108 # function @autoindent allows you to toggle it on/off at runtime.
87 109
88 110 autoindent 1
89 111
90 112 # Auto-magic. This gives you access to all the magic functions without having
91 113 # to prepend them with an @ sign. If you define a variable with the same name
92 114 # as a magic function (say who=1), you will need to access the magic function
93 115 # with @ (@who in this example). However, if later you delete your variable
94 116 # (del who), you'll recover the automagic calling form.
95 117
96 118 # Considering that many magic functions provide a lot of shell-like
97 119 # functionality, automagic gives you something close to a full Python+system
98 120 # shell environment (and you can extend it further if you want).
99 121
100 122 automagic 1
101 123
102 124 # Size of the output cache. After this many entries are stored, the cache will
103 125 # get flushed. Depending on the size of your intermediate calculations, you
104 126 # may have memory problems if you make it too big, since keeping things in the
105 127 # cache prevents Python from reclaiming the memory for old results. Experiment
106 128 # with a value that works well for you.
107 129
108 130 # If you choose cache_size 0 IPython will revert to python's regular >>>
109 131 # unnumbered prompt. You will still have _, __ and ___ for your last three
110 132 # results, but that will be it. No dynamic _1, _2, etc. will be created. If
111 133 # you are running on a slow machine or with very limited memory, this may
112 134 # help.
113 135
114 136 cache_size 1000
115 137
116 138 # Classic mode: Setting 'classic 1' you lose many of IPython niceties,
117 139 # but that's your choice! Classic 1 -> same as IPython -classic.
118 140 # Note that this is _not_ the normal python interpreter, it's simply
119 141 # IPython emulating most of the classic interpreter's behavior.
120 142 classic 0
121 143
122 144 # colors - Coloring option for prompts and traceback printouts.
123 145
124 146 # Currently available schemes: NoColor, Linux, LightBG.
125 147
126 148 # This option allows coloring the prompts and traceback printouts. This
127 149 # requires a terminal which can properly handle color escape sequences. If you
128 150 # are having problems with this, use the NoColor scheme (uses no color escapes
129 151 # at all).
130 152
131 153 # The Linux option works well in linux console type environments: dark
132 154 # background with light fonts.
133 155
134 156 # LightBG is similar to Linux but swaps dark/light colors to be more readable
135 157 # in light background terminals.
136 158
137 159 # keep uncommented only the one you want:
138 160 colors Linux
139 161 #colors LightBG
140 162 #colors NoColor
141 163
142 164 ########################
143 165 # Note to Windows users
144 166 #
145 167 # Color and readline support is avaialble to Windows users via Gary Bishop's
146 168 # readline library. You can find Gary's tools at
147 169 # http://sourceforge.net/projects/uncpythontools.
148 170 # Note that his readline module requires in turn the ctypes library, available
149 171 # at http://starship.python.net/crew/theller/ctypes.
150 172 ########################
151 173
152 174 # color_info: IPython can display information about objects via a set of
153 175 # functions, and optionally can use colors for this, syntax highlighting
154 176 # source code and various other elements. This information is passed through a
155 177 # pager (it defaults to 'less' if $PAGER is not set).
156 178
157 179 # If your pager has problems, try to setting it to properly handle escapes
158 180 # (see the less manpage for detail), or disable this option. The magic
159 181 # function @color_info allows you to toggle this interactively for testing.
160 182
161 183 color_info 1
162 184
163 185 # confirm_exit: set to 1 if you want IPython to confirm when you try to exit
164 186 # with an EOF (Control-d in Unix, Control-Z/Enter in Windows). Note that using
165 187 # the magic functions @Exit or @Quit you can force a direct exit, bypassing
166 188 # any confirmation.
167 189
168 190 confirm_exit 1
169 191
170 192 # Use deep_reload() as a substitute for reload() by default. deep_reload() is
171 193 # still available as dreload() and appears as a builtin.
172 194
173 195 deep_reload 0
174 196
175 197 # Which editor to use with the @edit command. If you leave this at 0, IPython
176 198 # will honor your EDITOR environment variable. Since this editor is invoked on
177 199 # the fly by ipython and is meant for editing small code snippets, you may
178 200 # want to use a small, lightweight editor here.
179 201
180 202 # For Emacs users, setting up your Emacs server properly as described in the
181 203 # manual is a good idea. An alternative is to use jed, a very light editor
182 204 # with much of the feel of Emacs (though not as powerful for heavy-duty work).
183 205
184 206 editor 0
185 207
186 208 # log 1 -> same as ipython -log. This automatically logs to ./ipython.log
187 209 log 0
188 210
189 211 # Same as ipython -Logfile YourLogfileName.
190 212 # Don't use with log 1 (use one or the other)
191 213 logfile ''
192 214
193 215 # banner 0 -> same as ipython -nobanner
194 216 banner 1
195 217
196 218 # messages 0 -> same as ipython -nomessages
197 219 messages 1
198 220
199 221 # Automatically call the pdb debugger after every uncaught exception. If you
200 222 # are used to debugging using pdb, this puts you automatically inside of it
201 223 # after any call (either in IPython or in code called by it) which triggers an
202 224 # exception which goes uncaught.
203 225 pdb 0
204 226
205 227 # Enable the pprint module for printing. pprint tends to give a more readable
206 228 # display (than print) for complex nested data structures.
207 229 pprint 1
208 230
209 231 # Prompt strings
210 232
211 233 # Most bash-like escapes can be used to customize IPython's prompts, as well as
212 234 # a few additional ones which are IPython-specific. All valid prompt escapes
213 235 # are described in detail in the Customization section of the IPython HTML/PDF
214 236 # manual.
215 237
216 238 # Use \# to represent the current prompt number, and quote them to protect
217 239 # spaces.
218 240 prompt_in1 'In [\#]: '
219 241
220 242 # \D is replaced by as many dots as there are digits in the
221 243 # current value of \#.
222 244 prompt_in2 ' .\D.: '
223 245
224 246 prompt_out 'Out[\#]: '
225 247
226 248 # Select whether to left-pad the output prompts to match the length of the
227 249 # input ones. This allows you for example to use a simple '>' as an output
228 250 # prompt, and yet have the output line up with the input. If set to false,
229 251 # the output prompts will be unpadded (flush left).
230 252 prompts_pad_left 1
231 253
232 254 # quick 1 -> same as ipython -quick
233 255 quick 0
234 256
235 257 # Use the readline library (1) or not (0). Most users will want this on, but
236 258 # if you experience strange problems with line management (mainly when using
237 259 # IPython inside Emacs buffers) you may try disabling it. Not having it on
238 260 # prevents you from getting command history with the arrow keys, searching and
239 261 # name completion using TAB.
240 262
241 263 readline 1
242 264
243 265 # Screen Length: number of lines of your screen. This is used to control
244 266 # printing of very long strings. Strings longer than this number of lines will
245 267 # be paged with the less command instead of directly printed.
246 268
247 269 # The default value for this is 0, which means IPython will auto-detect your
248 270 # screen size every time it needs to print. If for some reason this isn't
249 271 # working well (it needs curses support), specify it yourself. Otherwise don't
250 272 # change the default.
251 273
252 274 screen_length 0
253 275
254 276 # Prompt separators for input and output.
255 277 # Use \n for newline explicitly, without quotes.
256 278 # Use 0 (like at the cmd line) to turn off a given separator.
257 279
258 280 # The structure of prompt printing is:
259 281 # (SeparateIn)Input....
260 282 # (SeparateOut)Output...
261 283 # (SeparateOut2), # that is, no newline is printed after Out2
262 284 # By choosing these you can organize your output any way you want.
263 285
264 286 separate_in \n
265 287 separate_out 0
266 288 separate_out2 0
267 289
268 290 # 'nosep 1' is a shorthand for '-SeparateIn 0 -SeparateOut 0 -SeparateOut2 0'.
269 291 # Simply removes all input/output separators, overriding the choices above.
270 292 nosep 0
271 293
272 294 # Wildcard searches - IPython has a system for searching names using
273 295 # shell-like wildcards; type %psearch? for details. This variables sets
274 296 # whether by default such searches should be case sensitive or not. You can
275 297 # always override the default at the system command line or the IPython
276 298 # prompt.
277 299
278 300 wildcards_case_sensitive 1
279 301
280 302 # xmode - Exception reporting mode.
281 303
282 304 # Valid modes: Plain, Context and Verbose.
283 305
284 306 # Plain: similar to python's normal traceback printing.
285 307
286 308 # Context: prints 5 lines of context source code around each line in the
287 309 # traceback.
288 310
289 311 # Verbose: similar to Context, but additionally prints the variables currently
290 312 # visible where the exception happened (shortening their strings if too
291 313 # long). This can potentially be very slow, if you happen to have a huge data
292 314 # structure whose string representation is complex to compute. Your computer
293 315 # may appear to freeze for a while with cpu usage at 100%. If this occurs, you
294 316 # can cancel the traceback with Ctrl-C (maybe hitting it more than once).
295 317
296 318 #xmode Plain
297 319 xmode Context
298 320 #xmode Verbose
299 321
300 322 # multi_line_specials: if true, allow magics, aliases and shell escapes (via
301 323 # !cmd) to be used in multi-line input (like for loops). For example, if you
302 324 # have this active, the following is valid in IPython:
303 325 #
304 326 #In [17]: for i in range(3):
305 327 # ....: mkdir $i
306 328 # ....: !touch $i/hello
307 329 # ....: ls -l $i
308 330
309 331 multi_line_specials 1
310 332
311 333 #---------------------------------------------------------------------------
312 334 # Section: Readline configuration (readline is not available for MS-Windows)
313 335
314 336 # This is done via the following options:
315 337
316 338 # (i) readline_parse_and_bind: this option can appear as many times as you
317 339 # want, each time defining a string to be executed via a
318 340 # readline.parse_and_bind() command. The syntax for valid commands of this
319 341 # kind can be found by reading the documentation for the GNU readline library,
320 342 # as these commands are of the kind which readline accepts in its
321 343 # configuration file.
322 344
323 345 # The TAB key can be used to complete names at the command line in one of two
324 346 # ways: 'complete' and 'menu-complete'. The difference is that 'complete' only
325 347 # completes as much as possible while 'menu-complete' cycles through all
326 348 # possible completions. Leave the one you prefer uncommented.
327 349
328 350 readline_parse_and_bind tab: complete
329 351 #readline_parse_and_bind tab: menu-complete
330 352
331 353 # This binds Control-l to printing the list of all possible completions when
332 354 # there is more than one (what 'complete' does when hitting TAB twice, or at
333 355 # the first TAB if show-all-if-ambiguous is on)
334 356 readline_parse_and_bind "\C-l": possible-completions
335 357
336 358 # This forces readline to automatically print the above list when tab
337 359 # completion is set to 'complete'. You can still get this list manually by
338 360 # using the key bound to 'possible-completions' (Control-l by default) or by
339 361 # hitting TAB twice. Turning this on makes the printing happen at the first
340 362 # TAB.
341 363 readline_parse_and_bind set show-all-if-ambiguous on
342 364
343 365 # If you have TAB set to complete names, you can rebind any key (Control-o by
344 366 # default) to insert a true TAB character.
345 367 readline_parse_and_bind "\C-o": tab-insert
346 368
347 369 # These commands allow you to indent/unindent easily, with the 4-space
348 370 # convention of the Python coding standards. Since IPython's internal
349 371 # auto-indent system also uses 4 spaces, you should not change the number of
350 372 # spaces in the code below.
351 373 readline_parse_and_bind "\M-i": " "
352 374 readline_parse_and_bind "\M-o": "\d\d\d\d"
353 375 readline_parse_and_bind "\M-I": "\d\d\d\d"
354 376
355 377 # Bindings for incremental searches in the history. These searches use the
356 378 # string typed so far on the command line and search anything in the previous
357 379 # input history containing them.
358 380 readline_parse_and_bind "\C-r": reverse-search-history
359 381 readline_parse_and_bind "\C-s": forward-search-history
360 382
361 383 # Bindings for completing the current line in the history of previous
362 384 # commands. This allows you to recall any previous command by typing its first
363 385 # few letters and hitting Control-p, bypassing all intermediate commands which
364 386 # may be in the history (much faster than hitting up-arrow 50 times!)
365 387 readline_parse_and_bind "\C-p": history-search-backward
366 388 readline_parse_and_bind "\C-n": history-search-forward
367 389
368 390 # I also like to have the same functionality on the plain arrow keys. If you'd
369 391 # rather have the arrows use all the history (and not just match what you've
370 392 # typed so far), comment out or delete the next two lines.
371 393 readline_parse_and_bind "\e[A": history-search-backward
372 394 readline_parse_and_bind "\e[B": history-search-forward
373 395
374 396 # These are typically on by default under *nix, but not win32.
375 397 readline_parse_and_bind "\C-k": kill-line
376 398 readline_parse_and_bind "\C-u": unix-line-discard
377 399
378 400 # (ii) readline_remove_delims: a string of characters to be removed from the
379 401 # default word-delimiters list used by readline, so that completions may be
380 402 # performed on strings which contain them.
381 403
382 404 readline_remove_delims -/~
383 405
384 406 # (iii) readline_merge_completions: whether to merge the result of all
385 407 # possible completions or not. If true, IPython will complete filenames,
386 408 # python names and aliases and return all possible completions. If you set it
387 409 # to false, each completer is used at a time, and only if it doesn't return
388 410 # any completions is the next one used.
389 411
390 412 # The default order is: [python_matches, file_matches, alias_matches]
391 413
392 414 readline_merge_completions 1
393 415
394 416 # (iv) readline_omit__names: normally hitting <tab> after a '.' in a name
395 417 # will complete all attributes of an object, including all the special methods
396 418 # whose names start with single or double underscores (like __getitem__ or
397 419 # __class__).
398 420
399 421 # This variable allows you to control this completion behavior:
400 422
401 423 # readline_omit__names 1 -> completion will omit showing any names starting
402 424 # with two __, but it will still show names starting with one _.
403 425
404 426 # readline_omit__names 2 -> completion will omit all names beginning with one
405 427 # _ (which obviously means filtering out the double __ ones).
406 428
407 429 # Even when this option is set, you can still see those names by explicitly
408 430 # typing a _ after the period and hitting <tab>: 'name._<tab>' will always
409 431 # complete attribute names starting with '_'.
410 432
411 433 # This option is off by default so that new users see all attributes of any
412 434 # objects they are dealing with.
413 435
414 436 readline_omit__names 0
415 437
416 438 #---------------------------------------------------------------------------
417 439 # Section: modules to be loaded with 'import ...'
418 440
419 441 # List, separated by spaces, the names of the modules you want to import
420 442
421 443 # Example:
422 444 # import_mod sys os
423 445 # will produce internally the statements
424 446 # import sys
425 447 # import os
426 448
427 449 # Each import is executed in its own try/except block, so if one module
428 450 # fails to load the others will still be ok.
429 451
430 452 import_mod
431 453
432 454 #---------------------------------------------------------------------------
433 455 # Section: modules to import some functions from: 'from ... import ...'
434 456
435 457 # List, one per line, the modules for which you want only to import some
436 458 # functions. Give the module name first and then the name of functions to be
437 459 # imported from that module.
438 460
439 461 # Example:
440 462
441 463 # import_some IPython.genutils timing timings
442 464 # will produce internally the statement
443 465 # from IPython.genutils import timing, timings
444 466
445 467 # timing() and timings() are two IPython utilities for timing the execution of
446 468 # your own functions, which you may find useful. Just commment out the above
447 469 # line if you want to test them.
448 470
449 471 # If you have more than one modules_some line, each gets its own try/except
450 472 # block (like modules, see above).
451 473
452 474 import_some
453 475
454 476 #---------------------------------------------------------------------------
455 477 # Section: modules to import all from : 'from ... import *'
456 478
457 479 # List (same syntax as import_mod above) those modules for which you want to
458 480 # import all functions. Remember, this is a potentially dangerous thing to do,
459 481 # since it is very easy to overwrite names of things you need. Use with
460 482 # caution.
461 483
462 484 # Example:
463 485 # import_all sys os
464 486 # will produce internally the statements
465 487 # from sys import *
466 488 # from os import *
467 489
468 490 # As before, each will be called in a separate try/except block.
469 491
470 492 import_all
471 493
472 494 #---------------------------------------------------------------------------
473 495 # Section: Python code to execute.
474 496
475 497 # Put here code to be explicitly executed (keep it simple!)
476 498 # Put one line of python code per line. All whitespace is removed (this is a
477 499 # feature, not a bug), so don't get fancy building loops here.
478 500 # This is just for quick convenient creation of things you want available.
479 501
480 502 # Example:
481 503 # execute x = 1
482 504 # execute print 'hello world'; y = z = 'a'
483 505 # will produce internally
484 506 # x = 1
485 507 # print 'hello world'; y = z = 'a'
486 508 # and each *line* (not each statement, we don't do python syntax parsing) is
487 509 # executed in its own try/except block.
488 510
489 511 execute
490 512
491 513 # Note for the adventurous: you can use this to define your own names for the
492 514 # magic functions, by playing some namespace tricks:
493 515
494 516 # execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
495 517
496 518 # defines @pf as a new name for @profile.
497 519
498 520 #---------------------------------------------------------------------------
499 521 # Section: Pyhton files to load and execute.
500 522
501 523 # Put here the full names of files you want executed with execfile(file). If
502 524 # you want complicated initialization, just write whatever you want in a
503 525 # regular python file and load it from here.
504 526
505 527 # Filenames defined here (which *must* include the extension) are searched for
506 528 # through all of sys.path. Since IPython adds your .ipython directory to
507 529 # sys.path, they can also be placed in your .ipython dir and will be
508 530 # found. Otherwise (if you want to execute things not in .ipyton nor in
509 531 # sys.path) give a full path (you can use ~, it gets expanded)
510 532
511 533 # Example:
512 534 # execfile file1.py ~/file2.py
513 535 # will generate
514 536 # execfile('file1.py')
515 537 # execfile('_path_to_your_home/file2.py')
516 538
517 539 # As before, each file gets its own try/except block.
518 540
519 541 execfile
520 542
521 543 # If you are feeling adventurous, you can even add functionality to IPython
522 544 # through here. IPython works through a global variable called __ip which
523 545 # exists at the time when these files are read. If you know what you are doing
524 546 # (read the source) you can add functions to __ip in files loaded here.
525 547
526 548 # The file example-magic.py contains a simple but correct example. Try it:
527 549
528 550 # execfile example-magic.py
529 551
530 552 # Look at the examples in IPython/iplib.py for more details on how these magic
531 553 # functions need to process their arguments.
532 554
533 555 #---------------------------------------------------------------------------
534 556 # Section: aliases for system shell commands
535 557
536 558 # Here you can define your own names for system commands. The syntax is
537 559 # similar to that of the builtin @alias function:
538 560
539 561 # alias alias_name command_string
540 562
541 563 # The resulting aliases are auto-generated magic functions (hence usable as
542 564 # @alias_name)
543 565
544 566 # For example:
545 567
546 568 # alias myls ls -la
547 569
548 570 # will define 'myls' as an alias for executing the system command 'ls -la'.
549 571 # This allows you to customize IPython's environment to have the same aliases
550 572 # you are accustomed to from your own shell.
551 573
552 574 # You can also define aliases with parameters using %s specifiers (one per
553 575 # parameter):
554 576
555 577 # alias parts echo first %s second %s
556 578
557 579 # will give you in IPython:
558 580 # >>> @parts A B
559 581 # first A second B
560 582
561 583 # Use one 'alias' statement per alias you wish to define.
562 584
563 585 # alias
564 586
565 587 #************************* end of file <ipythonrc> ************************
@@ -1,539 +1,556 b''
1 1 """Word completion for IPython.
2 2
3 3 This module is a fork of the rlcompleter module in the Python standard
4 4 library. The original enhancements made to rlcompleter have been sent
5 5 upstream and were accepted as of Python 2.3, but we need a lot more
6 6 functionality specific to IPython, so this module will continue to live as an
7 7 IPython-specific utility.
8 8
9 9 ---------------------------------------------------------------------------
10 10 Original rlcompleter documentation:
11 11
12 12 This requires the latest extension to the readline module (the
13 13 completes keywords, built-ins and globals in __main__; when completing
14 14 NAME.NAME..., it evaluates (!) the expression up to the last dot and
15 15 completes its attributes.
16 16
17 17 It's very cool to do "import string" type "string.", hit the
18 18 completion key (twice), and see the list of names defined by the
19 19 string module!
20 20
21 21 Tip: to use the tab key as the completion key, call
22 22
23 23 readline.parse_and_bind("tab: complete")
24 24
25 25 Notes:
26 26
27 27 - Exceptions raised by the completer function are *ignored* (and
28 28 generally cause the completion to fail). This is a feature -- since
29 29 readline sets the tty device in raw (or cbreak) mode, printing a
30 30 traceback wouldn't work well without some complicated hoopla to save,
31 31 reset and restore the tty state.
32 32
33 33 - The evaluation of the NAME.NAME... form may cause arbitrary
34 34 application defined code to be executed if an object with a
35 35 __getattr__ hook is found. Since it is the responsibility of the
36 36 application (or the user) to enable this feature, I consider this an
37 37 acceptable risk. More complicated expressions (e.g. function calls or
38 38 indexing operations) are *not* evaluated.
39 39
40 40 - GNU readline is also used by the built-in functions input() and
41 41 raw_input(), and thus these also benefit/suffer from the completer
42 42 features. Clearly an interactive application can benefit by
43 43 specifying its own completer function and using raw_input() for all
44 44 its input.
45 45
46 46 - When the original stdin is not a tty device, GNU readline is never
47 47 used, and this module (and the readline module) are silently inactive.
48 48
49 49 """
50 50
51 51 #*****************************************************************************
52 52 #
53 53 # Since this file is essentially a minimally modified copy of the rlcompleter
54 54 # module which is part of the standard Python distribution, I assume that the
55 55 # proper procedure is to maintain its copyright as belonging to the Python
56 56 # Software Foundation (in addition to my own, for all new code).
57 57 #
58 58 # Copyright (C) 2001 Python Software Foundation, www.python.org
59 59 # Copyright (C) 2001-2005 Fernando Perez. <fperez@colorado.edu>
60 60 #
61 61 # Distributed under the terms of the BSD License. The full license is in
62 62 # the file COPYING, distributed as part of this software.
63 63 #
64 64 #*****************************************************************************
65 65
66 66 import __builtin__
67 67 import __main__
68 68 import glob
69 69 import keyword
70 70 import os
71 71 import re
72 72 import readline
73 73 import sys
74 74 import types
75 75
76 # Python 2.4 offers sets as a builtin
77 try:
78 set([1,2])
79 except NameError:
80 from sets import Set as set
81
82
76 83 from IPython.genutils import shlex_split
77 84
78 85 __all__ = ['Completer','IPCompleter']
79 86
80 87 def get_class_members(cls):
81 88 ret = dir(cls)
82 89 if hasattr(cls,'__bases__'):
83 90 for base in cls.__bases__:
84 91 ret.extend(get_class_members(base))
85 92 return ret
86 93
87 94 class Completer:
88 95 def __init__(self,namespace=None,global_namespace=None):
89 96 """Create a new completer for the command line.
90 97
91 98 Completer([namespace,global_namespace]) -> completer instance.
92 99
93 100 If unspecified, the default namespace where completions are performed
94 101 is __main__ (technically, __main__.__dict__). Namespaces should be
95 102 given as dictionaries.
96 103
97 104 An optional second namespace can be given. This allows the completer
98 105 to handle cases where both the local and global scopes need to be
99 106 distinguished.
100 107
101 108 Completer instances should be used as the completion mechanism of
102 109 readline via the set_completer() call:
103 110
104 111 readline.set_completer(Completer(my_namespace).complete)
105 112 """
106 113
107 114 # some minimal strict typechecks. For some core data structures, I
108 115 # want actual basic python types, not just anything that looks like
109 116 # one. This is especially true for namespaces.
110 117 for ns in (namespace,global_namespace):
111 118 if ns is not None and type(ns) != types.DictType:
112 119 raise TypeError,'namespace must be a dictionary'
113 120
114 121 # Don't bind to namespace quite yet, but flag whether the user wants a
115 122 # specific namespace or to use __main__.__dict__. This will allow us
116 123 # to bind to __main__.__dict__ at completion time, not now.
117 124 if namespace is None:
118 125 self.use_main_ns = 1
119 126 else:
120 127 self.use_main_ns = 0
121 128 self.namespace = namespace
122 129
123 130 # The global namespace, if given, can be bound directly
124 131 if global_namespace is None:
125 132 self.global_namespace = {}
126 133 else:
127 134 self.global_namespace = global_namespace
128 135
129 136 def complete(self, text, state):
130 137 """Return the next possible completion for 'text'.
131 138
132 139 This is called successively with state == 0, 1, 2, ... until it
133 140 returns None. The completion should begin with 'text'.
134 141
135 142 """
136 143 if self.use_main_ns:
137 144 self.namespace = __main__.__dict__
138 145
139 146 if state == 0:
140 147 if "." in text:
141 148 self.matches = self.attr_matches(text)
142 149 else:
143 150 self.matches = self.global_matches(text)
144 151 try:
145 152 return self.matches[state]
146 153 except IndexError:
147 154 return None
148 155
149 156 def global_matches(self, text):
150 157 """Compute matches when text is a simple name.
151 158
152 159 Return a list of all keywords, built-in functions and names currently
153 160 defined in self.namespace or self.global_namespace that match.
154 161
155 162 """
156 163 matches = []
157 164 match_append = matches.append
158 165 n = len(text)
159 166 for lst in [keyword.kwlist,
160 167 __builtin__.__dict__.keys(),
161 168 self.namespace.keys(),
162 169 self.global_namespace.keys()]:
163 170 for word in lst:
164 171 if word[:n] == text and word != "__builtins__":
165 172 match_append(word)
166 173 return matches
167 174
168 175 def attr_matches(self, text):
169 176 """Compute matches when text contains a dot.
170 177
171 178 Assuming the text is of the form NAME.NAME....[NAME], and is
172 179 evaluatable in self.namespace or self.global_namespace, it will be
173 180 evaluated and its attributes (as revealed by dir()) are used as
174 181 possible completions. (For class instances, class members are are
175 182 also considered.)
176 183
177 184 WARNING: this can still invoke arbitrary C code, if an object
178 185 with a __getattr__ hook is evaluated.
179 186
180 187 """
181 188 import re
182 189
183 190 # Another option, seems to work great. Catches things like ''.<tab>
184 191 m = re.match(r"(\S+(\.\w+)*)\.(\w*)$", text)
185 192
186 193 if not m:
187 194 return []
188 195
189 196 expr, attr = m.group(1, 3)
190 197 try:
191 198 object = eval(expr, self.namespace)
192 199 except:
193 200 object = eval(expr, self.global_namespace)
194 201
202 # Start building the attribute list via dir(), and then complete it
203 # with a few extra special-purpose calls.
195 204 words = dir(object)
205
196 206 if hasattr(object,'__class__'):
197 207 words.append('__class__')
198 208 words.extend(get_class_members(object.__class__))
199 209
210 # this is the 'dir' function for objects with Enthought's traits
211 if hasattr(object, 'trait_names'):
212 words.extend(object.trait_names())
213 # eliminate possible duplicates, as some traits may also appear as
214 # normal attributes in the dir() call.
215 words = set(words)
216
200 217 # filter out non-string attributes which may be stuffed by dir() calls
201 218 # and poor coding in third-party modules
202 219 words = [w for w in words
203 220 if isinstance(w, basestring) and w != "__builtins__"]
204 221 # Build match list to return
205 222 n = len(attr)
206 223 return ["%s.%s" % (expr, w) for w in words if w[:n] == attr ]
207 224
208 225 class IPCompleter(Completer):
209 226 """Extension of the completer class with IPython-specific features"""
210 227
211 228 def __init__(self,shell,namespace=None,global_namespace=None,
212 229 omit__names=0,alias_table=None):
213 230 """IPCompleter() -> completer
214 231
215 232 Return a completer object suitable for use by the readline library
216 233 via readline.set_completer().
217 234
218 235 Inputs:
219 236
220 237 - shell: a pointer to the ipython shell itself. This is needed
221 238 because this completer knows about magic functions, and those can
222 239 only be accessed via the ipython instance.
223 240
224 241 - namespace: an optional dict where completions are performed.
225 242
226 243 - global_namespace: secondary optional dict for completions, to
227 244 handle cases (such as IPython embedded inside functions) where
228 245 both Python scopes are visible.
229 246
230 247 - The optional omit__names parameter sets the completer to omit the
231 248 'magic' names (__magicname__) for python objects unless the text
232 249 to be completed explicitly starts with one or more underscores.
233 250
234 251 - If alias_table is supplied, it should be a dictionary of aliases
235 252 to complete. """
236 253
237 254 Completer.__init__(self,namespace,global_namespace)
238 255 self.magic_prefix = shell.name+'.magic_'
239 256 self.magic_escape = shell.ESC_MAGIC
240 257 self.readline = readline
241 258 delims = self.readline.get_completer_delims()
242 259 delims = delims.replace(self.magic_escape,'')
243 260 self.readline.set_completer_delims(delims)
244 261 self.get_line_buffer = self.readline.get_line_buffer
245 262 self.omit__names = omit__names
246 263 self.merge_completions = shell.rc.readline_merge_completions
247 264
248 265 if alias_table is None:
249 266 alias_table = {}
250 267 self.alias_table = alias_table
251 268 # Regexp to split filenames with spaces in them
252 269 self.space_name_re = re.compile(r'([^\\] )')
253 270 # Hold a local ref. to glob.glob for speed
254 271 self.glob = glob.glob
255 272
256 273 # Determine if we are running on 'dumb' terminals, like (X)Emacs
257 274 # buffers, to avoid completion problems.
258 275 term = os.environ.get('TERM','xterm')
259 276 self.dumb_terminal = term in ['dumb','emacs']
260 277
261 278 # Special handling of backslashes needed in win32 platforms
262 279 if sys.platform == "win32":
263 280 self.clean_glob = self._clean_glob_win32
264 281 else:
265 282 self.clean_glob = self._clean_glob
266 283 self.matchers = [self.python_matches,
267 284 self.file_matches,
268 285 self.alias_matches,
269 286 self.python_func_kw_matches]
270 287
271 288 # Code contributed by Alex Schmolck, for ipython/emacs integration
272 289 def all_completions(self, text):
273 290 """Return all possible completions for the benefit of emacs."""
274 291
275 292 completions = []
276 293 comp_append = completions.append
277 294 try:
278 295 for i in xrange(sys.maxint):
279 296 res = self.complete(text, i)
280 297
281 298 if not res: break
282 299
283 300 comp_append(res)
284 301 #XXX workaround for ``notDefined.<tab>``
285 302 except NameError:
286 303 pass
287 304 return completions
288 305 # /end Alex Schmolck code.
289 306
290 307 def _clean_glob(self,text):
291 308 return self.glob("%s*" % text)
292 309
293 310 def _clean_glob_win32(self,text):
294 311 return [f.replace("\\","/")
295 312 for f in self.glob("%s*" % text)]
296 313
297 314 def file_matches(self, text):
298 315 """Match filneames, expanding ~USER type strings.
299 316
300 317 Most of the seemingly convoluted logic in this completer is an
301 318 attempt to handle filenames with spaces in them. And yet it's not
302 319 quite perfect, because Python's readline doesn't expose all of the
303 320 GNU readline details needed for this to be done correctly.
304 321
305 322 For a filename with a space in it, the printed completions will be
306 323 only the parts after what's already been typed (instead of the
307 324 full completions, as is normally done). I don't think with the
308 325 current (as of Python 2.3) Python readline it's possible to do
309 326 better."""
310 327
311 328 #print 'Completer->file_matches: <%s>' % text # dbg
312 329
313 330 # chars that require escaping with backslash - i.e. chars
314 331 # that readline treats incorrectly as delimiters, but we
315 332 # don't want to treat as delimiters in filename matching
316 333 # when escaped with backslash
317 334
318 335 protectables = ' ()[]{}'
319 336
320 337 def protect_filename(s):
321 338 return "".join([(ch in protectables and '\\' + ch or ch)
322 339 for ch in s])
323 340
324 341 lbuf = self.get_line_buffer()[:self.readline.get_endidx()]
325 342 open_quotes = 0 # track strings with open quotes
326 343 try:
327 344 lsplit = shlex_split(lbuf)[-1]
328 345 except ValueError:
329 346 # typically an unmatched ", or backslash without escaped char.
330 347 if lbuf.count('"')==1:
331 348 open_quotes = 1
332 349 lsplit = lbuf.split('"')[-1]
333 350 elif lbuf.count("'")==1:
334 351 open_quotes = 1
335 352 lsplit = lbuf.split("'")[-1]
336 353 else:
337 354 return None
338 355 except IndexError:
339 356 # tab pressed on empty line
340 357 lsplit = ""
341 358
342 359 if lsplit != protect_filename(lsplit):
343 360 # if protectables are found, do matching on the whole escaped
344 361 # name
345 362 has_protectables = 1
346 363 text0,text = text,lsplit
347 364 else:
348 365 has_protectables = 0
349 366 text = os.path.expanduser(text)
350 367
351 368 if text == "":
352 369 return [protect_filename(f) for f in self.glob("*")]
353 370
354 371 m0 = self.clean_glob(text.replace('\\',''))
355 372 if has_protectables:
356 373 # If we had protectables, we need to revert our changes to the
357 374 # beginning of filename so that we don't double-write the part
358 375 # of the filename we have so far
359 376 len_lsplit = len(lsplit)
360 377 matches = [text0 + protect_filename(f[len_lsplit:]) for f in m0]
361 378 else:
362 379 if open_quotes:
363 380 # if we have a string with an open quote, we don't need to
364 381 # protect the names at all (and we _shouldn't_, as it
365 382 # would cause bugs when the filesystem call is made).
366 383 matches = m0
367 384 else:
368 385 matches = [protect_filename(f) for f in m0]
369 386 if len(matches) == 1 and os.path.isdir(matches[0]):
370 387 # Takes care of links to directories also. Use '/'
371 388 # explicitly, even under Windows, so that name completions
372 389 # don't end up escaped.
373 390 matches[0] += '/'
374 391 return matches
375 392
376 393 def alias_matches(self, text):
377 394 """Match internal system aliases"""
378 395 #print 'Completer->alias_matches:',text # dbg
379 396 text = os.path.expanduser(text)
380 397 aliases = self.alias_table.keys()
381 398 if text == "":
382 399 return aliases
383 400 else:
384 401 return [alias for alias in aliases if alias.startswith(text)]
385 402
386 403 def python_matches(self,text):
387 404 """Match attributes or global python names"""
388 405 #print 'Completer->python_matches' # dbg
389 406 if "." in text:
390 407 try:
391 408 matches = self.attr_matches(text)
392 409 if text.endswith('.') and self.omit__names:
393 410 if self.omit__names == 1:
394 411 # true if txt is _not_ a __ name, false otherwise:
395 412 no__name = (lambda txt:
396 413 re.match(r'.*\.__.*?__',txt) is None)
397 414 else:
398 415 # true if txt is _not_ a _ name, false otherwise:
399 416 no__name = (lambda txt:
400 417 re.match(r'.*\._.*?',txt) is None)
401 418 matches = filter(no__name, matches)
402 419 except NameError:
403 420 # catches <undefined attributes>.<tab>
404 421 matches = []
405 422 else:
406 423 matches = self.global_matches(text)
407 424 # this is so completion finds magics when automagic is on:
408 425 if matches == [] and not text.startswith(os.sep):
409 426 matches = self.attr_matches(self.magic_prefix+text)
410 427 return matches
411 428
412 429 def _default_arguments(self, obj):
413 430 """Return the list of default arguments of obj if it is callable,
414 431 or empty list otherwise."""
415 432
416 433 if not (inspect.isfunction(obj) or inspect.ismethod(obj)):
417 434 # for classes, check for __init__,__new__
418 435 if inspect.isclass(obj):
419 436 obj = (getattr(obj,'__init__',None) or
420 437 getattr(obj,'__new__',None))
421 438 # for all others, check if they are __call__able
422 439 elif hasattr(obj, '__call__'):
423 440 obj = obj.__call__
424 441 # XXX: is there a way to handle the builtins ?
425 442 try:
426 443 args,_,_1,defaults = inspect.getargspec(obj)
427 444 if defaults:
428 445 return args[-len(defaults):]
429 446 except TypeError: pass
430 447 return []
431 448
432 449 def python_func_kw_matches(self,text):
433 450 """Match named parameters (kwargs) of the last open function"""
434 451
435 452 if "." in text: # a parameter cannot be dotted
436 453 return []
437 454 try: regexp = self.__funcParamsRegex
438 455 except AttributeError:
439 456 regexp = self.__funcParamsRegex = re.compile(r'''
440 457 '.*?' | # single quoted strings or
441 458 ".*?" | # double quoted strings or
442 459 \w+ | # identifier
443 460 \S # other characters
444 461 ''', re.VERBOSE | re.DOTALL)
445 462 # 1. find the nearest identifier that comes before an unclosed
446 463 # parenthesis e.g. for "foo (1+bar(x), pa", the candidate is "foo"
447 464 tokens = regexp.findall(self.get_line_buffer())
448 465 tokens.reverse()
449 466 iterTokens = iter(tokens); openPar = 0
450 467 for token in iterTokens:
451 468 if token == ')':
452 469 openPar -= 1
453 470 elif token == '(':
454 471 openPar += 1
455 472 if openPar > 0:
456 473 # found the last unclosed parenthesis
457 474 break
458 475 else:
459 476 return []
460 477 # 2. Concatenate dotted names ("foo.bar" for "foo.bar(x, pa" )
461 478 ids = []
462 479 isId = re.compile(r'\w+$').match
463 480 while True:
464 481 try:
465 482 ids.append(iterTokens.next())
466 483 if not isId(ids[-1]):
467 484 ids.pop(); break
468 485 if not iterTokens.next() == '.':
469 486 break
470 487 except StopIteration:
471 488 break
472 489 # lookup the candidate callable matches either using global_matches
473 490 # or attr_matches for dotted names
474 491 if len(ids) == 1:
475 492 callableMatches = self.global_matches(ids[0])
476 493 else:
477 494 callableMatches = self.attr_matches('.'.join(ids[::-1]))
478 495 argMatches = []
479 496 for callableMatch in callableMatches:
480 497 try: namedArgs = self._default_arguments(eval(callableMatch,
481 498 self.namespace))
482 499 except: continue
483 500 for namedArg in namedArgs:
484 501 if namedArg.startswith(text):
485 502 argMatches.append("%s=" %namedArg)
486 503 return argMatches
487 504
488 505 def complete(self, text, state):
489 506 """Return the next possible completion for 'text'.
490 507
491 508 This is called successively with state == 0, 1, 2, ... until it
492 509 returns None. The completion should begin with 'text'. """
493 510
494 511 #print '\n*** COMPLETE: <%s> (%s)' % (text,state) # dbg
495 512
496 513 # if there is only a tab on a line with only whitespace, instead
497 514 # of the mostly useless 'do you want to see all million
498 515 # completions' message, just do the right thing and give the user
499 516 # his tab! Incidentally, this enables pasting of tabbed text from
500 517 # an editor (as long as autoindent is off).
501 518
502 519 # don't apply this on 'dumb' terminals, such as emacs buffers, so we
503 520 # don't interfere with their own tab-completion mechanism.
504 521 if not (self.dumb_terminal or self.get_line_buffer().strip()):
505 522 self.readline.insert_text('\t')
506 523 return None
507 524
508 525 magic_escape = self.magic_escape
509 526 magic_prefix = self.magic_prefix
510 527
511 528 try:
512 529 if text.startswith(magic_escape):
513 530 text = text.replace(magic_escape,magic_prefix)
514 531 elif text.startswith('~'):
515 532 text = os.path.expanduser(text)
516 533 if state == 0:
517 534 # Extend the list of completions with the results of each
518 535 # matcher, so we return results to the user from all
519 536 # namespaces.
520 537 if self.merge_completions:
521 538 self.matches = []
522 539 for matcher in self.matchers:
523 540 self.matches.extend(matcher(text))
524 541 else:
525 542 for matcher in self.matchers:
526 543 self.matches = matcher(text)
527 544 if self.matches:
528 545 break
529 546
530 547 try:
531 548 return self.matches[state].replace(magic_prefix,magic_escape)
532 549 except IndexError:
533 550 return None
534 551 except:
535 552 #from IPython.ultraTB import AutoFormattedTB; # dbg
536 553 #tb=AutoFormattedTB('Verbose');tb() #dbg
537 554
538 555 # If completion fails, don't annoy the user.
539 556 return None
@@ -1,1705 +1,1717 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 980 2005-12-30 15:42:04Z fperez $"""
8 $Id: genutils.py 990 2006-01-04 06:59:02Z fperez $"""
9 9
10 10 #*****************************************************************************
11 11 # Copyright (C) 2001-2004 Fernando Perez. <fperez@colorado.edu>
12 12 #
13 13 # Distributed under the terms of the BSD License. The full license is in
14 14 # the file COPYING, distributed as part of this software.
15 15 #*****************************************************************************
16 16
17 17 from __future__ import generators # 2.2 compatibility
18 18
19 19 from IPython import Release
20 20 __author__ = '%s <%s>' % Release.authors['Fernando']
21 21 __license__ = Release.license
22 22
23 23 #****************************************************************************
24 24 # required modules from the Python standard library
25 25 import __main__
26 26 import commands
27 27 import os
28 28 import re
29 29 import shlex
30 30 import shutil
31 31 import sys
32 32 import tempfile
33 33 import time
34 34 import types
35 35
36 36 # Other IPython utilities
37 37 from IPython.Itpl import Itpl,itpl,printpl
38 38 from IPython import DPyGetOpt
39 39
40 40 if os.name == "nt":
41 41 from IPython.winconsole import get_console_size
42 42
43 43 # Build objects which appeared in Python 2.3 for 2.2, to make ipython
44 44 # 2.2-friendly
45 45 try:
46 46 basestring
47 47 except NameError:
48 48 import types
49 49 basestring = (types.StringType, types.UnicodeType)
50 50 True = 1==1
51 51 False = 1==0
52 52
53 53 def enumerate(obj):
54 54 i = -1
55 55 for item in obj:
56 56 i += 1
57 57 yield i, item
58 58
59 59 # add these to the builtin namespace, so that all modules find them
60 60 import __builtin__
61 61 __builtin__.basestring = basestring
62 62 __builtin__.True = True
63 63 __builtin__.False = False
64 64 __builtin__.enumerate = enumerate
65 65
66 66 # Try to use shlex.split for converting an input string into a sys.argv-type
67 67 # list. This appeared in Python 2.3, so here's a quick backport for 2.2.
68 68 try:
69 69 shlex_split = shlex.split
70 70 except AttributeError:
71 71 _quotesre = re.compile(r'[\'"](.*)[\'"]')
72 72 _wordchars = ('abcdfeghijklmnopqrstuvwxyz'
73 73 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-.~*?'
74 74 'ßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþÿ'
75 75 'ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞ%s'
76 76 % os.sep)
77 77
78 78 def shlex_split(s):
79 79 """Simplified backport to Python 2.2 of shlex.split().
80 80
81 81 This is a quick and dirty hack, since the shlex module under 2.2 lacks
82 82 several of the features needed to really match the functionality of
83 83 shlex.split() in 2.3."""
84 84
85 85 lex = shlex.shlex(StringIO(s))
86 86 # Try to get options, extensions and path separators as characters
87 87 lex.wordchars = _wordchars
88 88 lex.commenters = ''
89 89 # Make a list out of the lexer by hand, since in 2.2 it's not an
90 90 # iterator.
91 91 lout = []
92 92 while 1:
93 93 token = lex.get_token()
94 94 if token == '':
95 95 break
96 96 # Try to handle quoted tokens correctly
97 97 quotes = _quotesre.match(token)
98 98 if quotes:
99 99 token = quotes.group(1)
100 100 lout.append(token)
101 101 return lout
102 102
103 103 #****************************************************************************
104 104 # Exceptions
105 105 class Error(Exception):
106 106 """Base class for exceptions in this module."""
107 107 pass
108 108
109 109 #----------------------------------------------------------------------------
110 110 class IOStream:
111 111 def __init__(self,stream,fallback):
112 112 if not hasattr(stream,'write') or not hasattr(stream,'flush'):
113 113 stream = fallback
114 114 self.stream = stream
115 115 self._swrite = stream.write
116 116 self.flush = stream.flush
117 117
118 118 def write(self,data):
119 119 try:
120 120 self._swrite(data)
121 121 except:
122 122 try:
123 123 # print handles some unicode issues which may trip a plain
124 124 # write() call. Attempt to emulate write() by using a
125 125 # trailing comma
126 126 print >> self.stream, data,
127 127 except:
128 128 # if we get here, something is seriously broken.
129 129 print >> sys.stderr, \
130 130 'ERROR - failed to write data to stream:', stream
131 131
132 132 class IOTerm:
133 133 """ Term holds the file or file-like objects for handling I/O operations.
134 134
135 135 These are normally just sys.stdin, sys.stdout and sys.stderr but for
136 136 Windows they can can replaced to allow editing the strings before they are
137 137 displayed."""
138 138
139 139 # In the future, having IPython channel all its I/O operations through
140 140 # this class will make it easier to embed it into other environments which
141 141 # are not a normal terminal (such as a GUI-based shell)
142 142 def __init__(self,cin=None,cout=None,cerr=None):
143 143 self.cin = IOStream(cin,sys.stdin)
144 144 self.cout = IOStream(cout,sys.stdout)
145 145 self.cerr = IOStream(cerr,sys.stderr)
146 146
147 147 # Global variable to be used for all I/O
148 148 Term = IOTerm()
149 149
150 150 # Windows-specific code to load Gary Bishop's readline and configure it
151 151 # automatically for the users
152 152 # Note: os.name on cygwin returns posix, so this should only pick up 'native'
153 153 # windows. Cygwin returns 'cygwin' for sys.platform.
154 154 if os.name == 'nt':
155 155 try:
156 156 import readline
157 157 except ImportError:
158 158 pass
159 159 else:
160 160 try:
161 161 _out = readline.GetOutputFile()
162 162 except AttributeError:
163 163 pass
164 164 else:
165 165 # Remake Term to use the readline i/o facilities
166 166 Term = IOTerm(cout=_out,cerr=_out)
167 167 del _out
168 168
169 169 #****************************************************************************
170 170 # Generic warning/error printer, used by everything else
171 171 def warn(msg,level=2,exit_val=1):
172 172 """Standard warning printer. Gives formatting consistency.
173 173
174 174 Output is sent to Term.cerr (sys.stderr by default).
175 175
176 176 Options:
177 177
178 178 -level(2): allows finer control:
179 179 0 -> Do nothing, dummy function.
180 180 1 -> Print message.
181 181 2 -> Print 'WARNING:' + message. (Default level).
182 182 3 -> Print 'ERROR:' + message.
183 183 4 -> Print 'FATAL ERROR:' + message and trigger a sys.exit(exit_val).
184 184
185 185 -exit_val (1): exit value returned by sys.exit() for a level 4
186 186 warning. Ignored for all other levels."""
187 187
188 188 if level>0:
189 189 header = ['','','WARNING: ','ERROR: ','FATAL ERROR: ']
190 190 print >> Term.cerr, '%s%s' % (header[level],msg)
191 191 if level == 4:
192 192 print >> Term.cerr,'Exiting.\n'
193 193 sys.exit(exit_val)
194 194
195 195 def info(msg):
196 196 """Equivalent to warn(msg,level=1)."""
197 197
198 198 warn(msg,level=1)
199 199
200 200 def error(msg):
201 201 """Equivalent to warn(msg,level=3)."""
202 202
203 203 warn(msg,level=3)
204 204
205 205 def fatal(msg,exit_val=1):
206 206 """Equivalent to warn(msg,exit_val=exit_val,level=4)."""
207 207
208 208 warn(msg,exit_val=exit_val,level=4)
209 209
210
211 # useful for debugging
212 def debugp(expr):
213 """Print the value of an expression from the caller's frame.
214
215 Takes an expression, evaluates it in the caller's frame and prints both
216 the given expression and the resulting value. The input must be of a form
217 suitable for eval()."""
218
219 cf = sys._getframe(1)
220 print '[DBG] %s -> %r' % (expr,eval(expr,cf.f_globals,cf.f_locals))
221
210 222 #----------------------------------------------------------------------------
211 223 StringTypes = types.StringTypes
212 224
213 225 # Basic timing functionality
214 226
215 227 # If possible (Unix), use the resource module instead of time.clock()
216 228 try:
217 229 import resource
218 230 def clock():
219 231 """clock() -> floating point number
220 232
221 233 Return the CPU time in seconds (user time only, system time is
222 234 ignored) since the start of the process. This is done via a call to
223 235 resource.getrusage, so it avoids the wraparound problems in
224 236 time.clock()."""
225 237
226 238 return resource.getrusage(resource.RUSAGE_SELF)[0]
227 239
228 240 def clock2():
229 241 """clock2() -> (t_user,t_system)
230 242
231 243 Similar to clock(), but return a tuple of user/system times."""
232 244 return resource.getrusage(resource.RUSAGE_SELF)[:2]
233 245
234 246 except ImportError:
235 247 clock = time.clock
236 248 def clock2():
237 249 """Under windows, system CPU time can't be measured.
238 250
239 251 This just returns clock() and zero."""
240 252 return time.clock(),0.0
241 253
242 254 def timings_out(reps,func,*args,**kw):
243 255 """timings_out(reps,func,*args,**kw) -> (t_total,t_per_call,output)
244 256
245 257 Execute a function reps times, return a tuple with the elapsed total
246 258 CPU time in seconds, the time per call and the function's output.
247 259
248 260 Under Unix, the return value is the sum of user+system time consumed by
249 261 the process, computed via the resource module. This prevents problems
250 262 related to the wraparound effect which the time.clock() function has.
251 263
252 264 Under Windows the return value is in wall clock seconds. See the
253 265 documentation for the time module for more details."""
254 266
255 267 reps = int(reps)
256 268 assert reps >=1, 'reps must be >= 1'
257 269 if reps==1:
258 270 start = clock()
259 271 out = func(*args,**kw)
260 272 tot_time = clock()-start
261 273 else:
262 274 rng = xrange(reps-1) # the last time is executed separately to store output
263 275 start = clock()
264 276 for dummy in rng: func(*args,**kw)
265 277 out = func(*args,**kw) # one last time
266 278 tot_time = clock()-start
267 279 av_time = tot_time / reps
268 280 return tot_time,av_time,out
269 281
270 282 def timings(reps,func,*args,**kw):
271 283 """timings(reps,func,*args,**kw) -> (t_total,t_per_call)
272 284
273 285 Execute a function reps times, return a tuple with the elapsed total CPU
274 286 time in seconds and the time per call. These are just the first two values
275 287 in timings_out()."""
276 288
277 289 return timings_out(reps,func,*args,**kw)[0:2]
278 290
279 291 def timing(func,*args,**kw):
280 292 """timing(func,*args,**kw) -> t_total
281 293
282 294 Execute a function once, return the elapsed total CPU time in
283 295 seconds. This is just the first value in timings_out()."""
284 296
285 297 return timings_out(1,func,*args,**kw)[0]
286 298
287 299 #****************************************************************************
288 300 # file and system
289 301
290 302 def system(cmd,verbose=0,debug=0,header=''):
291 303 """Execute a system command, return its exit status.
292 304
293 305 Options:
294 306
295 307 - verbose (0): print the command to be executed.
296 308
297 309 - debug (0): only print, do not actually execute.
298 310
299 311 - header (''): Header to print on screen prior to the executed command (it
300 312 is only prepended to the command, no newlines are added).
301 313
302 314 Note: a stateful version of this function is available through the
303 315 SystemExec class."""
304 316
305 317 stat = 0
306 318 if verbose or debug: print header+cmd
307 319 sys.stdout.flush()
308 320 if not debug: stat = os.system(cmd)
309 321 return stat
310 322
311 323 # This function is used by ipython in a lot of places to make system calls.
312 324 # We need it to be slightly different under win32, due to the vagaries of
313 325 # 'network shares'. A win32 override is below.
314 326
315 327 def shell(cmd,verbose=0,debug=0,header=''):
316 328 """Execute a command in the system shell, always return None.
317 329
318 330 Options:
319 331
320 332 - verbose (0): print the command to be executed.
321 333
322 334 - debug (0): only print, do not actually execute.
323 335
324 336 - header (''): Header to print on screen prior to the executed command (it
325 337 is only prepended to the command, no newlines are added).
326 338
327 339 Note: this is similar to genutils.system(), but it returns None so it can
328 340 be conveniently used in interactive loops without getting the return value
329 341 (typically 0) printed many times."""
330 342
331 343 stat = 0
332 344 if verbose or debug: print header+cmd
333 345 # flush stdout so we don't mangle python's buffering
334 346 sys.stdout.flush()
335 347 if not debug:
336 348 os.system(cmd)
337 349
338 350 # override shell() for win32 to deal with network shares
339 351 if os.name in ('nt','dos'):
340 352
341 353 shell_ori = shell
342 354
343 355 def shell(cmd,verbose=0,debug=0,header=''):
344 356 if os.getcwd().startswith(r"\\"):
345 357 path = os.getcwd()
346 358 # change to c drive (cannot be on UNC-share when issuing os.system,
347 359 # as cmd.exe cannot handle UNC addresses)
348 360 os.chdir("c:")
349 361 # issue pushd to the UNC-share and then run the command
350 362 try:
351 363 shell_ori('"pushd %s&&"'%path+cmd,verbose,debug,header)
352 364 finally:
353 365 os.chdir(path)
354 366 else:
355 367 shell_ori(cmd,verbose,debug,header)
356 368
357 369 shell.__doc__ = shell_ori.__doc__
358 370
359 371 def getoutput(cmd,verbose=0,debug=0,header='',split=0):
360 372 """Dummy substitute for perl's backquotes.
361 373
362 374 Executes a command and returns the output.
363 375
364 376 Accepts the same arguments as system(), plus:
365 377
366 378 - split(0): if true, the output is returned as a list split on newlines.
367 379
368 380 Note: a stateful version of this function is available through the
369 381 SystemExec class."""
370 382
371 383 if verbose or debug: print header+cmd
372 384 if not debug:
373 385 output = commands.getoutput(cmd)
374 386 if split:
375 387 return output.split('\n')
376 388 else:
377 389 return output
378 390
379 391 def getoutputerror(cmd,verbose=0,debug=0,header='',split=0):
380 392 """Return (standard output,standard error) of executing cmd in a shell.
381 393
382 394 Accepts the same arguments as system(), plus:
383 395
384 396 - split(0): if true, each of stdout/err is returned as a list split on
385 397 newlines.
386 398
387 399 Note: a stateful version of this function is available through the
388 400 SystemExec class."""
389 401
390 402 if verbose or debug: print header+cmd
391 403 if not cmd:
392 404 if split:
393 405 return [],[]
394 406 else:
395 407 return '',''
396 408 if not debug:
397 409 pin,pout,perr = os.popen3(cmd)
398 410 tout = pout.read().rstrip()
399 411 terr = perr.read().rstrip()
400 412 pin.close()
401 413 pout.close()
402 414 perr.close()
403 415 if split:
404 416 return tout.split('\n'),terr.split('\n')
405 417 else:
406 418 return tout,terr
407 419
408 420 # for compatibility with older naming conventions
409 421 xsys = system
410 422 bq = getoutput
411 423
412 424 class SystemExec:
413 425 """Access the system and getoutput functions through a stateful interface.
414 426
415 427 Note: here we refer to the system and getoutput functions from this
416 428 library, not the ones from the standard python library.
417 429
418 430 This class offers the system and getoutput functions as methods, but the
419 431 verbose, debug and header parameters can be set for the instance (at
420 432 creation time or later) so that they don't need to be specified on each
421 433 call.
422 434
423 435 For efficiency reasons, there's no way to override the parameters on a
424 436 per-call basis other than by setting instance attributes. If you need
425 437 local overrides, it's best to directly call system() or getoutput().
426 438
427 439 The following names are provided as alternate options:
428 440 - xsys: alias to system
429 441 - bq: alias to getoutput
430 442
431 443 An instance can then be created as:
432 444 >>> sysexec = SystemExec(verbose=1,debug=0,header='Calling: ')
433 445
434 446 And used as:
435 447 >>> sysexec.xsys('pwd')
436 448 >>> dirlist = sysexec.bq('ls -l')
437 449 """
438 450
439 451 def __init__(self,verbose=0,debug=0,header='',split=0):
440 452 """Specify the instance's values for verbose, debug and header."""
441 453 setattr_list(self,'verbose debug header split')
442 454
443 455 def system(self,cmd):
444 456 """Stateful interface to system(), with the same keyword parameters."""
445 457
446 458 system(cmd,self.verbose,self.debug,self.header)
447 459
448 460 def shell(self,cmd):
449 461 """Stateful interface to shell(), with the same keyword parameters."""
450 462
451 463 shell(cmd,self.verbose,self.debug,self.header)
452 464
453 465 xsys = system # alias
454 466
455 467 def getoutput(self,cmd):
456 468 """Stateful interface to getoutput()."""
457 469
458 470 return getoutput(cmd,self.verbose,self.debug,self.header,self.split)
459 471
460 472 def getoutputerror(self,cmd):
461 473 """Stateful interface to getoutputerror()."""
462 474
463 475 return getoutputerror(cmd,self.verbose,self.debug,self.header,self.split)
464 476
465 477 bq = getoutput # alias
466 478
467 479 #-----------------------------------------------------------------------------
468 480 def mutex_opts(dict,ex_op):
469 481 """Check for presence of mutually exclusive keys in a dict.
470 482
471 483 Call: mutex_opts(dict,[[op1a,op1b],[op2a,op2b]...]"""
472 484 for op1,op2 in ex_op:
473 485 if op1 in dict and op2 in dict:
474 486 raise ValueError,'\n*** ERROR in Arguments *** '\
475 487 'Options '+op1+' and '+op2+' are mutually exclusive.'
476 488
477 489 #-----------------------------------------------------------------------------
478 490 def get_py_filename(name):
479 491 """Return a valid python filename in the current directory.
480 492
481 493 If the given name is not a file, it adds '.py' and searches again.
482 494 Raises IOError with an informative message if the file isn't found."""
483 495
484 496 name = os.path.expanduser(name)
485 497 if not os.path.isfile(name) and not name.endswith('.py'):
486 498 name += '.py'
487 499 if os.path.isfile(name):
488 500 return name
489 501 else:
490 502 raise IOError,'File `%s` not found.' % name
491 503
492 504 #-----------------------------------------------------------------------------
493 505 def filefind(fname,alt_dirs = None):
494 506 """Return the given filename either in the current directory, if it
495 507 exists, or in a specified list of directories.
496 508
497 509 ~ expansion is done on all file and directory names.
498 510
499 511 Upon an unsuccessful search, raise an IOError exception."""
500 512
501 513 if alt_dirs is None:
502 514 try:
503 515 alt_dirs = get_home_dir()
504 516 except HomeDirError:
505 517 alt_dirs = os.getcwd()
506 518 search = [fname] + list_strings(alt_dirs)
507 519 search = map(os.path.expanduser,search)
508 520 #print 'search list for',fname,'list:',search # dbg
509 521 fname = search[0]
510 522 if os.path.isfile(fname):
511 523 return fname
512 524 for direc in search[1:]:
513 525 testname = os.path.join(direc,fname)
514 526 #print 'testname',testname # dbg
515 527 if os.path.isfile(testname):
516 528 return testname
517 529 raise IOError,'File' + `fname` + \
518 530 ' not found in current or supplied directories:' + `alt_dirs`
519 531
520 532 #----------------------------------------------------------------------------
521 533 def file_read(filename):
522 534 """Read a file and close it. Returns the file source."""
523 535 fobj=open(filename,'r');
524 536 source = fobj.read();
525 537 fobj.close()
526 538 return source
527 539
528 540 #----------------------------------------------------------------------------
529 541 def target_outdated(target,deps):
530 542 """Determine whether a target is out of date.
531 543
532 544 target_outdated(target,deps) -> 1/0
533 545
534 546 deps: list of filenames which MUST exist.
535 547 target: single filename which may or may not exist.
536 548
537 549 If target doesn't exist or is older than any file listed in deps, return
538 550 true, otherwise return false.
539 551 """
540 552 try:
541 553 target_time = os.path.getmtime(target)
542 554 except os.error:
543 555 return 1
544 556 for dep in deps:
545 557 dep_time = os.path.getmtime(dep)
546 558 if dep_time > target_time:
547 559 #print "For target",target,"Dep failed:",dep # dbg
548 560 #print "times (dep,tar):",dep_time,target_time # dbg
549 561 return 1
550 562 return 0
551 563
552 564 #-----------------------------------------------------------------------------
553 565 def target_update(target,deps,cmd):
554 566 """Update a target with a given command given a list of dependencies.
555 567
556 568 target_update(target,deps,cmd) -> runs cmd if target is outdated.
557 569
558 570 This is just a wrapper around target_outdated() which calls the given
559 571 command if target is outdated."""
560 572
561 573 if target_outdated(target,deps):
562 574 xsys(cmd)
563 575
564 576 #----------------------------------------------------------------------------
565 577 def unquote_ends(istr):
566 578 """Remove a single pair of quotes from the endpoints of a string."""
567 579
568 580 if not istr:
569 581 return istr
570 582 if (istr[0]=="'" and istr[-1]=="'") or \
571 583 (istr[0]=='"' and istr[-1]=='"'):
572 584 return istr[1:-1]
573 585 else:
574 586 return istr
575 587
576 588 #----------------------------------------------------------------------------
577 589 def process_cmdline(argv,names=[],defaults={},usage=''):
578 590 """ Process command-line options and arguments.
579 591
580 592 Arguments:
581 593
582 594 - argv: list of arguments, typically sys.argv.
583 595
584 596 - names: list of option names. See DPyGetOpt docs for details on options
585 597 syntax.
586 598
587 599 - defaults: dict of default values.
588 600
589 601 - usage: optional usage notice to print if a wrong argument is passed.
590 602
591 603 Return a dict of options and a list of free arguments."""
592 604
593 605 getopt = DPyGetOpt.DPyGetOpt()
594 606 getopt.setIgnoreCase(0)
595 607 getopt.parseConfiguration(names)
596 608
597 609 try:
598 610 getopt.processArguments(argv)
599 611 except:
600 612 print usage
601 613 warn(`sys.exc_value`,level=4)
602 614
603 615 defaults.update(getopt.optionValues)
604 616 args = getopt.freeValues
605 617
606 618 return defaults,args
607 619
608 620 #----------------------------------------------------------------------------
609 621 def optstr2types(ostr):
610 622 """Convert a string of option names to a dict of type mappings.
611 623
612 624 optstr2types(str) -> {None:'string_opts',int:'int_opts',float:'float_opts'}
613 625
614 626 This is used to get the types of all the options in a string formatted
615 627 with the conventions of DPyGetOpt. The 'type' None is used for options
616 628 which are strings (they need no further conversion). This function's main
617 629 use is to get a typemap for use with read_dict().
618 630 """
619 631
620 632 typeconv = {None:'',int:'',float:''}
621 633 typemap = {'s':None,'i':int,'f':float}
622 634 opt_re = re.compile(r'([\w]*)([^:=]*:?=?)([sif]?)')
623 635
624 636 for w in ostr.split():
625 637 oname,alias,otype = opt_re.match(w).groups()
626 638 if otype == '' or alias == '!': # simple switches are integers too
627 639 otype = 'i'
628 640 typeconv[typemap[otype]] += oname + ' '
629 641 return typeconv
630 642
631 643 #----------------------------------------------------------------------------
632 644 def read_dict(filename,type_conv=None,**opt):
633 645
634 646 """Read a dictionary of key=value pairs from an input file, optionally
635 647 performing conversions on the resulting values.
636 648
637 649 read_dict(filename,type_conv,**opt) -> dict
638 650
639 651 Only one value per line is accepted, the format should be
640 652 # optional comments are ignored
641 653 key value\n
642 654
643 655 Args:
644 656
645 657 - type_conv: A dictionary specifying which keys need to be converted to
646 658 which types. By default all keys are read as strings. This dictionary
647 659 should have as its keys valid conversion functions for strings
648 660 (int,long,float,complex, or your own). The value for each key
649 661 (converter) should be a whitespace separated string containing the names
650 662 of all the entries in the file to be converted using that function. For
651 663 keys to be left alone, use None as the conversion function (only needed
652 664 with purge=1, see below).
653 665
654 666 - opt: dictionary with extra options as below (default in parens)
655 667
656 668 purge(0): if set to 1, all keys *not* listed in type_conv are purged out
657 669 of the dictionary to be returned. If purge is going to be used, the
658 670 set of keys to be left as strings also has to be explicitly specified
659 671 using the (non-existent) conversion function None.
660 672
661 673 fs(None): field separator. This is the key/value separator to be used
662 674 when parsing the file. The None default means any whitespace [behavior
663 675 of string.split()].
664 676
665 677 strip(0): if 1, strip string values of leading/trailinig whitespace.
666 678
667 679 warn(1): warning level if requested keys are not found in file.
668 680 - 0: silently ignore.
669 681 - 1: inform but proceed.
670 682 - 2: raise KeyError exception.
671 683
672 684 no_empty(0): if 1, remove keys with whitespace strings as a value.
673 685
674 686 unique([]): list of keys (or space separated string) which can't be
675 687 repeated. If one such key is found in the file, each new instance
676 688 overwrites the previous one. For keys not listed here, the behavior is
677 689 to make a list of all appearances.
678 690
679 691 Example:
680 692 If the input file test.ini has:
681 693 i 3
682 694 x 4.5
683 695 y 5.5
684 696 s hi ho
685 697 Then:
686 698
687 699 >>> type_conv={int:'i',float:'x',None:'s'}
688 700 >>> read_dict('test.ini')
689 701 {'i': '3', 's': 'hi ho', 'x': '4.5', 'y': '5.5'}
690 702 >>> read_dict('test.ini',type_conv)
691 703 {'i': 3, 's': 'hi ho', 'x': 4.5, 'y': '5.5'}
692 704 >>> read_dict('test.ini',type_conv,purge=1)
693 705 {'i': 3, 's': 'hi ho', 'x': 4.5}
694 706 """
695 707
696 708 # starting config
697 709 opt.setdefault('purge',0)
698 710 opt.setdefault('fs',None) # field sep defaults to any whitespace
699 711 opt.setdefault('strip',0)
700 712 opt.setdefault('warn',1)
701 713 opt.setdefault('no_empty',0)
702 714 opt.setdefault('unique','')
703 715 if type(opt['unique']) in StringTypes:
704 716 unique_keys = qw(opt['unique'])
705 717 elif type(opt['unique']) in (types.TupleType,types.ListType):
706 718 unique_keys = opt['unique']
707 719 else:
708 720 raise ValueError, 'Unique keys must be given as a string, List or Tuple'
709 721
710 722 dict = {}
711 723 # first read in table of values as strings
712 724 file = open(filename,'r')
713 725 for line in file.readlines():
714 726 line = line.strip()
715 727 if len(line) and line[0]=='#': continue
716 728 if len(line)>0:
717 729 lsplit = line.split(opt['fs'],1)
718 730 try:
719 731 key,val = lsplit
720 732 except ValueError:
721 733 key,val = lsplit[0],''
722 734 key = key.strip()
723 735 if opt['strip']: val = val.strip()
724 736 if val == "''" or val == '""': val = ''
725 737 if opt['no_empty'] and (val=='' or val.isspace()):
726 738 continue
727 739 # if a key is found more than once in the file, build a list
728 740 # unless it's in the 'unique' list. In that case, last found in file
729 741 # takes precedence. User beware.
730 742 try:
731 743 if dict[key] and key in unique_keys:
732 744 dict[key] = val
733 745 elif type(dict[key]) is types.ListType:
734 746 dict[key].append(val)
735 747 else:
736 748 dict[key] = [dict[key],val]
737 749 except KeyError:
738 750 dict[key] = val
739 751 # purge if requested
740 752 if opt['purge']:
741 753 accepted_keys = qwflat(type_conv.values())
742 754 for key in dict.keys():
743 755 if key in accepted_keys: continue
744 756 del(dict[key])
745 757 # now convert if requested
746 758 if type_conv==None: return dict
747 759 conversions = type_conv.keys()
748 760 try: conversions.remove(None)
749 761 except: pass
750 762 for convert in conversions:
751 763 for val in qw(type_conv[convert]):
752 764 try:
753 765 dict[val] = convert(dict[val])
754 766 except KeyError,e:
755 767 if opt['warn'] == 0:
756 768 pass
757 769 elif opt['warn'] == 1:
758 770 print >>sys.stderr, 'Warning: key',val,\
759 771 'not found in file',filename
760 772 elif opt['warn'] == 2:
761 773 raise KeyError,e
762 774 else:
763 775 raise ValueError,'Warning level must be 0,1 or 2'
764 776
765 777 return dict
766 778
767 779 #----------------------------------------------------------------------------
768 780 def flag_calls(func):
769 781 """Wrap a function to detect and flag when it gets called.
770 782
771 783 This is a decorator which takes a function and wraps it in a function with
772 784 a 'called' attribute. wrapper.called is initialized to False.
773 785
774 786 The wrapper.called attribute is set to False right before each call to the
775 787 wrapped function, so if the call fails it remains False. After the call
776 788 completes, wrapper.called is set to True and the output is returned.
777 789
778 790 Testing for truth in wrapper.called allows you to determine if a call to
779 791 func() was attempted and succeeded."""
780 792
781 793 def wrapper(*args,**kw):
782 794 wrapper.called = False
783 795 out = func(*args,**kw)
784 796 wrapper.called = True
785 797 return out
786 798
787 799 wrapper.called = False
788 800 wrapper.__doc__ = func.__doc__
789 801 return wrapper
790 802
791 803 #----------------------------------------------------------------------------
792 804 class HomeDirError(Error):
793 805 pass
794 806
795 807 def get_home_dir():
796 808 """Return the closest possible equivalent to a 'home' directory.
797 809
798 810 We first try $HOME. Absent that, on NT it's $HOMEDRIVE\$HOMEPATH.
799 811
800 812 Currently only Posix and NT are implemented, a HomeDirError exception is
801 813 raised for all other OSes. """
802 814
803 815 isdir = os.path.isdir
804 816 env = os.environ
805 817 try:
806 818 homedir = env['HOME']
807 819 if not isdir(homedir):
808 820 # in case a user stuck some string which does NOT resolve to a
809 821 # valid path, it's as good as if we hadn't foud it
810 822 raise KeyError
811 823 return homedir
812 824 except KeyError:
813 825 if os.name == 'posix':
814 826 raise HomeDirError,'undefined $HOME, IPython can not proceed.'
815 827 elif os.name == 'nt':
816 828 # For some strange reason, win9x returns 'nt' for os.name.
817 829 try:
818 830 homedir = os.path.join(env['HOMEDRIVE'],env['HOMEPATH'])
819 831 if not isdir(homedir):
820 832 homedir = os.path.join(env['USERPROFILE'])
821 833 if not isdir(homedir):
822 834 raise HomeDirError
823 835 return homedir
824 836 except:
825 837 try:
826 838 # Use the registry to get the 'My Documents' folder.
827 839 import _winreg as wreg
828 840 key = wreg.OpenKey(wreg.HKEY_CURRENT_USER,
829 841 "Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders")
830 842 homedir = wreg.QueryValueEx(key,'Personal')[0]
831 843 key.Close()
832 844 if not isdir(homedir):
833 845 e = ('Invalid "Personal" folder registry key '
834 846 'typically "My Documents".\n'
835 847 'Value: %s\n'
836 848 'This is not a valid directory on your system.' %
837 849 homedir)
838 850 raise HomeDirError(e)
839 851 return homedir
840 852 except HomeDirError:
841 853 raise
842 854 except:
843 855 return 'C:\\'
844 856 elif os.name == 'dos':
845 857 # Desperate, may do absurd things in classic MacOS. May work under DOS.
846 858 return 'C:\\'
847 859 else:
848 860 raise HomeDirError,'support for your operating system not implemented.'
849 861
850 862 #****************************************************************************
851 863 # strings and text
852 864
853 865 class LSString(str):
854 866 """String derivative with a special access attributes.
855 867
856 868 These are normal strings, but with the special attributes:
857 869
858 870 .l (or .list) : value as list (split on newlines).
859 871 .n (or .nlstr): original value (the string itself).
860 872 .s (or .spstr): value as whitespace-separated string.
861 873
862 874 Any values which require transformations are computed only once and
863 875 cached.
864 876
865 877 Such strings are very useful to efficiently interact with the shell, which
866 878 typically only understands whitespace-separated options for commands."""
867 879
868 880 def get_list(self):
869 881 try:
870 882 return self.__list
871 883 except AttributeError:
872 884 self.__list = self.split('\n')
873 885 return self.__list
874 886
875 887 l = list = property(get_list)
876 888
877 889 def get_spstr(self):
878 890 try:
879 891 return self.__spstr
880 892 except AttributeError:
881 893 self.__spstr = self.replace('\n',' ')
882 894 return self.__spstr
883 895
884 896 s = spstr = property(get_spstr)
885 897
886 898 def get_nlstr(self):
887 899 return self
888 900
889 901 n = nlstr = property(get_nlstr)
890 902
891 903 #----------------------------------------------------------------------------
892 904 class SList(list):
893 905 """List derivative with a special access attributes.
894 906
895 907 These are normal lists, but with the special attributes:
896 908
897 909 .l (or .list) : value as list (the list itself).
898 910 .n (or .nlstr): value as a string, joined on newlines.
899 911 .s (or .spstr): value as a string, joined on spaces.
900 912
901 913 Any values which require transformations are computed only once and
902 914 cached."""
903 915
904 916 def get_list(self):
905 917 return self
906 918
907 919 l = list = property(get_list)
908 920
909 921 def get_spstr(self):
910 922 try:
911 923 return self.__spstr
912 924 except AttributeError:
913 925 self.__spstr = ' '.join(self)
914 926 return self.__spstr
915 927
916 928 s = spstr = property(get_spstr)
917 929
918 930 def get_nlstr(self):
919 931 try:
920 932 return self.__nlstr
921 933 except AttributeError:
922 934 self.__nlstr = '\n'.join(self)
923 935 return self.__nlstr
924 936
925 937 n = nlstr = property(get_nlstr)
926 938
927 939 #----------------------------------------------------------------------------
928 940 # This can be replaced with an isspace() call once we drop 2.2 compatibility
929 941 _isspace_match = re.compile(r'^\s+$').match
930 942 def isspace(s):
931 943 return bool(_isspace_match(s))
932 944
933 945 #----------------------------------------------------------------------------
934 946 def esc_quotes(strng):
935 947 """Return the input string with single and double quotes escaped out"""
936 948
937 949 return strng.replace('"','\\"').replace("'","\\'")
938 950
939 951 #----------------------------------------------------------------------------
940 952 def raw_input_multi(header='', ps1='==> ', ps2='..> ',terminate_str = '.'):
941 953 """Take multiple lines of input.
942 954
943 955 A list with each line of input as a separate element is returned when a
944 956 termination string is entered (defaults to a single '.'). Input can also
945 957 terminate via EOF (^D in Unix, ^Z-RET in Windows).
946 958
947 959 Lines of input which end in \\ are joined into single entries (and a
948 960 secondary continuation prompt is issued as long as the user terminates
949 961 lines with \\). This allows entering very long strings which are still
950 962 meant to be treated as single entities.
951 963 """
952 964
953 965 try:
954 966 if header:
955 967 header += '\n'
956 968 lines = [raw_input(header + ps1)]
957 969 except EOFError:
958 970 return []
959 971 terminate = [terminate_str]
960 972 try:
961 973 while lines[-1:] != terminate:
962 974 new_line = raw_input(ps1)
963 975 while new_line.endswith('\\'):
964 976 new_line = new_line[:-1] + raw_input(ps2)
965 977 lines.append(new_line)
966 978
967 979 return lines[:-1] # don't return the termination command
968 980 except EOFError:
969 981 print
970 982 return lines
971 983
972 984 #----------------------------------------------------------------------------
973 985 def raw_input_ext(prompt='', ps2='... '):
974 986 """Similar to raw_input(), but accepts extended lines if input ends with \\."""
975 987
976 988 line = raw_input(prompt)
977 989 while line.endswith('\\'):
978 990 line = line[:-1] + raw_input(ps2)
979 991 return line
980 992
981 993 #----------------------------------------------------------------------------
982 994 def ask_yes_no(prompt,default=None):
983 995 """Asks a question and returns an integer 1/0 (y/n) answer.
984 996
985 997 If default is given (one of 'y','n'), it is used if the user input is
986 998 empty. Otherwise the question is repeated until an answer is given.
987 999 If EOF occurs 20 times consecutively, the default answer is assumed,
988 1000 or if there is no default, an exception is raised to prevent infinite
989 1001 loops.
990 1002
991 1003 Valid answers are: y/yes/n/no (match is not case sensitive)."""
992 1004
993 1005 answers = {'y':True,'n':False,'yes':True,'no':False}
994 1006 ans = None
995 1007 eofs, max_eofs = 0, 20
996 1008 while ans not in answers.keys():
997 1009 try:
998 1010 ans = raw_input(prompt+' ').lower()
999 1011 if not ans: # response was an empty string
1000 1012 ans = default
1001 1013 eofs = 0
1002 1014 except (EOFError,KeyboardInterrupt):
1003 1015 eofs = eofs + 1
1004 1016 if eofs >= max_eofs:
1005 1017 if default in answers.keys():
1006 1018 ans = default
1007 1019 else:
1008 1020 raise
1009 1021
1010 1022 return answers[ans]
1011 1023
1012 1024 #----------------------------------------------------------------------------
1013 1025 def marquee(txt='',width=78,mark='*'):
1014 1026 """Return the input string centered in a 'marquee'."""
1015 1027 if not txt:
1016 1028 return (mark*width)[:width]
1017 1029 nmark = (width-len(txt)-2)/len(mark)/2
1018 1030 if nmark < 0: nmark =0
1019 1031 marks = mark*nmark
1020 1032 return '%s %s %s' % (marks,txt,marks)
1021 1033
1022 1034 #----------------------------------------------------------------------------
1023 1035 class EvalDict:
1024 1036 """
1025 1037 Emulate a dict which evaluates its contents in the caller's frame.
1026 1038
1027 1039 Usage:
1028 1040 >>>number = 19
1029 1041 >>>text = "python"
1030 1042 >>>print "%(text.capitalize())s %(number/9.0).1f rules!" % EvalDict()
1031 1043 """
1032 1044
1033 1045 # This version is due to sismex01@hebmex.com on c.l.py, and is basically a
1034 1046 # modified (shorter) version of:
1035 1047 # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66018 by
1036 1048 # Skip Montanaro (skip@pobox.com).
1037 1049
1038 1050 def __getitem__(self, name):
1039 1051 frame = sys._getframe(1)
1040 1052 return eval(name, frame.f_globals, frame.f_locals)
1041 1053
1042 1054 EvalString = EvalDict # for backwards compatibility
1043 1055 #----------------------------------------------------------------------------
1044 1056 def qw(words,flat=0,sep=None,maxsplit=-1):
1045 1057 """Similar to Perl's qw() operator, but with some more options.
1046 1058
1047 1059 qw(words,flat=0,sep=' ',maxsplit=-1) -> words.split(sep,maxsplit)
1048 1060
1049 1061 words can also be a list itself, and with flat=1, the output will be
1050 1062 recursively flattened. Examples:
1051 1063
1052 1064 >>> qw('1 2')
1053 1065 ['1', '2']
1054 1066 >>> qw(['a b','1 2',['m n','p q']])
1055 1067 [['a', 'b'], ['1', '2'], [['m', 'n'], ['p', 'q']]]
1056 1068 >>> qw(['a b','1 2',['m n','p q']],flat=1)
1057 1069 ['a', 'b', '1', '2', 'm', 'n', 'p', 'q'] """
1058 1070
1059 1071 if type(words) in StringTypes:
1060 1072 return [word.strip() for word in words.split(sep,maxsplit)
1061 1073 if word and not word.isspace() ]
1062 1074 if flat:
1063 1075 return flatten(map(qw,words,[1]*len(words)))
1064 1076 return map(qw,words)
1065 1077
1066 1078 #----------------------------------------------------------------------------
1067 1079 def qwflat(words,sep=None,maxsplit=-1):
1068 1080 """Calls qw(words) in flat mode. It's just a convenient shorthand."""
1069 1081 return qw(words,1,sep,maxsplit)
1070 1082
1071 1083 #----------------------------------------------------------------------------
1072 1084 def qw_lol(indata):
1073 1085 """qw_lol('a b') -> [['a','b']],
1074 1086 otherwise it's just a call to qw().
1075 1087
1076 1088 We need this to make sure the modules_some keys *always* end up as a
1077 1089 list of lists."""
1078 1090
1079 1091 if type(indata) in StringTypes:
1080 1092 return [qw(indata)]
1081 1093 else:
1082 1094 return qw(indata)
1083 1095
1084 1096 #-----------------------------------------------------------------------------
1085 1097 def list_strings(arg):
1086 1098 """Always return a list of strings, given a string or list of strings
1087 1099 as input."""
1088 1100
1089 1101 if type(arg) in StringTypes: return [arg]
1090 1102 else: return arg
1091 1103
1092 1104 #----------------------------------------------------------------------------
1093 1105 def grep(pat,list,case=1):
1094 1106 """Simple minded grep-like function.
1095 1107 grep(pat,list) returns occurrences of pat in list, None on failure.
1096 1108
1097 1109 It only does simple string matching, with no support for regexps. Use the
1098 1110 option case=0 for case-insensitive matching."""
1099 1111
1100 1112 # This is pretty crude. At least it should implement copying only references
1101 1113 # to the original data in case it's big. Now it copies the data for output.
1102 1114 out=[]
1103 1115 if case:
1104 1116 for term in list:
1105 1117 if term.find(pat)>-1: out.append(term)
1106 1118 else:
1107 1119 lpat=pat.lower()
1108 1120 for term in list:
1109 1121 if term.lower().find(lpat)>-1: out.append(term)
1110 1122
1111 1123 if len(out): return out
1112 1124 else: return None
1113 1125
1114 1126 #----------------------------------------------------------------------------
1115 1127 def dgrep(pat,*opts):
1116 1128 """Return grep() on dir()+dir(__builtins__).
1117 1129
1118 1130 A very common use of grep() when working interactively."""
1119 1131
1120 1132 return grep(pat,dir(__main__)+dir(__main__.__builtins__),*opts)
1121 1133
1122 1134 #----------------------------------------------------------------------------
1123 1135 def idgrep(pat):
1124 1136 """Case-insensitive dgrep()"""
1125 1137
1126 1138 return dgrep(pat,0)
1127 1139
1128 1140 #----------------------------------------------------------------------------
1129 1141 def igrep(pat,list):
1130 1142 """Synonym for case-insensitive grep."""
1131 1143
1132 1144 return grep(pat,list,case=0)
1133 1145
1134 1146 #----------------------------------------------------------------------------
1135 1147 def indent(str,nspaces=4,ntabs=0):
1136 1148 """Indent a string a given number of spaces or tabstops.
1137 1149
1138 1150 indent(str,nspaces=4,ntabs=0) -> indent str by ntabs+nspaces.
1139 1151 """
1140 1152 if str is None:
1141 1153 return
1142 1154 ind = '\t'*ntabs+' '*nspaces
1143 1155 outstr = '%s%s' % (ind,str.replace(os.linesep,os.linesep+ind))
1144 1156 if outstr.endswith(os.linesep+ind):
1145 1157 return outstr[:-len(ind)]
1146 1158 else:
1147 1159 return outstr
1148 1160
1149 1161 #-----------------------------------------------------------------------------
1150 1162 def native_line_ends(filename,backup=1):
1151 1163 """Convert (in-place) a file to line-ends native to the current OS.
1152 1164
1153 1165 If the optional backup argument is given as false, no backup of the
1154 1166 original file is left. """
1155 1167
1156 1168 backup_suffixes = {'posix':'~','dos':'.bak','nt':'.bak','mac':'.bak'}
1157 1169
1158 1170 bak_filename = filename + backup_suffixes[os.name]
1159 1171
1160 1172 original = open(filename).read()
1161 1173 shutil.copy2(filename,bak_filename)
1162 1174 try:
1163 1175 new = open(filename,'wb')
1164 1176 new.write(os.linesep.join(original.splitlines()))
1165 1177 new.write(os.linesep) # ALWAYS put an eol at the end of the file
1166 1178 new.close()
1167 1179 except:
1168 1180 os.rename(bak_filename,filename)
1169 1181 if not backup:
1170 1182 try:
1171 1183 os.remove(bak_filename)
1172 1184 except:
1173 1185 pass
1174 1186
1175 1187 #----------------------------------------------------------------------------
1176 1188 def get_pager_cmd(pager_cmd = None):
1177 1189 """Return a pager command.
1178 1190
1179 1191 Makes some attempts at finding an OS-correct one."""
1180 1192
1181 1193 if os.name == 'posix':
1182 1194 default_pager_cmd = 'less -r' # -r for color control sequences
1183 1195 elif os.name in ['nt','dos']:
1184 1196 default_pager_cmd = 'type'
1185 1197
1186 1198 if pager_cmd is None:
1187 1199 try:
1188 1200 pager_cmd = os.environ['PAGER']
1189 1201 except:
1190 1202 pager_cmd = default_pager_cmd
1191 1203 return pager_cmd
1192 1204
1193 1205 #-----------------------------------------------------------------------------
1194 1206 def get_pager_start(pager,start):
1195 1207 """Return the string for paging files with an offset.
1196 1208
1197 1209 This is the '+N' argument which less and more (under Unix) accept.
1198 1210 """
1199 1211
1200 1212 if pager in ['less','more']:
1201 1213 if start:
1202 1214 start_string = '+' + str(start)
1203 1215 else:
1204 1216 start_string = ''
1205 1217 else:
1206 1218 start_string = ''
1207 1219 return start_string
1208 1220
1209 1221 #----------------------------------------------------------------------------
1210 1222 if os.name == "nt":
1211 1223 import msvcrt
1212 1224 def page_more():
1213 1225 """ Smart pausing between pages
1214 1226
1215 1227 @return: True if need print more lines, False if quit
1216 1228 """
1217 1229 Term.cout.write('---Return to continue, q to quit--- ')
1218 1230 ans = msvcrt.getch()
1219 1231 if ans in ("q", "Q"):
1220 1232 result = False
1221 1233 else:
1222 1234 result = True
1223 1235 Term.cout.write("\b"*37 + " "*37 + "\b"*37)
1224 1236 return result
1225 1237 else:
1226 1238 def page_more():
1227 1239 ans = raw_input('---Return to continue, q to quit--- ')
1228 1240 if ans.lower().startswith('q'):
1229 1241 return False
1230 1242 else:
1231 1243 return True
1232 1244
1233 1245 esc_re = re.compile(r"(\x1b[^m]+m)")
1234 1246
1235 1247 def page_dumb(strng,start=0,screen_lines=25):
1236 1248 """Very dumb 'pager' in Python, for when nothing else works.
1237 1249
1238 1250 Only moves forward, same interface as page(), except for pager_cmd and
1239 1251 mode."""
1240 1252
1241 1253 out_ln = strng.splitlines()[start:]
1242 1254 screens = chop(out_ln,screen_lines-1)
1243 1255 if len(screens) == 1:
1244 1256 print >>Term.cout, os.linesep.join(screens[0])
1245 1257 else:
1246 1258 last_escape = ""
1247 1259 for scr in screens[0:-1]:
1248 1260 hunk = os.linesep.join(scr)
1249 1261 print >>Term.cout, last_escape + hunk
1250 1262 if not page_more():
1251 1263 return
1252 1264 esc_list = esc_re.findall(hunk)
1253 1265 if len(esc_list) > 0:
1254 1266 last_escape = esc_list[-1]
1255 1267 print >>Term.cout, last_escape + os.linesep.join(screens[-1])
1256 1268
1257 1269 #----------------------------------------------------------------------------
1258 1270 def page(strng,start=0,screen_lines=0,pager_cmd = None):
1259 1271 """Print a string, piping through a pager after a certain length.
1260 1272
1261 1273 The screen_lines parameter specifies the number of *usable* lines of your
1262 1274 terminal screen (total lines minus lines you need to reserve to show other
1263 1275 information).
1264 1276
1265 1277 If you set screen_lines to a number <=0, page() will try to auto-determine
1266 1278 your screen size and will only use up to (screen_size+screen_lines) for
1267 1279 printing, paging after that. That is, if you want auto-detection but need
1268 1280 to reserve the bottom 3 lines of the screen, use screen_lines = -3, and for
1269 1281 auto-detection without any lines reserved simply use screen_lines = 0.
1270 1282
1271 1283 If a string won't fit in the allowed lines, it is sent through the
1272 1284 specified pager command. If none given, look for PAGER in the environment,
1273 1285 and ultimately default to less.
1274 1286
1275 1287 If no system pager works, the string is sent through a 'dumb pager'
1276 1288 written in python, very simplistic.
1277 1289 """
1278 1290
1279 1291 # Ugly kludge, but calling curses.initscr() flat out crashes in emacs
1280 1292 TERM = os.environ.get('TERM','dumb')
1281 1293 if TERM in ['dumb','emacs'] and os.name != 'nt':
1282 1294 print strng
1283 1295 return
1284 1296 # chop off the topmost part of the string we don't want to see
1285 1297 str_lines = strng.split(os.linesep)[start:]
1286 1298 str_toprint = os.linesep.join(str_lines)
1287 1299 num_newlines = len(str_lines)
1288 1300 len_str = len(str_toprint)
1289 1301
1290 1302 # Dumb heuristics to guesstimate number of on-screen lines the string
1291 1303 # takes. Very basic, but good enough for docstrings in reasonable
1292 1304 # terminals. If someone later feels like refining it, it's not hard.
1293 1305 numlines = max(num_newlines,int(len_str/80)+1)
1294 1306
1295 1307 if os.name == "nt":
1296 1308 screen_lines_def = get_console_size(defaulty=25)[1]
1297 1309 else:
1298 1310 screen_lines_def = 25 # default value if we can't auto-determine
1299 1311
1300 1312 # auto-determine screen size
1301 1313 if screen_lines <= 0:
1302 1314 if TERM=='xterm':
1303 1315 try:
1304 1316 import curses
1305 1317 if hasattr(curses,'initscr'):
1306 1318 use_curses = 1
1307 1319 else:
1308 1320 use_curses = 0
1309 1321 except ImportError:
1310 1322 use_curses = 0
1311 1323 else:
1312 1324 # curses causes problems on many terminals other than xterm.
1313 1325 use_curses = 0
1314 1326 if use_curses:
1315 1327 scr = curses.initscr()
1316 1328 screen_lines_real,screen_cols = scr.getmaxyx()
1317 1329 curses.endwin()
1318 1330 screen_lines += screen_lines_real
1319 1331 #print '***Screen size:',screen_lines_real,'lines x',\
1320 1332 #screen_cols,'columns.' # dbg
1321 1333 else:
1322 1334 screen_lines += screen_lines_def
1323 1335
1324 1336 #print 'numlines',numlines,'screenlines',screen_lines # dbg
1325 1337 if numlines <= screen_lines :
1326 1338 #print '*** normal print' # dbg
1327 1339 print >>Term.cout, str_toprint
1328 1340 else:
1329 1341 # Try to open pager and default to internal one if that fails.
1330 1342 # All failure modes are tagged as 'retval=1', to match the return
1331 1343 # value of a failed system command. If any intermediate attempt
1332 1344 # sets retval to 1, at the end we resort to our own page_dumb() pager.
1333 1345 pager_cmd = get_pager_cmd(pager_cmd)
1334 1346 pager_cmd += ' ' + get_pager_start(pager_cmd,start)
1335 1347 if os.name == 'nt':
1336 1348 if pager_cmd.startswith('type'):
1337 1349 # The default WinXP 'type' command is failing on complex strings.
1338 1350 retval = 1
1339 1351 else:
1340 1352 tmpname = tempfile.mktemp('.txt')
1341 1353 tmpfile = file(tmpname,'wt')
1342 1354 tmpfile.write(strng)
1343 1355 tmpfile.close()
1344 1356 cmd = "%s < %s" % (pager_cmd,tmpname)
1345 1357 if os.system(cmd):
1346 1358 retval = 1
1347 1359 else:
1348 1360 retval = None
1349 1361 os.remove(tmpname)
1350 1362 else:
1351 1363 try:
1352 1364 retval = None
1353 1365 # if I use popen4, things hang. No idea why.
1354 1366 #pager,shell_out = os.popen4(pager_cmd)
1355 1367 pager = os.popen(pager_cmd,'w')
1356 1368 pager.write(strng)
1357 1369 pager.close()
1358 1370 retval = pager.close() # success returns None
1359 1371 except IOError,msg: # broken pipe when user quits
1360 1372 if msg.args == (32,'Broken pipe'):
1361 1373 retval = None
1362 1374 else:
1363 1375 retval = 1
1364 1376 except OSError:
1365 1377 # Other strange problems, sometimes seen in Win2k/cygwin
1366 1378 retval = 1
1367 1379 if retval is not None:
1368 1380 page_dumb(strng,screen_lines=screen_lines)
1369 1381
1370 1382 #----------------------------------------------------------------------------
1371 1383 def page_file(fname,start = 0, pager_cmd = None):
1372 1384 """Page a file, using an optional pager command and starting line.
1373 1385 """
1374 1386
1375 1387 pager_cmd = get_pager_cmd(pager_cmd)
1376 1388 pager_cmd += ' ' + get_pager_start(pager_cmd,start)
1377 1389
1378 1390 try:
1379 1391 if os.environ['TERM'] in ['emacs','dumb']:
1380 1392 raise EnvironmentError
1381 1393 xsys(pager_cmd + ' ' + fname)
1382 1394 except:
1383 1395 try:
1384 1396 if start > 0:
1385 1397 start -= 1
1386 1398 page(open(fname).read(),start)
1387 1399 except:
1388 1400 print 'Unable to show file',`fname`
1389 1401
1390 1402 #----------------------------------------------------------------------------
1391 1403 def snip_print(str,width = 75,print_full = 0,header = ''):
1392 1404 """Print a string snipping the midsection to fit in width.
1393 1405
1394 1406 print_full: mode control:
1395 1407 - 0: only snip long strings
1396 1408 - 1: send to page() directly.
1397 1409 - 2: snip long strings and ask for full length viewing with page()
1398 1410 Return 1 if snipping was necessary, 0 otherwise."""
1399 1411
1400 1412 if print_full == 1:
1401 1413 page(header+str)
1402 1414 return 0
1403 1415
1404 1416 print header,
1405 1417 if len(str) < width:
1406 1418 print str
1407 1419 snip = 0
1408 1420 else:
1409 1421 whalf = int((width -5)/2)
1410 1422 print str[:whalf] + ' <...> ' + str[-whalf:]
1411 1423 snip = 1
1412 1424 if snip and print_full == 2:
1413 1425 if raw_input(header+' Snipped. View (y/n)? [N]').lower() == 'y':
1414 1426 page(str)
1415 1427 return snip
1416 1428
1417 1429 #****************************************************************************
1418 1430 # lists, dicts and structures
1419 1431
1420 1432 def belong(candidates,checklist):
1421 1433 """Check whether a list of items appear in a given list of options.
1422 1434
1423 1435 Returns a list of 1 and 0, one for each candidate given."""
1424 1436
1425 1437 return [x in checklist for x in candidates]
1426 1438
1427 1439 #----------------------------------------------------------------------------
1428 1440 def uniq_stable(elems):
1429 1441 """uniq_stable(elems) -> list
1430 1442
1431 1443 Return from an iterable, a list of all the unique elements in the input,
1432 1444 but maintaining the order in which they first appear.
1433 1445
1434 1446 A naive solution to this problem which just makes a dictionary with the
1435 1447 elements as keys fails to respect the stability condition, since
1436 1448 dictionaries are unsorted by nature.
1437 1449
1438 1450 Note: All elements in the input must be valid dictionary keys for this
1439 1451 routine to work, as it internally uses a dictionary for efficiency
1440 1452 reasons."""
1441 1453
1442 1454 unique = []
1443 1455 unique_dict = {}
1444 1456 for nn in elems:
1445 1457 if nn not in unique_dict:
1446 1458 unique.append(nn)
1447 1459 unique_dict[nn] = None
1448 1460 return unique
1449 1461
1450 1462 #----------------------------------------------------------------------------
1451 1463 class NLprinter:
1452 1464 """Print an arbitrarily nested list, indicating index numbers.
1453 1465
1454 1466 An instance of this class called nlprint is available and callable as a
1455 1467 function.
1456 1468
1457 1469 nlprint(list,indent=' ',sep=': ') -> prints indenting each level by 'indent'
1458 1470 and using 'sep' to separate the index from the value. """
1459 1471
1460 1472 def __init__(self):
1461 1473 self.depth = 0
1462 1474
1463 1475 def __call__(self,lst,pos='',**kw):
1464 1476 """Prints the nested list numbering levels."""
1465 1477 kw.setdefault('indent',' ')
1466 1478 kw.setdefault('sep',': ')
1467 1479 kw.setdefault('start',0)
1468 1480 kw.setdefault('stop',len(lst))
1469 1481 # we need to remove start and stop from kw so they don't propagate
1470 1482 # into a recursive call for a nested list.
1471 1483 start = kw['start']; del kw['start']
1472 1484 stop = kw['stop']; del kw['stop']
1473 1485 if self.depth == 0 and 'header' in kw.keys():
1474 1486 print kw['header']
1475 1487
1476 1488 for idx in range(start,stop):
1477 1489 elem = lst[idx]
1478 1490 if type(elem)==type([]):
1479 1491 self.depth += 1
1480 1492 self.__call__(elem,itpl('$pos$idx,'),**kw)
1481 1493 self.depth -= 1
1482 1494 else:
1483 1495 printpl(kw['indent']*self.depth+'$pos$idx$kw["sep"]$elem')
1484 1496
1485 1497 nlprint = NLprinter()
1486 1498 #----------------------------------------------------------------------------
1487 1499 def all_belong(candidates,checklist):
1488 1500 """Check whether a list of items ALL appear in a given list of options.
1489 1501
1490 1502 Returns a single 1 or 0 value."""
1491 1503
1492 1504 return 1-(0 in [x in checklist for x in candidates])
1493 1505
1494 1506 #----------------------------------------------------------------------------
1495 1507 def sort_compare(lst1,lst2,inplace = 1):
1496 1508 """Sort and compare two lists.
1497 1509
1498 1510 By default it does it in place, thus modifying the lists. Use inplace = 0
1499 1511 to avoid that (at the cost of temporary copy creation)."""
1500 1512 if not inplace:
1501 1513 lst1 = lst1[:]
1502 1514 lst2 = lst2[:]
1503 1515 lst1.sort(); lst2.sort()
1504 1516 return lst1 == lst2
1505 1517
1506 1518 #----------------------------------------------------------------------------
1507 1519 def mkdict(**kwargs):
1508 1520 """Return a dict from a keyword list.
1509 1521
1510 1522 It's just syntactic sugar for making ditcionary creation more convenient:
1511 1523 # the standard way
1512 1524 >>>data = { 'red' : 1, 'green' : 2, 'blue' : 3 }
1513 1525 # a cleaner way
1514 1526 >>>data = dict(red=1, green=2, blue=3)
1515 1527
1516 1528 If you need more than this, look at the Struct() class."""
1517 1529
1518 1530 return kwargs
1519 1531
1520 1532 #----------------------------------------------------------------------------
1521 1533 def list2dict(lst):
1522 1534 """Takes a list of (key,value) pairs and turns it into a dict."""
1523 1535
1524 1536 dic = {}
1525 1537 for k,v in lst: dic[k] = v
1526 1538 return dic
1527 1539
1528 1540 #----------------------------------------------------------------------------
1529 1541 def list2dict2(lst,default=''):
1530 1542 """Takes a list and turns it into a dict.
1531 1543 Much slower than list2dict, but more versatile. This version can take
1532 1544 lists with sublists of arbitrary length (including sclars)."""
1533 1545
1534 1546 dic = {}
1535 1547 for elem in lst:
1536 1548 if type(elem) in (types.ListType,types.TupleType):
1537 1549 size = len(elem)
1538 1550 if size == 0:
1539 1551 pass
1540 1552 elif size == 1:
1541 1553 dic[elem] = default
1542 1554 else:
1543 1555 k,v = elem[0], elem[1:]
1544 1556 if len(v) == 1: v = v[0]
1545 1557 dic[k] = v
1546 1558 else:
1547 1559 dic[elem] = default
1548 1560 return dic
1549 1561
1550 1562 #----------------------------------------------------------------------------
1551 1563 def flatten(seq):
1552 1564 """Flatten a list of lists (NOT recursive, only works for 2d lists)."""
1553 1565
1554 1566 # bug in python??? (YES. Fixed in 2.2, let's leave the kludgy fix in).
1555 1567
1556 1568 # if the x=0 isn't made, a *global* variable x is left over after calling
1557 1569 # this function, with the value of the last element in the return
1558 1570 # list. This does seem like a bug big time to me.
1559 1571
1560 1572 # the problem is fixed with the x=0, which seems to force the creation of
1561 1573 # a local name
1562 1574
1563 1575 x = 0
1564 1576 return [x for subseq in seq for x in subseq]
1565 1577
1566 1578 #----------------------------------------------------------------------------
1567 1579 def get_slice(seq,start=0,stop=None,step=1):
1568 1580 """Get a slice of a sequence with variable step. Specify start,stop,step."""
1569 1581 if stop == None:
1570 1582 stop = len(seq)
1571 1583 item = lambda i: seq[i]
1572 1584 return map(item,xrange(start,stop,step))
1573 1585
1574 1586 #----------------------------------------------------------------------------
1575 1587 def chop(seq,size):
1576 1588 """Chop a sequence into chunks of the given size."""
1577 1589 chunk = lambda i: seq[i:i+size]
1578 1590 return map(chunk,xrange(0,len(seq),size))
1579 1591
1580 1592 #----------------------------------------------------------------------------
1581 1593 def with(object, **args):
1582 1594 """Set multiple attributes for an object, similar to Pascal's with.
1583 1595
1584 1596 Example:
1585 1597 with(jim,
1586 1598 born = 1960,
1587 1599 haircolour = 'Brown',
1588 1600 eyecolour = 'Green')
1589 1601
1590 1602 Credit: Greg Ewing, in
1591 1603 http://mail.python.org/pipermail/python-list/2001-May/040703.html"""
1592 1604
1593 1605 object.__dict__.update(args)
1594 1606
1595 1607 #----------------------------------------------------------------------------
1596 1608 def setattr_list(obj,alist,nspace = None):
1597 1609 """Set a list of attributes for an object taken from a namespace.
1598 1610
1599 1611 setattr_list(obj,alist,nspace) -> sets in obj all the attributes listed in
1600 1612 alist with their values taken from nspace, which must be a dict (something
1601 1613 like locals() will often do) If nspace isn't given, locals() of the
1602 1614 *caller* is used, so in most cases you can omit it.
1603 1615
1604 1616 Note that alist can be given as a string, which will be automatically
1605 1617 split into a list on whitespace. If given as a list, it must be a list of
1606 1618 *strings* (the variable names themselves), not of variables."""
1607 1619
1608 1620 # this grabs the local variables from the *previous* call frame -- that is
1609 1621 # the locals from the function that called setattr_list().
1610 1622 # - snipped from weave.inline()
1611 1623 if nspace is None:
1612 1624 call_frame = sys._getframe().f_back
1613 1625 nspace = call_frame.f_locals
1614 1626
1615 1627 if type(alist) in StringTypes:
1616 1628 alist = alist.split()
1617 1629 for attr in alist:
1618 1630 val = eval(attr,nspace)
1619 1631 setattr(obj,attr,val)
1620 1632
1621 1633 #----------------------------------------------------------------------------
1622 1634 def getattr_list(obj,alist,*args):
1623 1635 """getattr_list(obj,alist[, default]) -> attribute list.
1624 1636
1625 1637 Get a list of named attributes for an object. When a default argument is
1626 1638 given, it is returned when the attribute doesn't exist; without it, an
1627 1639 exception is raised in that case.
1628 1640
1629 1641 Note that alist can be given as a string, which will be automatically
1630 1642 split into a list on whitespace. If given as a list, it must be a list of
1631 1643 *strings* (the variable names themselves), not of variables."""
1632 1644
1633 1645 if type(alist) in StringTypes:
1634 1646 alist = alist.split()
1635 1647 if args:
1636 1648 if len(args)==1:
1637 1649 default = args[0]
1638 1650 return map(lambda attr: getattr(obj,attr,default),alist)
1639 1651 else:
1640 1652 raise ValueError,'getattr_list() takes only one optional argument'
1641 1653 else:
1642 1654 return map(lambda attr: getattr(obj,attr),alist)
1643 1655
1644 1656 #----------------------------------------------------------------------------
1645 1657 def map_method(method,object_list,*argseq,**kw):
1646 1658 """map_method(method,object_list,*args,**kw) -> list
1647 1659
1648 1660 Return a list of the results of applying the methods to the items of the
1649 1661 argument sequence(s). If more than one sequence is given, the method is
1650 1662 called with an argument list consisting of the corresponding item of each
1651 1663 sequence. All sequences must be of the same length.
1652 1664
1653 1665 Keyword arguments are passed verbatim to all objects called.
1654 1666
1655 1667 This is Python code, so it's not nearly as fast as the builtin map()."""
1656 1668
1657 1669 out_list = []
1658 1670 idx = 0
1659 1671 for object in object_list:
1660 1672 try:
1661 1673 handler = getattr(object, method)
1662 1674 except AttributeError:
1663 1675 out_list.append(None)
1664 1676 else:
1665 1677 if argseq:
1666 1678 args = map(lambda lst:lst[idx],argseq)
1667 1679 #print 'ob',object,'hand',handler,'ar',args # dbg
1668 1680 out_list.append(handler(args,**kw))
1669 1681 else:
1670 1682 out_list.append(handler(**kw))
1671 1683 idx += 1
1672 1684 return out_list
1673 1685
1674 1686 #----------------------------------------------------------------------------
1675 1687 def import_fail_info(mod_name,fns=None):
1676 1688 """Inform load failure for a module."""
1677 1689
1678 1690 if fns == None:
1679 1691 warn("Loading of %s failed.\n" % (mod_name,))
1680 1692 else:
1681 1693 warn("Loading of %s from %s failed.\n" % (fns,mod_name))
1682 1694
1683 1695 #----------------------------------------------------------------------------
1684 1696 # Proposed popitem() extension, written as a method
1685 1697
1686 1698 class NotGiven: pass
1687 1699
1688 1700 def popkey(dct,key,default=NotGiven):
1689 1701 """Return dct[key] and delete dct[key].
1690 1702
1691 1703 If default is given, return it if dct[key] doesn't exist, otherwise raise
1692 1704 KeyError. """
1693 1705
1694 1706 try:
1695 1707 val = dct[key]
1696 1708 except KeyError:
1697 1709 if default is NotGiven:
1698 1710 raise
1699 1711 else:
1700 1712 return default
1701 1713 else:
1702 1714 del dct[key]
1703 1715 return val
1704 1716 #*************************** end of file <genutils.py> **********************
1705 1717
@@ -1,2138 +1,2153 b''
1 1 # -*- coding: utf-8 -*-
2 2 """
3 3 IPython -- An enhanced Interactive Python
4 4
5 5 Requires Python 2.1 or newer.
6 6
7 7 This file contains all the classes and helper functions specific to IPython.
8 8
9 $Id: iplib.py 988 2006-01-02 21:21:47Z fperez $
9 $Id: iplib.py 990 2006-01-04 06:59:02Z fperez $
10 10 """
11 11
12 12 #*****************************************************************************
13 13 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
14 14 # Copyright (C) 2001-2005 Fernando Perez. <fperez@colorado.edu>
15 15 #
16 16 # Distributed under the terms of the BSD License. The full license is in
17 17 # the file COPYING, distributed as part of this software.
18 18 #
19 19 # Note: this code originally subclassed code.InteractiveConsole from the
20 20 # Python standard library. Over time, all of that class has been copied
21 21 # verbatim here for modifications which could not be accomplished by
22 22 # subclassing. At this point, there are no dependencies at all on the code
23 23 # module anymore (it is not even imported). The Python License (sec. 2)
24 24 # allows for this, but it's always nice to acknowledge credit where credit is
25 25 # due.
26 26 #*****************************************************************************
27 27
28 28 #****************************************************************************
29 29 # Modules and globals
30 30
31 31 from __future__ import generators # for 2.2 backwards-compatibility
32 32
33 33 from IPython import Release
34 34 __author__ = '%s <%s>\n%s <%s>' % \
35 35 ( Release.authors['Janko'] + Release.authors['Fernando'] )
36 36 __license__ = Release.license
37 37 __version__ = Release.version
38 38
39 39 # Python standard modules
40 40 import __main__
41 41 import __builtin__
42 42 import StringIO
43 43 import bdb
44 44 import cPickle as pickle
45 45 import codeop
46 46 import exceptions
47 47 import glob
48 48 import inspect
49 49 import keyword
50 50 import new
51 51 import os
52 52 import pdb
53 53 import pydoc
54 54 import re
55 55 import shutil
56 56 import string
57 57 import sys
58 58 import tempfile
59 59 import traceback
60 60 import types
61 61
62 62 from pprint import pprint, pformat
63 63
64 64 # IPython's own modules
65 65 import IPython
66 66 from IPython import OInspect,PyColorize,ultraTB
67 67 from IPython.ColorANSI import ColorScheme,ColorSchemeTable # too long names
68 68 from IPython.FakeModule import FakeModule
69 69 from IPython.Itpl import Itpl,itpl,printpl,ItplNS,itplns
70 70 from IPython.Logger import Logger
71 71 from IPython.Magic import Magic
72 72 from IPython.Prompts import CachedOutput
73 73 from IPython.Struct import Struct
74 74 from IPython.background_jobs import BackgroundJobManager
75 75 from IPython.usage import cmd_line_usage,interactive_usage
76 76 from IPython.genutils import *
77 77
78 78 # store the builtin raw_input globally, and use this always, in case user code
79 79 # overwrites it (like wx.py.PyShell does)
80 80 raw_input_original = raw_input
81 81
82 82 # compiled regexps for autoindent management
83 83 ini_spaces_re = re.compile(r'^(\s+)')
84 84 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
85 85
86 86 #****************************************************************************
87 87 # Some utility function definitions
88 88
89 89 def softspace(file, newvalue):
90 90 """Copied from code.py, to remove the dependency"""
91 91 oldvalue = 0
92 92 try:
93 93 oldvalue = file.softspace
94 94 except AttributeError:
95 95 pass
96 96 try:
97 97 file.softspace = newvalue
98 98 except (AttributeError, TypeError):
99 99 # "attribute-less object" or "read-only attributes"
100 100 pass
101 101 return oldvalue
102 102
103 103 #****************************************************************************
104 104
105 105
106 106 #****************************************************************************
107 107 # Local use exceptions
108 108 class SpaceInInput(exceptions.Exception): pass
109 109
110 110 #****************************************************************************
111 111 # Local use classes
112 112 class Bunch: pass
113 113
114 114 class Undefined: pass
115 115
116 116 class InputList(list):
117 117 """Class to store user input.
118 118
119 119 It's basically a list, but slices return a string instead of a list, thus
120 120 allowing things like (assuming 'In' is an instance):
121 121
122 122 exec In[4:7]
123 123
124 124 or
125 125
126 126 exec In[5:9] + In[14] + In[21:25]"""
127 127
128 128 def __getslice__(self,i,j):
129 129 return ''.join(list.__getslice__(self,i,j))
130 130
131 131 class SyntaxTB(ultraTB.ListTB):
132 132 """Extension which holds some state: the last exception value"""
133 133
134 134 def __init__(self,color_scheme = 'NoColor'):
135 135 ultraTB.ListTB.__init__(self,color_scheme)
136 136 self.last_syntax_error = None
137 137
138 138 def __call__(self, etype, value, elist):
139 139 self.last_syntax_error = value
140 140 ultraTB.ListTB.__call__(self,etype,value,elist)
141 141
142 142 def clear_err_state(self):
143 143 """Return the current error state and clear it"""
144 144 e = self.last_syntax_error
145 145 self.last_syntax_error = None
146 146 return e
147 147
148 148 #****************************************************************************
149 149 # Main IPython class
150 150
151 151 # FIXME: the Magic class is a mixin for now, and will unfortunately remain so
152 152 # until a full rewrite is made. I've cleaned all cross-class uses of
153 153 # attributes and methods, but too much user code out there relies on the
154 154 # equlity %foo == __IP.magic_foo, so I can't actually remove the mixin usage.
155 155 #
156 156 # But at least now, all the pieces have been separated and we could, in
157 157 # principle, stop using the mixin. This will ease the transition to the
158 158 # chainsaw branch.
159 159
160 160 # For reference, the following is the list of 'self.foo' uses in the Magic
161 161 # class as of 2005-12-28. These are names we CAN'T use in the main ipython
162 162 # class, to prevent clashes.
163 163
164 164 # ['self.__class__', 'self.__dict__', 'self._inspect', 'self._ofind',
165 165 # 'self.arg_err', 'self.extract_input', 'self.format_', 'self.lsmagic',
166 166 # 'self.magic_', 'self.options_table', 'self.parse', 'self.shell',
167 167 # 'self.value']
168 168
169 169 class InteractiveShell(object,Magic):
170 170 """An enhanced console for Python."""
171 171
172 172 # class attribute to indicate whether the class supports threads or not.
173 173 # Subclasses with thread support should override this as needed.
174 174 isthreaded = False
175 175
176 176 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
177 177 user_ns = None,user_global_ns=None,banner2='',
178 178 custom_exceptions=((),None),embedded=False):
179 179
180 180 # some minimal strict typechecks. For some core data structures, I
181 181 # want actual basic python types, not just anything that looks like
182 182 # one. This is especially true for namespaces.
183 183 for ns in (user_ns,user_global_ns):
184 184 if ns is not None and type(ns) != types.DictType:
185 185 raise TypeError,'namespace must be a dictionary'
186 186
187 187 # Job manager (for jobs run as background threads)
188 188 self.jobs = BackgroundJobManager()
189 189
190 190 # track which builtins we add, so we can clean up later
191 191 self.builtins_added = {}
192 192 # This method will add the necessary builtins for operation, but
193 193 # tracking what it did via the builtins_added dict.
194 194 self.add_builtins()
195 195
196 196 # Do the intuitively correct thing for quit/exit: we remove the
197 197 # builtins if they exist, and our own magics will deal with this
198 198 try:
199 199 del __builtin__.exit, __builtin__.quit
200 200 except AttributeError:
201 201 pass
202 202
203 203 # Store the actual shell's name
204 204 self.name = name
205 205
206 206 # We need to know whether the instance is meant for embedding, since
207 207 # global/local namespaces need to be handled differently in that case
208 208 self.embedded = embedded
209 209
210 210 # command compiler
211 211 self.compile = codeop.CommandCompiler()
212 212
213 213 # User input buffer
214 214 self.buffer = []
215 215
216 216 # Default name given in compilation of code
217 217 self.filename = '<ipython console>'
218 218
219 219 # Make an empty namespace, which extension writers can rely on both
220 220 # existing and NEVER being used by ipython itself. This gives them a
221 221 # convenient location for storing additional information and state
222 222 # their extensions may require, without fear of collisions with other
223 223 # ipython names that may develop later.
224 224 self.meta = Bunch()
225 225
226 226 # Create the namespace where the user will operate. user_ns is
227 227 # normally the only one used, and it is passed to the exec calls as
228 228 # the locals argument. But we do carry a user_global_ns namespace
229 229 # given as the exec 'globals' argument, This is useful in embedding
230 230 # situations where the ipython shell opens in a context where the
231 231 # distinction between locals and globals is meaningful.
232 232
233 233 # FIXME. For some strange reason, __builtins__ is showing up at user
234 234 # level as a dict instead of a module. This is a manual fix, but I
235 235 # should really track down where the problem is coming from. Alex
236 236 # Schmolck reported this problem first.
237 237
238 238 # A useful post by Alex Martelli on this topic:
239 239 # Re: inconsistent value from __builtins__
240 240 # Von: Alex Martelli <aleaxit@yahoo.com>
241 241 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
242 242 # Gruppen: comp.lang.python
243 243
244 244 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
245 245 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
246 246 # > <type 'dict'>
247 247 # > >>> print type(__builtins__)
248 248 # > <type 'module'>
249 249 # > Is this difference in return value intentional?
250 250
251 251 # Well, it's documented that '__builtins__' can be either a dictionary
252 252 # or a module, and it's been that way for a long time. Whether it's
253 253 # intentional (or sensible), I don't know. In any case, the idea is
254 254 # that if you need to access the built-in namespace directly, you
255 255 # should start with "import __builtin__" (note, no 's') which will
256 256 # definitely give you a module. Yeah, it's somewhat confusing:-(.
257 257
258 258 if user_ns is None:
259 259 # Set __name__ to __main__ to better match the behavior of the
260 260 # normal interpreter.
261 261 user_ns = {'__name__' :'__main__',
262 262 '__builtins__' : __builtin__,
263 263 }
264 264
265 265 if user_global_ns is None:
266 266 user_global_ns = {}
267 267
268 268 # Assign namespaces
269 269 # This is the namespace where all normal user variables live
270 270 self.user_ns = user_ns
271 271 # Embedded instances require a separate namespace for globals.
272 272 # Normally this one is unused by non-embedded instances.
273 273 self.user_global_ns = user_global_ns
274 274 # A namespace to keep track of internal data structures to prevent
275 275 # them from cluttering user-visible stuff. Will be updated later
276 276 self.internal_ns = {}
277 277
278 278 # Namespace of system aliases. Each entry in the alias
279 279 # table must be a 2-tuple of the form (N,name), where N is the number
280 280 # of positional arguments of the alias.
281 281 self.alias_table = {}
282 282
283 283 # A table holding all the namespaces IPython deals with, so that
284 284 # introspection facilities can search easily.
285 285 self.ns_table = {'user':user_ns,
286 286 'user_global':user_global_ns,
287 287 'alias':self.alias_table,
288 288 'internal':self.internal_ns,
289 289 'builtin':__builtin__.__dict__
290 290 }
291 291
292 292 # The user namespace MUST have a pointer to the shell itself.
293 293 self.user_ns[name] = self
294 294
295 295 # We need to insert into sys.modules something that looks like a
296 296 # module but which accesses the IPython namespace, for shelve and
297 297 # pickle to work interactively. Normally they rely on getting
298 298 # everything out of __main__, but for embedding purposes each IPython
299 299 # instance has its own private namespace, so we can't go shoving
300 300 # everything into __main__.
301 301
302 302 # note, however, that we should only do this for non-embedded
303 303 # ipythons, which really mimic the __main__.__dict__ with their own
304 304 # namespace. Embedded instances, on the other hand, should not do
305 305 # this because they need to manage the user local/global namespaces
306 306 # only, but they live within a 'normal' __main__ (meaning, they
307 307 # shouldn't overtake the execution environment of the script they're
308 308 # embedded in).
309 309
310 310 if not embedded:
311 311 try:
312 312 main_name = self.user_ns['__name__']
313 313 except KeyError:
314 314 raise KeyError,'user_ns dictionary MUST have a "__name__" key'
315 315 else:
316 316 #print "pickle hack in place" # dbg
317 317 #print 'main_name:',main_name # dbg
318 318 sys.modules[main_name] = FakeModule(self.user_ns)
319 319
320 320 # List of input with multi-line handling.
321 321 # Fill its zero entry, user counter starts at 1
322 322 self.input_hist = InputList(['\n'])
323 323
324 324 # list of visited directories
325 325 try:
326 326 self.dir_hist = [os.getcwd()]
327 327 except IOError, e:
328 328 self.dir_hist = []
329 329
330 330 # dict of output history
331 331 self.output_hist = {}
332 332
333 333 # dict of things NOT to alias (keywords, builtins and some magics)
334 334 no_alias = {}
335 335 no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias']
336 336 for key in keyword.kwlist + no_alias_magics:
337 337 no_alias[key] = 1
338 338 no_alias.update(__builtin__.__dict__)
339 339 self.no_alias = no_alias
340 340
341 341 # make global variables for user access to these
342 342 self.user_ns['_ih'] = self.input_hist
343 343 self.user_ns['_oh'] = self.output_hist
344 344 self.user_ns['_dh'] = self.dir_hist
345 345
346 346 # user aliases to input and output histories
347 347 self.user_ns['In'] = self.input_hist
348 348 self.user_ns['Out'] = self.output_hist
349 349
350 350 # Object variable to store code object waiting execution. This is
351 351 # used mainly by the multithreaded shells, but it can come in handy in
352 352 # other situations. No need to use a Queue here, since it's a single
353 353 # item which gets cleared once run.
354 354 self.code_to_run = None
355 355
356 356 # escapes for automatic behavior on the command line
357 357 self.ESC_SHELL = '!'
358 358 self.ESC_HELP = '?'
359 359 self.ESC_MAGIC = '%'
360 360 self.ESC_QUOTE = ','
361 361 self.ESC_QUOTE2 = ';'
362 362 self.ESC_PAREN = '/'
363 363
364 364 # And their associated handlers
365 365 self.esc_handlers = {self.ESC_PAREN : self.handle_auto,
366 366 self.ESC_QUOTE : self.handle_auto,
367 367 self.ESC_QUOTE2 : self.handle_auto,
368 368 self.ESC_MAGIC : self.handle_magic,
369 369 self.ESC_HELP : self.handle_help,
370 370 self.ESC_SHELL : self.handle_shell_escape,
371 371 }
372 372
373 373 # class initializations
374 374 Magic.__init__(self,self)
375 375
376 376 # Python source parser/formatter for syntax highlighting
377 377 pyformat = PyColorize.Parser().format
378 378 self.pycolorize = lambda src: pyformat(src,'str',self.rc['colors'])
379 379
380 380 # hooks holds pointers used for user-side customizations
381 381 self.hooks = Struct()
382 382
383 383 # Set all default hooks, defined in the IPython.hooks module.
384 384 hooks = IPython.hooks
385 385 for hook_name in hooks.__all__:
386 386 self.set_hook(hook_name,getattr(hooks,hook_name))
387 387
388 388 # Flag to mark unconditional exit
389 389 self.exit_now = False
390 390
391 391 self.usage_min = """\
392 392 An enhanced console for Python.
393 393 Some of its features are:
394 394 - Readline support if the readline library is present.
395 395 - Tab completion in the local namespace.
396 396 - Logging of input, see command-line options.
397 397 - System shell escape via ! , eg !ls.
398 398 - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.)
399 399 - Keeps track of locally defined variables via %who, %whos.
400 400 - Show object information with a ? eg ?x or x? (use ?? for more info).
401 401 """
402 402 if usage: self.usage = usage
403 403 else: self.usage = self.usage_min
404 404
405 405 # Storage
406 406 self.rc = rc # This will hold all configuration information
407 407 self.pager = 'less'
408 408 # temporary files used for various purposes. Deleted at exit.
409 409 self.tempfiles = []
410 410
411 411 # Keep track of readline usage (later set by init_readline)
412 412 self.has_readline = False
413 413
414 414 # template for logfile headers. It gets resolved at runtime by the
415 415 # logstart method.
416 416 self.loghead_tpl = \
417 417 """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE ***
418 418 #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW
419 419 #log# opts = %s
420 420 #log# args = %s
421 421 #log# It is safe to make manual edits below here.
422 422 #log#-----------------------------------------------------------------------
423 423 """
424 424 # for pushd/popd management
425 425 try:
426 426 self.home_dir = get_home_dir()
427 427 except HomeDirError,msg:
428 428 fatal(msg)
429 429
430 430 self.dir_stack = [os.getcwd().replace(self.home_dir,'~')]
431 431
432 432 # Functions to call the underlying shell.
433 433
434 434 # utility to expand user variables via Itpl
435 435 self.var_expand = lambda cmd: str(ItplNS(cmd.replace('#','\#'),
436 436 self.user_ns))
437 437 # The first is similar to os.system, but it doesn't return a value,
438 438 # and it allows interpolation of variables in the user's namespace.
439 439 self.system = lambda cmd: shell(self.var_expand(cmd),
440 440 header='IPython system call: ',
441 441 verbose=self.rc.system_verbose)
442 442 # These are for getoutput and getoutputerror:
443 443 self.getoutput = lambda cmd: \
444 444 getoutput(self.var_expand(cmd),
445 445 header='IPython system call: ',
446 446 verbose=self.rc.system_verbose)
447 447 self.getoutputerror = lambda cmd: \
448 448 getoutputerror(str(ItplNS(cmd.replace('#','\#'),
449 449 self.user_ns)),
450 450 header='IPython system call: ',
451 451 verbose=self.rc.system_verbose)
452 452
453 453 # RegExp for splitting line contents into pre-char//first
454 454 # word-method//rest. For clarity, each group in on one line.
455 455
456 456 # WARNING: update the regexp if the above escapes are changed, as they
457 457 # are hardwired in.
458 458
459 459 # Don't get carried away with trying to make the autocalling catch too
460 460 # much: it's better to be conservative rather than to trigger hidden
461 461 # evals() somewhere and end up causing side effects.
462 462
463 463 self.line_split = re.compile(r'^([\s*,;/])'
464 464 r'([\?\w\.]+\w*\s*)'
465 465 r'(\(?.*$)')
466 466
467 467 # Original re, keep around for a while in case changes break something
468 468 #self.line_split = re.compile(r'(^[\s*!\?%,/]?)'
469 469 # r'(\s*[\?\w\.]+\w*\s*)'
470 470 # r'(\(?.*$)')
471 471
472 472 # RegExp to identify potential function names
473 473 self.re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$')
474 474 # RegExp to exclude strings with this start from autocalling
475 self.re_exclude_auto = re.compile('^[!=()<>,\*/\+-]|^is ')
475 self.re_exclude_auto = re.compile('^[!=()\[\]<>,\*/\+-]|^is ')
476 476
477 477 # try to catch also methods for stuff in lists/tuples/dicts: off
478 478 # (experimental). For this to work, the line_split regexp would need
479 479 # to be modified so it wouldn't break things at '['. That line is
480 480 # nasty enough that I shouldn't change it until I can test it _well_.
481 481 #self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$')
482 482
483 483 # keep track of where we started running (mainly for crash post-mortem)
484 484 self.starting_dir = os.getcwd()
485 485
486 486 # Various switches which can be set
487 487 self.CACHELENGTH = 5000 # this is cheap, it's just text
488 488 self.BANNER = "Python %(version)s on %(platform)s\n" % sys.__dict__
489 489 self.banner2 = banner2
490 490
491 491 # TraceBack handlers:
492 492
493 493 # Syntax error handler.
494 494 self.SyntaxTB = SyntaxTB(color_scheme='NoColor')
495 495
496 496 # The interactive one is initialized with an offset, meaning we always
497 497 # want to remove the topmost item in the traceback, which is our own
498 498 # internal code. Valid modes: ['Plain','Context','Verbose']
499 499 self.InteractiveTB = ultraTB.AutoFormattedTB(mode = 'Plain',
500 500 color_scheme='NoColor',
501 501 tb_offset = 1)
502 502
503 503 # IPython itself shouldn't crash. This will produce a detailed
504 504 # post-mortem if it does. But we only install the crash handler for
505 505 # non-threaded shells, the threaded ones use a normal verbose reporter
506 506 # and lose the crash handler. This is because exceptions in the main
507 507 # thread (such as in GUI code) propagate directly to sys.excepthook,
508 508 # and there's no point in printing crash dumps for every user exception.
509 509 if self.isthreaded:
510 510 sys.excepthook = ultraTB.FormattedTB()
511 511 else:
512 512 from IPython import CrashHandler
513 513 sys.excepthook = CrashHandler.CrashHandler(self)
514 514
515 515 # The instance will store a pointer to this, so that runtime code
516 516 # (such as magics) can access it. This is because during the
517 517 # read-eval loop, it gets temporarily overwritten (to deal with GUI
518 518 # frameworks).
519 519 self.sys_excepthook = sys.excepthook
520 520
521 521 # and add any custom exception handlers the user may have specified
522 522 self.set_custom_exc(*custom_exceptions)
523 523
524 524 # Object inspector
525 525 self.inspector = OInspect.Inspector(OInspect.InspectColors,
526 526 PyColorize.ANSICodeColors,
527 527 'NoColor')
528 528 # indentation management
529 529 self.autoindent = False
530 530 self.indent_current_nsp = 0
531 531 self.indent_current = '' # actual indent string
532 532
533 533 # Make some aliases automatically
534 534 # Prepare list of shell aliases to auto-define
535 535 if os.name == 'posix':
536 536 auto_alias = ('mkdir mkdir', 'rmdir rmdir',
537 537 'mv mv -i','rm rm -i','cp cp -i',
538 538 'cat cat','less less','clear clear',
539 539 # a better ls
540 540 'ls ls -F',
541 541 # long ls
542 542 'll ls -lF',
543 543 # color ls
544 544 'lc ls -F -o --color',
545 545 # ls normal files only
546 546 'lf ls -F -o --color %l | grep ^-',
547 547 # ls symbolic links
548 548 'lk ls -F -o --color %l | grep ^l',
549 549 # directories or links to directories,
550 550 'ldir ls -F -o --color %l | grep /$',
551 551 # things which are executable
552 552 'lx ls -F -o --color %l | grep ^-..x',
553 553 )
554 554 elif os.name in ['nt','dos']:
555 555 auto_alias = ('dir dir /on', 'ls dir /on',
556 556 'ddir dir /ad /on', 'ldir dir /ad /on',
557 557 'mkdir mkdir','rmdir rmdir','echo echo',
558 558 'ren ren','cls cls','copy copy')
559 559 else:
560 560 auto_alias = ()
561 561 self.auto_alias = map(lambda s:s.split(None,1),auto_alias)
562 562 # Call the actual (public) initializer
563 563 self.init_auto_alias()
564 564 # end __init__
565 565
566 566 def post_config_initialization(self):
567 567 """Post configuration init method
568 568
569 569 This is called after the configuration files have been processed to
570 570 'finalize' the initialization."""
571 571
572 572 rc = self.rc
573 573
574 574 # Load readline proper
575 575 if rc.readline:
576 576 self.init_readline()
577 577
578 578 # log system
579 579 self.logger = Logger(self,logfname='ipython_log.py',logmode='rotate')
580 580 # local shortcut, this is used a LOT
581 581 self.log = self.logger.log
582 582
583 583 # Initialize cache, set in/out prompts and printing system
584 584 self.outputcache = CachedOutput(self,
585 585 rc.cache_size,
586 586 rc.pprint,
587 587 input_sep = rc.separate_in,
588 588 output_sep = rc.separate_out,
589 589 output_sep2 = rc.separate_out2,
590 590 ps1 = rc.prompt_in1,
591 591 ps2 = rc.prompt_in2,
592 592 ps_out = rc.prompt_out,
593 593 pad_left = rc.prompts_pad_left)
594 594
595 595 # user may have over-ridden the default print hook:
596 596 try:
597 597 self.outputcache.__class__.display = self.hooks.display
598 598 except AttributeError:
599 599 pass
600 600
601 601 # I don't like assigning globally to sys, because it means when embedding
602 602 # instances, each embedded instance overrides the previous choice. But
603 603 # sys.displayhook seems to be called internally by exec, so I don't see a
604 604 # way around it.
605 605 sys.displayhook = self.outputcache
606 606
607 607 # Set user colors (don't do it in the constructor above so that it
608 608 # doesn't crash if colors option is invalid)
609 609 self.magic_colors(rc.colors)
610 610
611 611 # Set calling of pdb on exceptions
612 612 self.call_pdb = rc.pdb
613 613
614 614 # Load user aliases
615 615 for alias in rc.alias:
616 616 self.magic_alias(alias)
617 617
618 618 # dynamic data that survives through sessions
619 619 # XXX make the filename a config option?
620 620 persist_base = 'persist'
621 621 if rc.profile:
622 622 persist_base += '_%s' % rc.profile
623 623 self.persist_fname = os.path.join(rc.ipythondir,persist_base)
624 624
625 625 try:
626 626 self.persist = pickle.load(file(self.persist_fname))
627 627 except:
628 628 self.persist = {}
629 629
630 630
631 631 for (key, value) in [(k[2:],v) for (k,v) in self.persist.items() if k.startswith('S:')]:
632 632 try:
633 633 obj = pickle.loads(value)
634 634 except:
635 635
636 636 print "Unable to restore variable '%s', ignoring (use %%store -d to forget!)" % key
637 637 print "The error was:",sys.exc_info()[0]
638 638 continue
639 639
640 640
641 641 self.user_ns[key] = obj
642 642
643 643 def add_builtins(self):
644 644 """Store ipython references into the builtin namespace.
645 645
646 646 Some parts of ipython operate via builtins injected here, which hold a
647 647 reference to IPython itself."""
648 648
649 649 builtins_new = dict(__IPYTHON__ = self,
650 650 ip_set_hook = self.set_hook,
651 651 jobs = self.jobs,
652 652 ipmagic = self.ipmagic,
653 653 ipalias = self.ipalias,
654 654 ipsystem = self.ipsystem,
655 655 )
656 656 for biname,bival in builtins_new.items():
657 657 try:
658 658 # store the orignal value so we can restore it
659 659 self.builtins_added[biname] = __builtin__.__dict__[biname]
660 660 except KeyError:
661 661 # or mark that it wasn't defined, and we'll just delete it at
662 662 # cleanup
663 663 self.builtins_added[biname] = Undefined
664 664 __builtin__.__dict__[biname] = bival
665 665
666 666 # Keep in the builtins a flag for when IPython is active. We set it
667 667 # with setdefault so that multiple nested IPythons don't clobber one
668 668 # another. Each will increase its value by one upon being activated,
669 669 # which also gives us a way to determine the nesting level.
670 670 __builtin__.__dict__.setdefault('__IPYTHON__active',0)
671 671
672 672 def clean_builtins(self):
673 673 """Remove any builtins which might have been added by add_builtins, or
674 674 restore overwritten ones to their previous values."""
675 675 for biname,bival in self.builtins_added.items():
676 676 if bival is Undefined:
677 677 del __builtin__.__dict__[biname]
678 678 else:
679 679 __builtin__.__dict__[biname] = bival
680 680 self.builtins_added.clear()
681 681
682 682 def set_hook(self,name,hook):
683 683 """set_hook(name,hook) -> sets an internal IPython hook.
684 684
685 685 IPython exposes some of its internal API as user-modifiable hooks. By
686 686 resetting one of these hooks, you can modify IPython's behavior to
687 687 call at runtime your own routines."""
688 688
689 689 # At some point in the future, this should validate the hook before it
690 690 # accepts it. Probably at least check that the hook takes the number
691 691 # of args it's supposed to.
692 692 setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__))
693 693
694 694 def set_custom_exc(self,exc_tuple,handler):
695 695 """set_custom_exc(exc_tuple,handler)
696 696
697 697 Set a custom exception handler, which will be called if any of the
698 698 exceptions in exc_tuple occur in the mainloop (specifically, in the
699 699 runcode() method.
700 700
701 701 Inputs:
702 702
703 703 - exc_tuple: a *tuple* of valid exceptions to call the defined
704 704 handler for. It is very important that you use a tuple, and NOT A
705 705 LIST here, because of the way Python's except statement works. If
706 706 you only want to trap a single exception, use a singleton tuple:
707 707
708 708 exc_tuple == (MyCustomException,)
709 709
710 710 - handler: this must be defined as a function with the following
711 711 basic interface: def my_handler(self,etype,value,tb).
712 712
713 713 This will be made into an instance method (via new.instancemethod)
714 714 of IPython itself, and it will be called if any of the exceptions
715 715 listed in the exc_tuple are caught. If the handler is None, an
716 716 internal basic one is used, which just prints basic info.
717 717
718 718 WARNING: by putting in your own exception handler into IPython's main
719 719 execution loop, you run a very good chance of nasty crashes. This
720 720 facility should only be used if you really know what you are doing."""
721 721
722 722 assert type(exc_tuple)==type(()) , \
723 723 "The custom exceptions must be given AS A TUPLE."
724 724
725 725 def dummy_handler(self,etype,value,tb):
726 726 print '*** Simple custom exception handler ***'
727 727 print 'Exception type :',etype
728 728 print 'Exception value:',value
729 729 print 'Traceback :',tb
730 730 print 'Source code :','\n'.join(self.buffer)
731 731
732 732 if handler is None: handler = dummy_handler
733 733
734 734 self.CustomTB = new.instancemethod(handler,self,self.__class__)
735 735 self.custom_exceptions = exc_tuple
736 736
737 737 def set_custom_completer(self,completer,pos=0):
738 738 """set_custom_completer(completer,pos=0)
739 739
740 740 Adds a new custom completer function.
741 741
742 742 The position argument (defaults to 0) is the index in the completers
743 743 list where you want the completer to be inserted."""
744 744
745 745 newcomp = new.instancemethod(completer,self.Completer,
746 746 self.Completer.__class__)
747 747 self.Completer.matchers.insert(pos,newcomp)
748 748
749 749 def _get_call_pdb(self):
750 750 return self._call_pdb
751 751
752 752 def _set_call_pdb(self,val):
753 753
754 754 if val not in (0,1,False,True):
755 755 raise ValueError,'new call_pdb value must be boolean'
756 756
757 757 # store value in instance
758 758 self._call_pdb = val
759 759
760 760 # notify the actual exception handlers
761 761 self.InteractiveTB.call_pdb = val
762 762 if self.isthreaded:
763 763 try:
764 764 self.sys_excepthook.call_pdb = val
765 765 except:
766 766 warn('Failed to activate pdb for threaded exception handler')
767 767
768 768 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
769 769 'Control auto-activation of pdb at exceptions')
770 770
771 771
772 772 # These special functions get installed in the builtin namespace, to
773 773 # provide programmatic (pure python) access to magics, aliases and system
774 774 # calls. This is important for logging, user scripting, and more.
775 775
776 776 # We are basically exposing, via normal python functions, the three
777 777 # mechanisms in which ipython offers special call modes (magics for
778 778 # internal control, aliases for direct system access via pre-selected
779 779 # names, and !cmd for calling arbitrary system commands).
780 780
781 781 def ipmagic(self,arg_s):
782 782 """Call a magic function by name.
783 783
784 784 Input: a string containing the name of the magic function to call and any
785 785 additional arguments to be passed to the magic.
786 786
787 787 ipmagic('name -opt foo bar') is equivalent to typing at the ipython
788 788 prompt:
789 789
790 790 In[1]: %name -opt foo bar
791 791
792 792 To call a magic without arguments, simply use ipmagic('name').
793 793
794 794 This provides a proper Python function to call IPython's magics in any
795 795 valid Python code you can type at the interpreter, including loops and
796 796 compound statements. It is added by IPython to the Python builtin
797 797 namespace upon initialization."""
798 798
799 799 args = arg_s.split(' ',1)
800 800 magic_name = args[0]
801 801 if magic_name.startswith(self.ESC_MAGIC):
802 802 magic_name = magic_name[1:]
803 803 try:
804 804 magic_args = args[1]
805 805 except IndexError:
806 806 magic_args = ''
807 807 fn = getattr(self,'magic_'+magic_name,None)
808 808 if fn is None:
809 809 error("Magic function `%s` not found." % magic_name)
810 810 else:
811 811 magic_args = self.var_expand(magic_args)
812 812 return fn(magic_args)
813 813
814 814 def ipalias(self,arg_s):
815 815 """Call an alias by name.
816 816
817 817 Input: a string containing the name of the alias to call and any
818 818 additional arguments to be passed to the magic.
819 819
820 820 ipalias('name -opt foo bar') is equivalent to typing at the ipython
821 821 prompt:
822 822
823 823 In[1]: name -opt foo bar
824 824
825 825 To call an alias without arguments, simply use ipalias('name').
826 826
827 827 This provides a proper Python function to call IPython's aliases in any
828 828 valid Python code you can type at the interpreter, including loops and
829 829 compound statements. It is added by IPython to the Python builtin
830 830 namespace upon initialization."""
831 831
832 832 args = arg_s.split(' ',1)
833 833 alias_name = args[0]
834 834 try:
835 835 alias_args = args[1]
836 836 except IndexError:
837 837 alias_args = ''
838 838 if alias_name in self.alias_table:
839 839 self.call_alias(alias_name,alias_args)
840 840 else:
841 841 error("Alias `%s` not found." % alias_name)
842 842
843 843 def ipsystem(self,arg_s):
844 844 """Make a system call, using IPython."""
845 845 self.system(arg_s)
846 846
847 847 def complete(self,text):
848 848 """Return a sorted list of all possible completions on text.
849 849
850 850 Inputs:
851 851
852 852 - text: a string of text to be completed on.
853 853
854 854 This is a wrapper around the completion mechanism, similar to what
855 855 readline does at the command line when the TAB key is hit. By
856 856 exposing it as a method, it can be used by other non-readline
857 857 environments (such as GUIs) for text completion.
858 858
859 859 Simple usage example:
860 860
861 861 In [1]: x = 'hello'
862 862
863 863 In [2]: __IP.complete('x.l')
864 864 Out[2]: ['x.ljust', 'x.lower', 'x.lstrip']"""
865 865
866 866 complete = self.Completer.complete
867 867 state = 0
868 868 # use a dict so we get unique keys, since ipyhton's multiple
869 869 # completers can return duplicates.
870 870 comps = {}
871 871 while True:
872 872 newcomp = complete(text,state)
873 873 if newcomp is None:
874 874 break
875 875 comps[newcomp] = 1
876 876 state += 1
877 877 outcomps = comps.keys()
878 878 outcomps.sort()
879 879 return outcomps
880 880
881 881 def set_completer_frame(self, frame):
882 882 if frame:
883 883 self.Completer.namespace = frame.f_locals
884 884 self.Completer.global_namespace = frame.f_globals
885 885 else:
886 886 self.Completer.namespace = self.user_ns
887 887 self.Completer.global_namespace = self.user_global_ns
888 888
889 889 def init_auto_alias(self):
890 890 """Define some aliases automatically.
891 891
892 892 These are ALL parameter-less aliases"""
893 893 for alias,cmd in self.auto_alias:
894 894 self.alias_table[alias] = (0,cmd)
895 895
896 896 def alias_table_validate(self,verbose=0):
897 897 """Update information about the alias table.
898 898
899 899 In particular, make sure no Python keywords/builtins are in it."""
900 900
901 901 no_alias = self.no_alias
902 902 for k in self.alias_table.keys():
903 903 if k in no_alias:
904 904 del self.alias_table[k]
905 905 if verbose:
906 906 print ("Deleting alias <%s>, it's a Python "
907 907 "keyword or builtin." % k)
908 908
909 909 def set_autoindent(self,value=None):
910 910 """Set the autoindent flag, checking for readline support.
911 911
912 912 If called with no arguments, it acts as a toggle."""
913 913
914 914 if not self.has_readline:
915 915 if os.name == 'posix':
916 916 warn("The auto-indent feature requires the readline library")
917 917 self.autoindent = 0
918 918 return
919 919 if value is None:
920 920 self.autoindent = not self.autoindent
921 921 else:
922 922 self.autoindent = value
923 923
924 924 def rc_set_toggle(self,rc_field,value=None):
925 925 """Set or toggle a field in IPython's rc config. structure.
926 926
927 927 If called with no arguments, it acts as a toggle.
928 928
929 929 If called with a non-existent field, the resulting AttributeError
930 930 exception will propagate out."""
931 931
932 932 rc_val = getattr(self.rc,rc_field)
933 933 if value is None:
934 934 value = not rc_val
935 935 setattr(self.rc,rc_field,value)
936 936
937 937 def user_setup(self,ipythondir,rc_suffix,mode='install'):
938 938 """Install the user configuration directory.
939 939
940 940 Can be called when running for the first time or to upgrade the user's
941 941 .ipython/ directory with the mode parameter. Valid modes are 'install'
942 942 and 'upgrade'."""
943 943
944 944 def wait():
945 945 try:
946 946 raw_input("Please press <RETURN> to start IPython.")
947 947 except EOFError:
948 948 print >> Term.cout
949 949 print '*'*70
950 950
951 951 cwd = os.getcwd() # remember where we started
952 952 glb = glob.glob
953 953 print '*'*70
954 954 if mode == 'install':
955 955 print \
956 956 """Welcome to IPython. I will try to create a personal configuration directory
957 957 where you can customize many aspects of IPython's functionality in:\n"""
958 958 else:
959 959 print 'I am going to upgrade your configuration in:'
960 960
961 961 print ipythondir
962 962
963 963 rcdirend = os.path.join('IPython','UserConfig')
964 964 cfg = lambda d: os.path.join(d,rcdirend)
965 965 try:
966 966 rcdir = filter(os.path.isdir,map(cfg,sys.path))[0]
967 967 except IOError:
968 968 warning = """
969 969 Installation error. IPython's directory was not found.
970 970
971 971 Check the following:
972 972
973 973 The ipython/IPython directory should be in a directory belonging to your
974 974 PYTHONPATH environment variable (that is, it should be in a directory
975 975 belonging to sys.path). You can copy it explicitly there or just link to it.
976 976
977 977 IPython will proceed with builtin defaults.
978 978 """
979 979 warn(warning)
980 980 wait()
981 981 return
982 982
983 983 if mode == 'install':
984 984 try:
985 985 shutil.copytree(rcdir,ipythondir)
986 986 os.chdir(ipythondir)
987 987 rc_files = glb("ipythonrc*")
988 988 for rc_file in rc_files:
989 989 os.rename(rc_file,rc_file+rc_suffix)
990 990 except:
991 991 warning = """
992 992
993 993 There was a problem with the installation:
994 994 %s
995 995 Try to correct it or contact the developers if you think it's a bug.
996 996 IPython will proceed with builtin defaults.""" % sys.exc_info()[1]
997 997 warn(warning)
998 998 wait()
999 999 return
1000 1000
1001 1001 elif mode == 'upgrade':
1002 1002 try:
1003 1003 os.chdir(ipythondir)
1004 1004 except:
1005 1005 print """
1006 1006 Can not upgrade: changing to directory %s failed. Details:
1007 1007 %s
1008 1008 """ % (ipythondir,sys.exc_info()[1])
1009 1009 wait()
1010 1010 return
1011 1011 else:
1012 1012 sources = glb(os.path.join(rcdir,'[A-Za-z]*'))
1013 1013 for new_full_path in sources:
1014 1014 new_filename = os.path.basename(new_full_path)
1015 1015 if new_filename.startswith('ipythonrc'):
1016 1016 new_filename = new_filename + rc_suffix
1017 1017 # The config directory should only contain files, skip any
1018 1018 # directories which may be there (like CVS)
1019 1019 if os.path.isdir(new_full_path):
1020 1020 continue
1021 1021 if os.path.exists(new_filename):
1022 1022 old_file = new_filename+'.old'
1023 1023 if os.path.exists(old_file):
1024 1024 os.remove(old_file)
1025 1025 os.rename(new_filename,old_file)
1026 1026 shutil.copy(new_full_path,new_filename)
1027 1027 else:
1028 1028 raise ValueError,'unrecognized mode for install:',`mode`
1029 1029
1030 1030 # Fix line-endings to those native to each platform in the config
1031 1031 # directory.
1032 1032 try:
1033 1033 os.chdir(ipythondir)
1034 1034 except:
1035 1035 print """
1036 1036 Problem: changing to directory %s failed.
1037 1037 Details:
1038 1038 %s
1039 1039
1040 1040 Some configuration files may have incorrect line endings. This should not
1041 1041 cause any problems during execution. """ % (ipythondir,sys.exc_info()[1])
1042 1042 wait()
1043 1043 else:
1044 1044 for fname in glb('ipythonrc*'):
1045 1045 try:
1046 1046 native_line_ends(fname,backup=0)
1047 1047 except IOError:
1048 1048 pass
1049 1049
1050 1050 if mode == 'install':
1051 1051 print """
1052 1052 Successful installation!
1053 1053
1054 1054 Please read the sections 'Initial Configuration' and 'Quick Tips' in the
1055 1055 IPython manual (there are both HTML and PDF versions supplied with the
1056 1056 distribution) to make sure that your system environment is properly configured
1057 1057 to take advantage of IPython's features."""
1058 1058 else:
1059 1059 print """
1060 1060 Successful upgrade!
1061 1061
1062 1062 All files in your directory:
1063 1063 %(ipythondir)s
1064 1064 which would have been overwritten by the upgrade were backed up with a .old
1065 1065 extension. If you had made particular customizations in those files you may
1066 1066 want to merge them back into the new files.""" % locals()
1067 1067 wait()
1068 1068 os.chdir(cwd)
1069 1069 # end user_setup()
1070 1070
1071 1071 def atexit_operations(self):
1072 1072 """This will be executed at the time of exit.
1073 1073
1074 1074 Saving of persistent data should be performed here. """
1075 1075
1076 1076 # input history
1077 1077 self.savehist()
1078 1078
1079 1079 # Cleanup all tempfiles left around
1080 1080 for tfile in self.tempfiles:
1081 1081 try:
1082 1082 os.unlink(tfile)
1083 1083 except OSError:
1084 1084 pass
1085 1085
1086 1086 # save the "persistent data" catch-all dictionary
1087 1087 try:
1088 1088 pickle.dump(self.persist, open(self.persist_fname,"w"))
1089 1089 except:
1090 1090 print "*** ERROR *** persistent data saving failed."
1091 1091
1092 1092 def savehist(self):
1093 1093 """Save input history to a file (via readline library)."""
1094 1094 try:
1095 1095 self.readline.write_history_file(self.histfile)
1096 1096 except:
1097 1097 print 'Unable to save IPython command history to file: ' + \
1098 1098 `self.histfile`
1099 1099
1100 1100 def pre_readline(self):
1101 1101 """readline hook to be used at the start of each line.
1102 1102
1103 1103 Currently it handles auto-indent only."""
1104 1104
1105 1105 self.readline.insert_text(self.indent_current)
1106 1106
1107 1107 def init_readline(self):
1108 1108 """Command history completion/saving/reloading."""
1109 1109 try:
1110 1110 import readline
1111 1111 except ImportError:
1112 1112 self.has_readline = 0
1113 1113 self.readline = None
1114 1114 # no point in bugging windows users with this every time:
1115 1115 if os.name == 'posix':
1116 1116 warn('Readline services not available on this platform.')
1117 1117 else:
1118 1118 import atexit
1119 1119 from IPython.completer import IPCompleter
1120 1120 self.Completer = IPCompleter(self,
1121 1121 self.user_ns,
1122 1122 self.user_global_ns,
1123 1123 self.rc.readline_omit__names,
1124 1124 self.alias_table)
1125 1125
1126 1126 # Platform-specific configuration
1127 1127 if os.name == 'nt':
1128 1128 self.readline_startup_hook = readline.set_pre_input_hook
1129 1129 else:
1130 1130 self.readline_startup_hook = readline.set_startup_hook
1131 1131
1132 1132 # Load user's initrc file (readline config)
1133 1133 inputrc_name = os.environ.get('INPUTRC')
1134 1134 if inputrc_name is None:
1135 1135 home_dir = get_home_dir()
1136 1136 if home_dir is not None:
1137 1137 inputrc_name = os.path.join(home_dir,'.inputrc')
1138 1138 if os.path.isfile(inputrc_name):
1139 1139 try:
1140 1140 readline.read_init_file(inputrc_name)
1141 1141 except:
1142 1142 warn('Problems reading readline initialization file <%s>'
1143 1143 % inputrc_name)
1144 1144
1145 1145 self.has_readline = 1
1146 1146 self.readline = readline
1147 1147 # save this in sys so embedded copies can restore it properly
1148 1148 sys.ipcompleter = self.Completer.complete
1149 1149 readline.set_completer(self.Completer.complete)
1150 1150
1151 1151 # Configure readline according to user's prefs
1152 1152 for rlcommand in self.rc.readline_parse_and_bind:
1153 1153 readline.parse_and_bind(rlcommand)
1154 1154
1155 1155 # remove some chars from the delimiters list
1156 1156 delims = readline.get_completer_delims()
1157 1157 delims = delims.translate(string._idmap,
1158 1158 self.rc.readline_remove_delims)
1159 1159 readline.set_completer_delims(delims)
1160 1160 # otherwise we end up with a monster history after a while:
1161 1161 readline.set_history_length(1000)
1162 1162 try:
1163 1163 #print '*** Reading readline history' # dbg
1164 1164 readline.read_history_file(self.histfile)
1165 1165 except IOError:
1166 1166 pass # It doesn't exist yet.
1167 1167
1168 1168 atexit.register(self.atexit_operations)
1169 1169 del atexit
1170 1170
1171 1171 # Configure auto-indent for all platforms
1172 1172 self.set_autoindent(self.rc.autoindent)
1173 1173
1174 1174 def _should_recompile(self,e):
1175 1175 """Utility routine for edit_syntax_error"""
1176 1176
1177 1177 if e.filename in ('<ipython console>','<input>','<string>',
1178 1178 '<console>'):
1179 1179 return False
1180 1180 try:
1181 1181 if not ask_yes_no('Return to editor to correct syntax error? '
1182 1182 '[Y/n] ','y'):
1183 1183 return False
1184 1184 except EOFError:
1185 1185 return False
1186 1186 self.hooks.fix_error_editor(e.filename,e.lineno,e.offset,e.msg)
1187 1187 return True
1188 1188
1189 1189 def edit_syntax_error(self):
1190 1190 """The bottom half of the syntax error handler called in the main loop.
1191 1191
1192 1192 Loop until syntax error is fixed or user cancels.
1193 1193 """
1194 1194
1195 1195 while self.SyntaxTB.last_syntax_error:
1196 1196 # copy and clear last_syntax_error
1197 1197 err = self.SyntaxTB.clear_err_state()
1198 1198 if not self._should_recompile(err):
1199 1199 return
1200 1200 try:
1201 1201 # may set last_syntax_error again if a SyntaxError is raised
1202 1202 self.safe_execfile(err.filename,self.shell.user_ns)
1203 1203 except:
1204 1204 self.showtraceback()
1205 1205 else:
1206 1206 f = file(err.filename)
1207 1207 try:
1208 1208 sys.displayhook(f.read())
1209 1209 finally:
1210 1210 f.close()
1211 1211
1212 1212 def showsyntaxerror(self, filename=None):
1213 1213 """Display the syntax error that just occurred.
1214 1214
1215 1215 This doesn't display a stack trace because there isn't one.
1216 1216
1217 1217 If a filename is given, it is stuffed in the exception instead
1218 1218 of what was there before (because Python's parser always uses
1219 1219 "<string>" when reading from a string).
1220 1220 """
1221 1221 etype, value, last_traceback = sys.exc_info()
1222 1222 if filename and etype is SyntaxError:
1223 1223 # Work hard to stuff the correct filename in the exception
1224 1224 try:
1225 1225 msg, (dummy_filename, lineno, offset, line) = value
1226 1226 except:
1227 1227 # Not the format we expect; leave it alone
1228 1228 pass
1229 1229 else:
1230 1230 # Stuff in the right filename
1231 1231 try:
1232 1232 # Assume SyntaxError is a class exception
1233 1233 value = SyntaxError(msg, (filename, lineno, offset, line))
1234 1234 except:
1235 1235 # If that failed, assume SyntaxError is a string
1236 1236 value = msg, (filename, lineno, offset, line)
1237 1237 self.SyntaxTB(etype,value,[])
1238 1238
1239 1239 def debugger(self):
1240 1240 """Call the pdb debugger."""
1241 1241
1242 1242 if not self.rc.pdb:
1243 1243 return
1244 1244 pdb.pm()
1245 1245
1246 1246 def showtraceback(self,exc_tuple = None,filename=None):
1247 1247 """Display the exception that just occurred."""
1248 1248
1249 1249 # Though this won't be called by syntax errors in the input line,
1250 1250 # there may be SyntaxError cases whith imported code.
1251 1251 if exc_tuple is None:
1252 1252 type, value, tb = sys.exc_info()
1253 1253 else:
1254 1254 type, value, tb = exc_tuple
1255 1255 if type is SyntaxError:
1256 1256 self.showsyntaxerror(filename)
1257 1257 else:
1258 1258 self.InteractiveTB()
1259 1259 if self.InteractiveTB.call_pdb and self.has_readline:
1260 1260 # pdb mucks up readline, fix it back
1261 1261 self.readline.set_completer(self.Completer.complete)
1262 1262
1263 1263 def mainloop(self,banner=None):
1264 1264 """Creates the local namespace and starts the mainloop.
1265 1265
1266 1266 If an optional banner argument is given, it will override the
1267 1267 internally created default banner."""
1268 1268
1269 1269 if self.rc.c: # Emulate Python's -c option
1270 1270 self.exec_init_cmd()
1271 1271 if banner is None:
1272 1272 if self.rc.banner:
1273 1273 banner = self.BANNER+self.banner2
1274 1274 else:
1275 1275 banner = ''
1276 1276 self.interact(banner)
1277 1277
1278 1278 def exec_init_cmd(self):
1279 1279 """Execute a command given at the command line.
1280 1280
1281 1281 This emulates Python's -c option."""
1282 1282
1283 1283 sys.argv = ['-c']
1284 1284 self.push(self.rc.c)
1285 1285
1286 1286 def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0):
1287 1287 """Embeds IPython into a running python program.
1288 1288
1289 1289 Input:
1290 1290
1291 1291 - header: An optional header message can be specified.
1292 1292
1293 1293 - local_ns, global_ns: working namespaces. If given as None, the
1294 1294 IPython-initialized one is updated with __main__.__dict__, so that
1295 1295 program variables become visible but user-specific configuration
1296 1296 remains possible.
1297 1297
1298 1298 - stack_depth: specifies how many levels in the stack to go to
1299 1299 looking for namespaces (when local_ns and global_ns are None). This
1300 1300 allows an intermediate caller to make sure that this function gets
1301 1301 the namespace from the intended level in the stack. By default (0)
1302 1302 it will get its locals and globals from the immediate caller.
1303 1303
1304 1304 Warning: it's possible to use this in a program which is being run by
1305 1305 IPython itself (via %run), but some funny things will happen (a few
1306 1306 globals get overwritten). In the future this will be cleaned up, as
1307 1307 there is no fundamental reason why it can't work perfectly."""
1308 1308
1309 1309 # Get locals and globals from caller
1310 1310 if local_ns is None or global_ns is None:
1311 1311 call_frame = sys._getframe(stack_depth).f_back
1312 1312
1313 1313 if local_ns is None:
1314 1314 local_ns = call_frame.f_locals
1315 1315 if global_ns is None:
1316 1316 global_ns = call_frame.f_globals
1317 1317
1318 1318 # Update namespaces and fire up interpreter
1319 1319
1320 1320 # The global one is easy, we can just throw it in
1321 1321 self.user_global_ns = global_ns
1322 1322
1323 1323 # but the user/local one is tricky: ipython needs it to store internal
1324 1324 # data, but we also need the locals. We'll copy locals in the user
1325 1325 # one, but will track what got copied so we can delete them at exit.
1326 1326 # This is so that a later embedded call doesn't see locals from a
1327 1327 # previous call (which most likely existed in a separate scope).
1328 1328 local_varnames = local_ns.keys()
1329 1329 self.user_ns.update(local_ns)
1330 1330
1331 1331 # Patch for global embedding to make sure that things don't overwrite
1332 1332 # user globals accidentally. Thanks to Richard <rxe@renre-europe.com>
1333 1333 # FIXME. Test this a bit more carefully (the if.. is new)
1334 1334 if local_ns is None and global_ns is None:
1335 1335 self.user_global_ns.update(__main__.__dict__)
1336 1336
1337 1337 # make sure the tab-completer has the correct frame information, so it
1338 1338 # actually completes using the frame's locals/globals
1339 1339 self.set_completer_frame(call_frame)
1340 1340
1341 1341 # before activating the interactive mode, we need to make sure that
1342 1342 # all names in the builtin namespace needed by ipython point to
1343 1343 # ourselves, and not to other instances.
1344 1344 self.add_builtins()
1345 1345
1346 1346 self.interact(header)
1347 1347
1348 1348 # now, purge out the user namespace from anything we might have added
1349 1349 # from the caller's local namespace
1350 1350 delvar = self.user_ns.pop
1351 1351 for var in local_varnames:
1352 1352 delvar(var,None)
1353 1353 # and clean builtins we may have overridden
1354 1354 self.clean_builtins()
1355 1355
1356 1356 def interact(self, banner=None):
1357 1357 """Closely emulate the interactive Python console.
1358 1358
1359 1359 The optional banner argument specify the banner to print
1360 1360 before the first interaction; by default it prints a banner
1361 1361 similar to the one printed by the real Python interpreter,
1362 1362 followed by the current class name in parentheses (so as not
1363 1363 to confuse this with the real interpreter -- since it's so
1364 1364 close!).
1365 1365
1366 1366 """
1367 1367 cprt = 'Type "copyright", "credits" or "license" for more information.'
1368 1368 if banner is None:
1369 1369 self.write("Python %s on %s\n%s\n(%s)\n" %
1370 1370 (sys.version, sys.platform, cprt,
1371 1371 self.__class__.__name__))
1372 1372 else:
1373 1373 self.write(banner)
1374 1374
1375 1375 more = 0
1376 1376
1377 1377 # Mark activity in the builtins
1378 1378 __builtin__.__dict__['__IPYTHON__active'] += 1
1379 1379
1380 1380 # exit_now is set by a call to %Exit or %Quit
1381 1381 self.exit_now = False
1382 1382 while not self.exit_now:
1383 1383
1384 1384 try:
1385 1385 if more:
1386 1386 prompt = self.outputcache.prompt2
1387 1387 if self.autoindent:
1388 1388 self.readline_startup_hook(self.pre_readline)
1389 1389 else:
1390 1390 prompt = self.outputcache.prompt1
1391 1391 try:
1392 1392 line = self.raw_input(prompt,more)
1393 1393 if self.autoindent:
1394 1394 self.readline_startup_hook(None)
1395 1395 except EOFError:
1396 1396 if self.autoindent:
1397 1397 self.readline_startup_hook(None)
1398 1398 self.write("\n")
1399 1399 self.exit()
1400 1400 else:
1401 1401 more = self.push(line)
1402 1402
1403 1403 if (self.SyntaxTB.last_syntax_error and
1404 1404 self.rc.autoedit_syntax):
1405 1405 self.edit_syntax_error()
1406 1406
1407 1407 except KeyboardInterrupt:
1408 1408 self.write("\nKeyboardInterrupt\n")
1409 1409 self.resetbuffer()
1410 1410 more = 0
1411 1411 # keep cache in sync with the prompt counter:
1412 1412 self.outputcache.prompt_count -= 1
1413 1413
1414 1414 if self.autoindent:
1415 1415 self.indent_current_nsp = 0
1416 1416 self.indent_current = ' '* self.indent_current_nsp
1417 1417
1418 1418 except bdb.BdbQuit:
1419 1419 warn("The Python debugger has exited with a BdbQuit exception.\n"
1420 1420 "Because of how pdb handles the stack, it is impossible\n"
1421 1421 "for IPython to properly format this particular exception.\n"
1422 1422 "IPython will resume normal operation.")
1423 1423
1424 1424 # We are off again...
1425 1425 __builtin__.__dict__['__IPYTHON__active'] -= 1
1426 1426
1427 1427 def excepthook(self, type, value, tb):
1428 1428 """One more defense for GUI apps that call sys.excepthook.
1429 1429
1430 1430 GUI frameworks like wxPython trap exceptions and call
1431 1431 sys.excepthook themselves. I guess this is a feature that
1432 1432 enables them to keep running after exceptions that would
1433 1433 otherwise kill their mainloop. This is a bother for IPython
1434 1434 which excepts to catch all of the program exceptions with a try:
1435 1435 except: statement.
1436 1436
1437 1437 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1438 1438 any app directly invokes sys.excepthook, it will look to the user like
1439 1439 IPython crashed. In order to work around this, we can disable the
1440 1440 CrashHandler and replace it with this excepthook instead, which prints a
1441 1441 regular traceback using our InteractiveTB. In this fashion, apps which
1442 1442 call sys.excepthook will generate a regular-looking exception from
1443 1443 IPython, and the CrashHandler will only be triggered by real IPython
1444 1444 crashes.
1445 1445
1446 1446 This hook should be used sparingly, only in places which are not likely
1447 1447 to be true IPython errors.
1448 1448 """
1449 1449
1450 1450 self.InteractiveTB(type, value, tb, tb_offset=0)
1451 1451 if self.InteractiveTB.call_pdb and self.has_readline:
1452 1452 self.readline.set_completer(self.Completer.complete)
1453 1453
1454 1454 def call_alias(self,alias,rest=''):
1455 1455 """Call an alias given its name and the rest of the line.
1456 1456
1457 1457 This function MUST be given a proper alias, because it doesn't make
1458 1458 any checks when looking up into the alias table. The caller is
1459 1459 responsible for invoking it only with a valid alias."""
1460 1460
1461 1461 #print 'ALIAS: <%s>+<%s>' % (alias,rest) # dbg
1462 1462 nargs,cmd = self.alias_table[alias]
1463 1463 # Expand the %l special to be the user's input line
1464 1464 if cmd.find('%l') >= 0:
1465 1465 cmd = cmd.replace('%l',rest)
1466 1466 rest = ''
1467 1467 if nargs==0:
1468 1468 # Simple, argument-less aliases
1469 1469 cmd = '%s %s' % (cmd,rest)
1470 1470 else:
1471 1471 # Handle aliases with positional arguments
1472 1472 args = rest.split(None,nargs)
1473 1473 if len(args)< nargs:
1474 1474 error('Alias <%s> requires %s arguments, %s given.' %
1475 1475 (alias,nargs,len(args)))
1476 1476 return
1477 1477 cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
1478 1478 # Now call the macro, evaluating in the user's namespace
1479 1479 try:
1480 1480 self.system(cmd)
1481 1481 except:
1482 1482 self.showtraceback()
1483 1483
1484 1484 def autoindent_update(self,line):
1485 1485 """Keep track of the indent level."""
1486 1486 if self.autoindent:
1487 1487 if line:
1488 1488 ini_spaces = ini_spaces_re.match(line)
1489 1489 if ini_spaces:
1490 1490 nspaces = ini_spaces.end()
1491 1491 else:
1492 1492 nspaces = 0
1493 1493 self.indent_current_nsp = nspaces
1494 1494
1495 1495 if line[-1] == ':':
1496 1496 self.indent_current_nsp += 4
1497 1497 elif dedent_re.match(line):
1498 1498 self.indent_current_nsp -= 4
1499 1499 else:
1500 1500 self.indent_current_nsp = 0
1501 1501
1502 1502 # indent_current is the actual string to be inserted
1503 1503 # by the readline hooks for indentation
1504 1504 self.indent_current = ' '* self.indent_current_nsp
1505 1505
1506 1506 def runlines(self,lines):
1507 1507 """Run a string of one or more lines of source.
1508 1508
1509 1509 This method is capable of running a string containing multiple source
1510 1510 lines, as if they had been entered at the IPython prompt. Since it
1511 1511 exposes IPython's processing machinery, the given strings can contain
1512 1512 magic calls (%magic), special shell access (!cmd), etc."""
1513 1513
1514 1514 # We must start with a clean buffer, in case this is run from an
1515 1515 # interactive IPython session (via a magic, for example).
1516 1516 self.resetbuffer()
1517 1517 lines = lines.split('\n')
1518 1518 more = 0
1519 1519 for line in lines:
1520 1520 # skip blank lines so we don't mess up the prompt counter, but do
1521 1521 # NOT skip even a blank line if we are in a code block (more is
1522 1522 # true)
1523 1523 if line or more:
1524 1524 more = self.push(self.prefilter(line,more))
1525 1525 # IPython's runsource returns None if there was an error
1526 1526 # compiling the code. This allows us to stop processing right
1527 1527 # away, so the user gets the error message at the right place.
1528 1528 if more is None:
1529 1529 break
1530 1530 # final newline in case the input didn't have it, so that the code
1531 1531 # actually does get executed
1532 1532 if more:
1533 1533 self.push('\n')
1534 1534
1535 1535 def runsource(self, source, filename='<input>', symbol='single'):
1536 1536 """Compile and run some source in the interpreter.
1537 1537
1538 1538 Arguments are as for compile_command().
1539 1539
1540 1540 One several things can happen:
1541 1541
1542 1542 1) The input is incorrect; compile_command() raised an
1543 1543 exception (SyntaxError or OverflowError). A syntax traceback
1544 1544 will be printed by calling the showsyntaxerror() method.
1545 1545
1546 1546 2) The input is incomplete, and more input is required;
1547 1547 compile_command() returned None. Nothing happens.
1548 1548
1549 1549 3) The input is complete; compile_command() returned a code
1550 1550 object. The code is executed by calling self.runcode() (which
1551 1551 also handles run-time exceptions, except for SystemExit).
1552 1552
1553 1553 The return value is:
1554 1554
1555 1555 - True in case 2
1556 1556
1557 1557 - False in the other cases, unless an exception is raised, where
1558 1558 None is returned instead. This can be used by external callers to
1559 1559 know whether to continue feeding input or not.
1560 1560
1561 1561 The return value can be used to decide whether to use sys.ps1 or
1562 1562 sys.ps2 to prompt the next line."""
1563 1563
1564 1564 try:
1565 1565 code = self.compile(source,filename,symbol)
1566 1566 except (OverflowError, SyntaxError, ValueError):
1567 1567 # Case 1
1568 1568 self.showsyntaxerror(filename)
1569 1569 return None
1570 1570
1571 1571 if code is None:
1572 1572 # Case 2
1573 1573 return True
1574 1574
1575 1575 # Case 3
1576 1576 # We store the code object so that threaded shells and
1577 1577 # custom exception handlers can access all this info if needed.
1578 1578 # The source corresponding to this can be obtained from the
1579 1579 # buffer attribute as '\n'.join(self.buffer).
1580 1580 self.code_to_run = code
1581 1581 # now actually execute the code object
1582 1582 if self.runcode(code) == 0:
1583 1583 return False
1584 1584 else:
1585 1585 return None
1586 1586
1587 1587 def runcode(self,code_obj):
1588 1588 """Execute a code object.
1589 1589
1590 1590 When an exception occurs, self.showtraceback() is called to display a
1591 1591 traceback.
1592 1592
1593 1593 Return value: a flag indicating whether the code to be run completed
1594 1594 successfully:
1595 1595
1596 1596 - 0: successful execution.
1597 1597 - 1: an error occurred.
1598 1598 """
1599 1599
1600 1600 # Set our own excepthook in case the user code tries to call it
1601 1601 # directly, so that the IPython crash handler doesn't get triggered
1602 1602 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
1603 1603
1604 1604 # we save the original sys.excepthook in the instance, in case config
1605 1605 # code (such as magics) needs access to it.
1606 1606 self.sys_excepthook = old_excepthook
1607 1607 outflag = 1 # happens in more places, so it's easier as default
1608 1608 try:
1609 1609 try:
1610 1610 # Embedded instances require separate global/local namespaces
1611 1611 # so they can see both the surrounding (local) namespace and
1612 1612 # the module-level globals when called inside another function.
1613 1613 if self.embedded:
1614 1614 exec code_obj in self.user_global_ns, self.user_ns
1615 1615 # Normal (non-embedded) instances should only have a single
1616 1616 # namespace for user code execution, otherwise functions won't
1617 1617 # see interactive top-level globals.
1618 1618 else:
1619 1619 exec code_obj in self.user_ns
1620 1620 finally:
1621 1621 # Reset our crash handler in place
1622 1622 sys.excepthook = old_excepthook
1623 1623 except SystemExit:
1624 1624 self.resetbuffer()
1625 1625 self.showtraceback()
1626 1626 warn("Type exit or quit to exit IPython "
1627 1627 "(%Exit or %Quit do so unconditionally).",level=1)
1628 1628 except self.custom_exceptions:
1629 1629 etype,value,tb = sys.exc_info()
1630 1630 self.CustomTB(etype,value,tb)
1631 1631 except:
1632 1632 self.showtraceback()
1633 1633 else:
1634 1634 outflag = 0
1635 1635 if softspace(sys.stdout, 0):
1636 1636 print
1637 1637 # Flush out code object which has been run (and source)
1638 1638 self.code_to_run = None
1639 1639 return outflag
1640 1640
1641 1641 def push(self, line):
1642 1642 """Push a line to the interpreter.
1643 1643
1644 1644 The line should not have a trailing newline; it may have
1645 1645 internal newlines. The line is appended to a buffer and the
1646 1646 interpreter's runsource() method is called with the
1647 1647 concatenated contents of the buffer as source. If this
1648 1648 indicates that the command was executed or invalid, the buffer
1649 1649 is reset; otherwise, the command is incomplete, and the buffer
1650 1650 is left as it was after the line was appended. The return
1651 1651 value is 1 if more input is required, 0 if the line was dealt
1652 1652 with in some way (this is the same as runsource()).
1653 1653 """
1654 1654
1655 1655 # autoindent management should be done here, and not in the
1656 1656 # interactive loop, since that one is only seen by keyboard input. We
1657 1657 # need this done correctly even for code run via runlines (which uses
1658 1658 # push).
1659 1659
1660 1660 #print 'push line: <%s>' % line # dbg
1661 1661 self.autoindent_update(line)
1662 1662
1663 1663 self.buffer.append(line)
1664 1664 more = self.runsource('\n'.join(self.buffer), self.filename)
1665 1665 if not more:
1666 1666 self.resetbuffer()
1667 1667 return more
1668 1668
1669 1669 def resetbuffer(self):
1670 1670 """Reset the input buffer."""
1671 1671 self.buffer[:] = []
1672 1672
1673 1673 def raw_input(self,prompt='',continue_prompt=False):
1674 1674 """Write a prompt and read a line.
1675 1675
1676 1676 The returned line does not include the trailing newline.
1677 1677 When the user enters the EOF key sequence, EOFError is raised.
1678 1678
1679 1679 Optional inputs:
1680 1680
1681 1681 - prompt(''): a string to be printed to prompt the user.
1682 1682
1683 1683 - continue_prompt(False): whether this line is the first one or a
1684 1684 continuation in a sequence of inputs.
1685 1685 """
1686 1686
1687 1687 line = raw_input_original(prompt)
1688 1688 # Try to be reasonably smart about not re-indenting pasted input more
1689 1689 # than necessary. We do this by trimming out the auto-indent initial
1690 1690 # spaces, if the user's actual input started itself with whitespace.
1691 1691 if self.autoindent:
1692 1692 line2 = line[self.indent_current_nsp:]
1693 1693 if line2[0:1] in (' ','\t'):
1694 1694 line = line2
1695 1695 return self.prefilter(line,continue_prompt)
1696 1696
1697 1697 def split_user_input(self,line):
1698 1698 """Split user input into pre-char, function part and rest."""
1699 1699
1700 1700 lsplit = self.line_split.match(line)
1701 1701 if lsplit is None: # no regexp match returns None
1702 1702 try:
1703 1703 iFun,theRest = line.split(None,1)
1704 1704 except ValueError:
1705 1705 iFun,theRest = line,''
1706 1706 pre = re.match('^(\s*)(.*)',line).groups()[0]
1707 1707 else:
1708 1708 pre,iFun,theRest = lsplit.groups()
1709 1709
1710 1710 #print 'line:<%s>' % line # dbg
1711 1711 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun.strip(),theRest) # dbg
1712 1712 return pre,iFun.strip(),theRest
1713 1713
1714 1714 def _prefilter(self, line, continue_prompt):
1715 1715 """Calls different preprocessors, depending on the form of line."""
1716 1716
1717 1717 # All handlers *must* return a value, even if it's blank ('').
1718 1718
1719 1719 # Lines are NOT logged here. Handlers should process the line as
1720 1720 # needed, update the cache AND log it (so that the input cache array
1721 1721 # stays synced).
1722 1722
1723 1723 # This function is _very_ delicate, and since it's also the one which
1724 1724 # determines IPython's response to user input, it must be as efficient
1725 1725 # as possible. For this reason it has _many_ returns in it, trying
1726 1726 # always to exit as quickly as it can figure out what it needs to do.
1727 1727
1728 1728 # This function is the main responsible for maintaining IPython's
1729 1729 # behavior respectful of Python's semantics. So be _very_ careful if
1730 1730 # making changes to anything here.
1731 1731
1732 1732 #.....................................................................
1733 1733 # Code begins
1734 1734
1735 1735 #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg
1736 1736
1737 1737 # save the line away in case we crash, so the post-mortem handler can
1738 1738 # record it
1739 1739 self._last_input_line = line
1740 1740
1741 1741 #print '***line: <%s>' % line # dbg
1742 1742
1743 1743 # the input history needs to track even empty lines
1744 1744 if not line.strip():
1745 1745 if not continue_prompt:
1746 1746 self.outputcache.prompt_count -= 1
1747 1747 return self.handle_normal(line,continue_prompt)
1748 1748 #return self.handle_normal('',continue_prompt)
1749 1749
1750 1750 # print '***cont',continue_prompt # dbg
1751 1751 # special handlers are only allowed for single line statements
1752 1752 if continue_prompt and not self.rc.multi_line_specials:
1753 1753 return self.handle_normal(line,continue_prompt)
1754 1754
1755 1755 # For the rest, we need the structure of the input
1756 1756 pre,iFun,theRest = self.split_user_input(line)
1757 1757 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
1758 1758
1759 1759 # First check for explicit escapes in the last/first character
1760 1760 handler = None
1761 1761 if line[-1] == self.ESC_HELP:
1762 1762 handler = self.esc_handlers.get(line[-1]) # the ? can be at the end
1763 1763 if handler is None:
1764 1764 # look at the first character of iFun, NOT of line, so we skip
1765 1765 # leading whitespace in multiline input
1766 1766 handler = self.esc_handlers.get(iFun[0:1])
1767 1767 if handler is not None:
1768 1768 return handler(line,continue_prompt,pre,iFun,theRest)
1769 1769 # Emacs ipython-mode tags certain input lines
1770 1770 if line.endswith('# PYTHON-MODE'):
1771 1771 return self.handle_emacs(line,continue_prompt)
1772 1772
1773 1773 # Next, check if we can automatically execute this thing
1774 1774
1775 1775 # Allow ! in multi-line statements if multi_line_specials is on:
1776 1776 if continue_prompt and self.rc.multi_line_specials and \
1777 1777 iFun.startswith(self.ESC_SHELL):
1778 1778 return self.handle_shell_escape(line,continue_prompt,
1779 1779 pre=pre,iFun=iFun,
1780 1780 theRest=theRest)
1781 1781
1782 1782 # Let's try to find if the input line is a magic fn
1783 1783 oinfo = None
1784 1784 if hasattr(self,'magic_'+iFun):
1785 1785 # WARNING: _ofind uses getattr(), so it can consume generators and
1786 1786 # cause other side effects.
1787 1787 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
1788 1788 if oinfo['ismagic']:
1789 1789 # Be careful not to call magics when a variable assignment is
1790 1790 # being made (ls='hi', for example)
1791 1791 if self.rc.automagic and \
1792 1792 (len(theRest)==0 or theRest[0] not in '!=()<>,') and \
1793 1793 (self.rc.multi_line_specials or not continue_prompt):
1794 1794 return self.handle_magic(line,continue_prompt,
1795 1795 pre,iFun,theRest)
1796 1796 else:
1797 1797 return self.handle_normal(line,continue_prompt)
1798 1798
1799 1799 # If the rest of the line begins with an (in)equality, assginment or
1800 1800 # function call, we should not call _ofind but simply execute it.
1801 1801 # This avoids spurious geattr() accesses on objects upon assignment.
1802 1802 #
1803 1803 # It also allows users to assign to either alias or magic names true
1804 1804 # python variables (the magic/alias systems always take second seat to
1805 1805 # true python code).
1806 1806 if theRest and theRest[0] in '!=()':
1807 1807 return self.handle_normal(line,continue_prompt)
1808 1808
1809 1809 if oinfo is None:
1810 1810 # let's try to ensure that _oinfo is ONLY called when autocall is
1811 1811 # on. Since it has inevitable potential side effects, at least
1812 1812 # having autocall off should be a guarantee to the user that no
1813 1813 # weird things will happen.
1814 1814
1815 1815 if self.rc.autocall:
1816 1816 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
1817 1817 else:
1818 1818 # in this case, all that's left is either an alias or
1819 1819 # processing the line normally.
1820 1820 if iFun in self.alias_table:
1821 1821 return self.handle_alias(line,continue_prompt,
1822 1822 pre,iFun,theRest)
1823 1823 else:
1824 1824 return self.handle_normal(line,continue_prompt)
1825 1825
1826 1826 if not oinfo['found']:
1827 1827 return self.handle_normal(line,continue_prompt)
1828 1828 else:
1829 1829 #print 'iFun <%s> rest <%s>' % (iFun,theRest) # dbg
1830 1830 if oinfo['isalias']:
1831 1831 return self.handle_alias(line,continue_prompt,
1832 1832 pre,iFun,theRest)
1833 1833
1834 1834 if self.rc.autocall and \
1835 1835 not self.re_exclude_auto.match(theRest) and \
1836 1836 self.re_fun_name.match(iFun) and \
1837 1837 callable(oinfo['obj']) :
1838 1838 #print 'going auto' # dbg
1839 return self.handle_auto(line,continue_prompt,pre,iFun,theRest)
1839 return self.handle_auto(line,continue_prompt,
1840 pre,iFun,theRest,oinfo['obj'])
1840 1841 else:
1841 1842 #print 'was callable?', callable(oinfo['obj']) # dbg
1842 1843 return self.handle_normal(line,continue_prompt)
1843 1844
1844 1845 # If we get here, we have a normal Python line. Log and return.
1845 1846 return self.handle_normal(line,continue_prompt)
1846 1847
1847 1848 def _prefilter_dumb(self, line, continue_prompt):
1848 1849 """simple prefilter function, for debugging"""
1849 1850 return self.handle_normal(line,continue_prompt)
1850 1851
1851 1852 # Set the default prefilter() function (this can be user-overridden)
1852 1853 prefilter = _prefilter
1853 1854
1854 1855 def handle_normal(self,line,continue_prompt=None,
1855 1856 pre=None,iFun=None,theRest=None):
1856 1857 """Handle normal input lines. Use as a template for handlers."""
1857 1858
1858 1859 # With autoindent on, we need some way to exit the input loop, and I
1859 1860 # don't want to force the user to have to backspace all the way to
1860 1861 # clear the line. The rule will be in this case, that either two
1861 1862 # lines of pure whitespace in a row, or a line of pure whitespace but
1862 1863 # of a size different to the indent level, will exit the input loop.
1863 1864
1864 1865 if (continue_prompt and self.autoindent and isspace(line) and
1865 1866 (line != self.indent_current or isspace(self.buffer[-1]))):
1866 1867 line = ''
1867 1868
1868 1869 self.log(line,continue_prompt)
1869 1870 return line
1870 1871
1871 1872 def handle_alias(self,line,continue_prompt=None,
1872 1873 pre=None,iFun=None,theRest=None):
1873 1874 """Handle alias input lines. """
1874 1875
1875 1876 # pre is needed, because it carries the leading whitespace. Otherwise
1876 1877 # aliases won't work in indented sections.
1877 1878 line_out = '%sipalias("%s %s")' % (pre,iFun,esc_quotes(theRest))
1878 1879 self.log(line_out,continue_prompt)
1879 1880 return line_out
1880 1881
1881 1882 def handle_shell_escape(self, line, continue_prompt=None,
1882 1883 pre=None,iFun=None,theRest=None):
1883 1884 """Execute the line in a shell, empty return value"""
1884 1885
1885 1886 #print 'line in :', `line` # dbg
1886 1887 # Example of a special handler. Others follow a similar pattern.
1887 1888 if continue_prompt: # multi-line statements
1888 1889 if iFun.startswith('!!'):
1889 1890 print 'SyntaxError: !! is not allowed in multiline statements'
1890 1891 return pre
1891 1892 else:
1892 1893 cmd = ("%s %s" % (iFun[1:],theRest))
1893 1894 line_out = '%sipsystem(r"""%s"""[:-1])' % (pre,cmd + "_")
1894 1895 else: # single-line input
1895 1896 if line.startswith('!!'):
1896 1897 # rewrite iFun/theRest to properly hold the call to %sx and
1897 1898 # the actual command to be executed, so handle_magic can work
1898 1899 # correctly
1899 1900 theRest = '%s %s' % (iFun[2:],theRest)
1900 1901 iFun = 'sx'
1901 1902 return self.handle_magic('%ssx %s' % (self.ESC_MAGIC,line[2:]),
1902 1903 continue_prompt,pre,iFun,theRest)
1903 1904 else:
1904 1905 cmd=line[1:]
1905 1906 line_out = '%sipsystem(r"""%s"""[:-1])' % (pre,cmd +"_")
1906 1907 # update cache/log and return
1907 1908 self.log(line_out,continue_prompt)
1908 1909 return line_out
1909 1910
1910 1911 def handle_magic(self, line, continue_prompt=None,
1911 1912 pre=None,iFun=None,theRest=None):
1912 1913 """Execute magic functions.
1913 1914
1914 1915 Also log them with a prepended # so the log is clean Python."""
1915 1916
1916 1917 cmd = '%sipmagic("%s")' % (pre,esc_quotes('%s %s' % (iFun,theRest)))
1917 1918 self.log(cmd,continue_prompt)
1918 1919 #print 'in handle_magic, cmd=<%s>' % cmd # dbg
1919 1920 return cmd
1920 1921
1921 1922 def handle_auto(self, line, continue_prompt=None,
1922 pre=None,iFun=None,theRest=None):
1923 pre=None,iFun=None,theRest=None,obj=None):
1923 1924 """Hande lines which can be auto-executed, quoting if requested."""
1924 1925
1925 1926 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
1926 1927
1927 1928 # This should only be active for single-line input!
1928 1929 if continue_prompt:
1930 self.log(line,continue_prompt)
1929 1931 return line
1930 1932
1933 auto_rewrite = True
1931 1934 if pre == self.ESC_QUOTE:
1932 1935 # Auto-quote splitting on whitespace
1933 1936 newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) )
1934 1937 elif pre == self.ESC_QUOTE2:
1935 1938 # Auto-quote whole string
1936 1939 newcmd = '%s("%s")' % (iFun,theRest)
1937 1940 else:
1938 # Auto-paren
1939 if theRest[0:1] in ('=','['):
1940 # Don't autocall in these cases. They can be either
1941 # rebindings of an existing callable's name, or item access
1942 # for an object which is BOTH callable and implements
1943 # __getitem__.
1944 return '%s %s' % (iFun,theRest)
1945 if theRest.endswith(';'):
1946 newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1])
1941 # Auto-paren.
1942 # We only apply it to argument-less calls if the autocall
1943 # parameter is set to 2. We only need to check that autocall is <
1944 # 2, since this function isn't called unless it's at least 1.
1945 if not theRest and self.rc.autocall < 2:
1946 newcmd = '%s %s' % (iFun,theRest)
1947 auto_rewrite = False
1947 1948 else:
1948 newcmd = '%s(%s)' % (iFun.rstrip(),theRest)
1949 if theRest.startswith('['):
1950 if hasattr(obj,'__getitem__'):
1951 # Don't autocall in this case: item access for an object
1952 # which is BOTH callable and implements __getitem__.
1953 newcmd = '%s %s' % (iFun,theRest)
1954 auto_rewrite = False
1955 else:
1956 # if the object doesn't support [] access, go ahead and
1957 # autocall
1958 newcmd = '%s(%s)' % (iFun.rstrip(),theRest)
1959 elif theRest.endswith(';'):
1960 newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1])
1961 else:
1962 newcmd = '%s(%s)' % (iFun.rstrip(),theRest)
1949 1963
1950 print >>Term.cout, self.outputcache.prompt1.auto_rewrite() + newcmd
1964 if auto_rewrite:
1965 print >>Term.cout, self.outputcache.prompt1.auto_rewrite() + newcmd
1951 1966 # log what is now valid Python, not the actual user input (without the
1952 1967 # final newline)
1953 1968 self.log(newcmd,continue_prompt)
1954 1969 return newcmd
1955 1970
1956 1971 def handle_help(self, line, continue_prompt=None,
1957 1972 pre=None,iFun=None,theRest=None):
1958 1973 """Try to get some help for the object.
1959 1974
1960 1975 obj? or ?obj -> basic information.
1961 1976 obj?? or ??obj -> more details.
1962 1977 """
1963 1978
1964 1979 # We need to make sure that we don't process lines which would be
1965 1980 # otherwise valid python, such as "x=1 # what?"
1966 1981 try:
1967 1982 codeop.compile_command(line)
1968 1983 except SyntaxError:
1969 1984 # We should only handle as help stuff which is NOT valid syntax
1970 1985 if line[0]==self.ESC_HELP:
1971 1986 line = line[1:]
1972 1987 elif line[-1]==self.ESC_HELP:
1973 1988 line = line[:-1]
1974 1989 self.log('#?'+line)
1975 1990 if line:
1976 1991 self.magic_pinfo(line)
1977 1992 else:
1978 1993 page(self.usage,screen_lines=self.rc.screen_length)
1979 1994 return '' # Empty string is needed here!
1980 1995 except:
1981 1996 # Pass any other exceptions through to the normal handler
1982 1997 return self.handle_normal(line,continue_prompt)
1983 1998 else:
1984 1999 # If the code compiles ok, we should handle it normally
1985 2000 return self.handle_normal(line,continue_prompt)
1986 2001
1987 2002 def handle_emacs(self,line,continue_prompt=None,
1988 2003 pre=None,iFun=None,theRest=None):
1989 2004 """Handle input lines marked by python-mode."""
1990 2005
1991 2006 # Currently, nothing is done. Later more functionality can be added
1992 2007 # here if needed.
1993 2008
1994 2009 # The input cache shouldn't be updated
1995 2010
1996 2011 return line
1997 2012
1998 2013 def mktempfile(self,data=None):
1999 2014 """Make a new tempfile and return its filename.
2000 2015
2001 2016 This makes a call to tempfile.mktemp, but it registers the created
2002 2017 filename internally so ipython cleans it up at exit time.
2003 2018
2004 2019 Optional inputs:
2005 2020
2006 2021 - data(None): if data is given, it gets written out to the temp file
2007 2022 immediately, and the file is closed again."""
2008 2023
2009 2024 filename = tempfile.mktemp('.py')
2010 2025 self.tempfiles.append(filename)
2011 2026
2012 2027 if data:
2013 2028 tmp_file = open(filename,'w')
2014 2029 tmp_file.write(data)
2015 2030 tmp_file.close()
2016 2031 return filename
2017 2032
2018 2033 def write(self,data):
2019 2034 """Write a string to the default output"""
2020 2035 Term.cout.write(data)
2021 2036
2022 2037 def write_err(self,data):
2023 2038 """Write a string to the default error output"""
2024 2039 Term.cerr.write(data)
2025 2040
2026 2041 def exit(self):
2027 2042 """Handle interactive exit.
2028 2043
2029 2044 This method sets the exit_now attribute."""
2030 2045
2031 2046 if self.rc.confirm_exit:
2032 2047 if ask_yes_no('Do you really want to exit ([y]/n)?','y'):
2033 2048 self.exit_now = True
2034 2049 else:
2035 2050 self.exit_now = True
2036 2051 return self.exit_now
2037 2052
2038 2053 def safe_execfile(self,fname,*where,**kw):
2039 2054 fname = os.path.expanduser(fname)
2040 2055
2041 2056 # find things also in current directory
2042 2057 dname = os.path.dirname(fname)
2043 2058 if not sys.path.count(dname):
2044 2059 sys.path.append(dname)
2045 2060
2046 2061 try:
2047 2062 xfile = open(fname)
2048 2063 except:
2049 2064 print >> Term.cerr, \
2050 2065 'Could not open file <%s> for safe execution.' % fname
2051 2066 return None
2052 2067
2053 2068 kw.setdefault('islog',0)
2054 2069 kw.setdefault('quiet',1)
2055 2070 kw.setdefault('exit_ignore',0)
2056 2071 first = xfile.readline()
2057 2072 loghead = str(self.loghead_tpl).split('\n',1)[0].strip()
2058 2073 xfile.close()
2059 2074 # line by line execution
2060 2075 if first.startswith(loghead) or kw['islog']:
2061 2076 print 'Loading log file <%s> one line at a time...' % fname
2062 2077 if kw['quiet']:
2063 2078 stdout_save = sys.stdout
2064 2079 sys.stdout = StringIO.StringIO()
2065 2080 try:
2066 2081 globs,locs = where[0:2]
2067 2082 except:
2068 2083 try:
2069 2084 globs = locs = where[0]
2070 2085 except:
2071 2086 globs = locs = globals()
2072 2087 badblocks = []
2073 2088
2074 2089 # we also need to identify indented blocks of code when replaying
2075 2090 # logs and put them together before passing them to an exec
2076 2091 # statement. This takes a bit of regexp and look-ahead work in the
2077 2092 # file. It's easiest if we swallow the whole thing in memory
2078 2093 # first, and manually walk through the lines list moving the
2079 2094 # counter ourselves.
2080 2095 indent_re = re.compile('\s+\S')
2081 2096 xfile = open(fname)
2082 2097 filelines = xfile.readlines()
2083 2098 xfile.close()
2084 2099 nlines = len(filelines)
2085 2100 lnum = 0
2086 2101 while lnum < nlines:
2087 2102 line = filelines[lnum]
2088 2103 lnum += 1
2089 2104 # don't re-insert logger status info into cache
2090 2105 if line.startswith('#log#'):
2091 2106 continue
2092 2107 else:
2093 2108 # build a block of code (maybe a single line) for execution
2094 2109 block = line
2095 2110 try:
2096 2111 next = filelines[lnum] # lnum has already incremented
2097 2112 except:
2098 2113 next = None
2099 2114 while next and indent_re.match(next):
2100 2115 block += next
2101 2116 lnum += 1
2102 2117 try:
2103 2118 next = filelines[lnum]
2104 2119 except:
2105 2120 next = None
2106 2121 # now execute the block of one or more lines
2107 2122 try:
2108 2123 exec block in globs,locs
2109 2124 except SystemExit:
2110 2125 pass
2111 2126 except:
2112 2127 badblocks.append(block.rstrip())
2113 2128 if kw['quiet']: # restore stdout
2114 2129 sys.stdout.close()
2115 2130 sys.stdout = stdout_save
2116 2131 print 'Finished replaying log file <%s>' % fname
2117 2132 if badblocks:
2118 2133 print >> sys.stderr, ('\nThe following lines/blocks in file '
2119 2134 '<%s> reported errors:' % fname)
2120 2135
2121 2136 for badline in badblocks:
2122 2137 print >> sys.stderr, badline
2123 2138 else: # regular file execution
2124 2139 try:
2125 2140 execfile(fname,*where)
2126 2141 except SyntaxError:
2127 2142 etype,evalue = sys.exc_info()[:2]
2128 2143 self.SyntaxTB(etype,evalue,[])
2129 2144 warn('Failure executing file: <%s>' % fname)
2130 2145 except SystemExit,status:
2131 2146 if not kw['exit_ignore']:
2132 2147 self.InteractiveTB()
2133 2148 warn('Failure executing file: <%s>' % fname)
2134 2149 except:
2135 2150 self.InteractiveTB()
2136 2151 warn('Failure executing file: <%s>' % fname)
2137 2152
2138 2153 #************************* end of file <iplib.py> *****************************
@@ -1,701 +1,701 b''
1 1 # -*- coding: utf-8 -*-
2 2 """
3 3 IPython -- An enhanced Interactive Python
4 4
5 5 Requires Python 2.1 or better.
6 6
7 7 This file contains the main make_IPython() starter function.
8 8
9 $Id: ipmaker.py 967 2005-12-29 09:02:13Z fperez $"""
9 $Id: ipmaker.py 990 2006-01-04 06:59:02Z fperez $"""
10 10
11 11 #*****************************************************************************
12 12 # Copyright (C) 2001-2004 Fernando Perez. <fperez@colorado.edu>
13 13 #
14 14 # Distributed under the terms of the BSD License. The full license is in
15 15 # the file COPYING, distributed as part of this software.
16 16 #*****************************************************************************
17 17
18 18 from IPython import Release
19 19 __author__ = '%s <%s>' % Release.authors['Fernando']
20 20 __license__ = Release.license
21 21 __version__ = Release.version
22 22
23 23 credits._Printer__data = """
24 24 Python: %s
25 25
26 26 IPython: Fernando Perez, Janko Hauser, Nathan Gray, and many users.
27 27 See http://ipython.scipy.org for more information.""" \
28 28 % credits._Printer__data
29 29
30 30 copyright._Printer__data += """
31 31
32 32 Copyright (c) 2001-2004 Fernando Perez, Janko Hauser, Nathan Gray.
33 33 All Rights Reserved."""
34 34
35 35 #****************************************************************************
36 36 # Required modules
37 37
38 38 # From the standard library
39 39 import __main__
40 40 import __builtin__
41 41 import os
42 42 import re
43 43 import sys
44 44 import types
45 45 from pprint import pprint,pformat
46 46
47 47 # Our own
48 48 from IPython import DPyGetOpt
49 49 from IPython.Struct import Struct
50 50 from IPython.OutputTrap import OutputTrap
51 51 from IPython.ConfigLoader import ConfigLoader
52 52 from IPython.iplib import InteractiveShell
53 53 from IPython.usage import cmd_line_usage,interactive_usage
54 54 from IPython.genutils import *
55 55
56 56 #-----------------------------------------------------------------------------
57 57 def make_IPython(argv=None,user_ns=None,user_global_ns=None,debug=1,
58 58 rc_override=None,shell_class=InteractiveShell,
59 59 embedded=False,**kw):
60 60 """This is a dump of IPython into a single function.
61 61
62 62 Later it will have to be broken up in a sensible manner.
63 63
64 64 Arguments:
65 65
66 66 - argv: a list similar to sys.argv[1:]. It should NOT contain the desired
67 67 script name, b/c DPyGetOpt strips the first argument only for the real
68 68 sys.argv.
69 69
70 70 - user_ns: a dict to be used as the user's namespace."""
71 71
72 72 #----------------------------------------------------------------------
73 73 # Defaults and initialization
74 74
75 75 # For developer debugging, deactivates crash handler and uses pdb.
76 76 DEVDEBUG = False
77 77
78 78 if argv is None:
79 79 argv = sys.argv
80 80
81 81 # __IP is the main global that lives throughout and represents the whole
82 82 # application. If the user redefines it, all bets are off as to what
83 83 # happens.
84 84
85 85 # __IP is the name of he global which the caller will have accessible as
86 86 # __IP.name. We set its name via the first parameter passed to
87 87 # InteractiveShell:
88 88
89 89 IP = shell_class('__IP',user_ns=user_ns,user_global_ns=user_global_ns,
90 90 embedded=embedded,**kw)
91 91
92 92 # Put 'help' in the user namespace
93 93 from site import _Helper
94 94 IP.user_ns['help'] = _Helper()
95 95
96 96
97 97 if DEVDEBUG:
98 98 # For developer debugging only (global flag)
99 99 from IPython import ultraTB
100 100 sys.excepthook = ultraTB.VerboseTB(call_pdb=1)
101 101
102 102 IP.BANNER_PARTS = ['Python %s\n'
103 103 'Type "copyright", "credits" or "license" '
104 104 'for more information.\n'
105 105 % (sys.version.split('\n')[0],),
106 106 "IPython %s -- An enhanced Interactive Python."
107 107 % (__version__,),
108 108 """? -> Introduction to IPython's features.
109 109 %magic -> Information about IPython's 'magic' % functions.
110 110 help -> Python's own help system.
111 111 object? -> Details about 'object'. ?object also works, ?? prints more.
112 112 """ ]
113 113
114 114 IP.usage = interactive_usage
115 115
116 116 # Platform-dependent suffix and directory names. We use _ipython instead
117 117 # of .ipython under win32 b/c there's software that breaks with .named
118 118 # directories on that platform.
119 119 if os.name == 'posix':
120 120 rc_suffix = ''
121 121 ipdir_def = '.ipython'
122 122 else:
123 123 rc_suffix = '.ini'
124 124 ipdir_def = '_ipython'
125 125
126 126 # default directory for configuration
127 127 ipythondir = os.path.abspath(os.environ.get('IPYTHONDIR',
128 128 os.path.join(IP.home_dir,ipdir_def)))
129 129
130 130 # we need the directory where IPython itself is installed
131 131 import IPython
132 132 IPython_dir = os.path.dirname(IPython.__file__)
133 133 del IPython
134 134
135 135 #-------------------------------------------------------------------------
136 136 # Command line handling
137 137
138 138 # Valid command line options (uses DPyGetOpt syntax, like Perl's
139 139 # GetOpt::Long)
140 140
141 141 # Any key not listed here gets deleted even if in the file (like session
142 142 # or profile). That's deliberate, to maintain the rc namespace clean.
143 143
144 144 # Each set of options appears twice: under _conv only the names are
145 145 # listed, indicating which type they must be converted to when reading the
146 146 # ipythonrc file. And under DPyGetOpt they are listed with the regular
147 147 # DPyGetOpt syntax (=s,=i,:f,etc).
148 148
149 149 # Make sure there's a space before each end of line (they get auto-joined!)
150 cmdline_opts = ('autocall! autoindent! automagic! banner! cache_size|cs=i '
150 cmdline_opts = ('autocall=i autoindent! automagic! banner! cache_size|cs=i '
151 151 'c=s classic|cl color_info! colors=s confirm_exit! '
152 152 'debug! deep_reload! editor=s log|l messages! nosep pdb! '
153 153 'pprint! prompt_in1|pi1=s prompt_in2|pi2=s prompt_out|po=s '
154 154 'quick screen_length|sl=i prompts_pad_left=i '
155 155 'logfile|lf=s logplay|lp=s profile|p=s '
156 156 'readline! readline_merge_completions! '
157 157 'readline_omit__names! '
158 158 'rcfile=s separate_in|si=s separate_out|so=s '
159 159 'separate_out2|so2=s xmode=s wildcards_case_sensitive! '
160 160 'magic_docstrings system_verbose! '
161 161 'multi_line_specials! '
162 162 'autoedit_syntax!')
163 163
164 164 # Options that can *only* appear at the cmd line (not in rcfiles).
165 165
166 166 # The "ignore" option is a kludge so that Emacs buffers don't crash, since
167 167 # the 'C-c !' command in emacs automatically appends a -i option at the end.
168 168 cmdline_only = ('help ignore|i ipythondir=s Version upgrade '
169 169 'gthread! qthread! wthread! pylab! tk!')
170 170
171 171 # Build the actual name list to be used by DPyGetOpt
172 172 opts_names = qw(cmdline_opts) + qw(cmdline_only)
173 173
174 174 # Set sensible command line defaults.
175 175 # This should have everything from cmdline_opts and cmdline_only
176 176 opts_def = Struct(autocall = 1,
177 177 autoedit_syntax = 1,
178 178 autoindent=0,
179 179 automagic = 1,
180 180 banner = 1,
181 181 cache_size = 1000,
182 182 c = '',
183 183 classic = 0,
184 184 colors = 'NoColor',
185 185 color_info = 0,
186 186 confirm_exit = 1,
187 187 debug = 0,
188 188 deep_reload = 0,
189 189 editor = '0',
190 190 help = 0,
191 191 ignore = 0,
192 192 ipythondir = ipythondir,
193 193 log = 0,
194 194 logfile = '',
195 195 logplay = '',
196 196 multi_line_specials = 1,
197 197 messages = 1,
198 198 nosep = 0,
199 199 pdb = 0,
200 200 pprint = 0,
201 201 profile = '',
202 202 prompt_in1 = 'In [\\#]: ',
203 203 prompt_in2 = ' .\\D.: ',
204 204 prompt_out = 'Out[\\#]: ',
205 205 prompts_pad_left = 1,
206 206 quick = 0,
207 207 readline = 1,
208 208 readline_merge_completions = 1,
209 209 readline_omit__names = 0,
210 210 rcfile = 'ipythonrc' + rc_suffix,
211 211 screen_length = 0,
212 212 separate_in = '\n',
213 213 separate_out = '\n',
214 214 separate_out2 = '',
215 215 system_verbose = 0,
216 216 gthread = 0,
217 217 qthread = 0,
218 218 wthread = 0,
219 219 pylab = 0,
220 220 tk = 0,
221 221 upgrade = 0,
222 222 Version = 0,
223 223 xmode = 'Verbose',
224 224 wildcards_case_sensitive = 1,
225 225 magic_docstrings = 0, # undocumented, for doc generation
226 226 )
227 227
228 228 # Things that will *only* appear in rcfiles (not at the command line).
229 229 # Make sure there's a space before each end of line (they get auto-joined!)
230 230 rcfile_opts = { qwflat: 'include import_mod import_all execfile ',
231 231 qw_lol: 'import_some ',
232 232 # for things with embedded whitespace:
233 233 list_strings:'execute alias readline_parse_and_bind ',
234 234 # Regular strings need no conversion:
235 235 None:'readline_remove_delims ',
236 236 }
237 237 # Default values for these
238 238 rc_def = Struct(include = [],
239 239 import_mod = [],
240 240 import_all = [],
241 241 import_some = [[]],
242 242 execute = [],
243 243 execfile = [],
244 244 alias = [],
245 245 readline_parse_and_bind = [],
246 246 readline_remove_delims = '',
247 247 )
248 248
249 249 # Build the type conversion dictionary from the above tables:
250 250 typeconv = rcfile_opts.copy()
251 251 typeconv.update(optstr2types(cmdline_opts))
252 252
253 253 # FIXME: the None key appears in both, put that back together by hand. Ugly!
254 254 typeconv[None] += ' ' + rcfile_opts[None]
255 255
256 256 # Remove quotes at ends of all strings (used to protect spaces)
257 257 typeconv[unquote_ends] = typeconv[None]
258 258 del typeconv[None]
259 259
260 260 # Build the list we'll use to make all config decisions with defaults:
261 261 opts_all = opts_def.copy()
262 262 opts_all.update(rc_def)
263 263
264 264 # Build conflict resolver for recursive loading of config files:
265 265 # - preserve means the outermost file maintains the value, it is not
266 266 # overwritten if an included file has the same key.
267 267 # - add_flip applies + to the two values, so it better make sense to add
268 268 # those types of keys. But it flips them first so that things loaded
269 269 # deeper in the inclusion chain have lower precedence.
270 270 conflict = {'preserve': ' '.join([ typeconv[int],
271 271 typeconv[unquote_ends] ]),
272 272 'add_flip': ' '.join([ typeconv[qwflat],
273 273 typeconv[qw_lol],
274 274 typeconv[list_strings] ])
275 275 }
276 276
277 277 # Now actually process the command line
278 278 getopt = DPyGetOpt.DPyGetOpt()
279 279 getopt.setIgnoreCase(0)
280 280
281 281 getopt.parseConfiguration(opts_names)
282 282
283 283 try:
284 284 getopt.processArguments(argv)
285 285 except:
286 286 print cmd_line_usage
287 287 warn('\nError in Arguments: ' + `sys.exc_value`)
288 288 sys.exit(1)
289 289
290 290 # convert the options dict to a struct for much lighter syntax later
291 291 opts = Struct(getopt.optionValues)
292 292 args = getopt.freeValues
293 293
294 294 # this is the struct (which has default values at this point) with which
295 295 # we make all decisions:
296 296 opts_all.update(opts)
297 297
298 298 # Options that force an immediate exit
299 299 if opts_all.help:
300 300 page(cmd_line_usage)
301 301 sys.exit()
302 302
303 303 if opts_all.Version:
304 304 print __version__
305 305 sys.exit()
306 306
307 307 if opts_all.magic_docstrings:
308 308 IP.magic_magic('-latex')
309 309 sys.exit()
310 310
311 311 # Create user config directory if it doesn't exist. This must be done
312 312 # *after* getting the cmd line options.
313 313 if not os.path.isdir(opts_all.ipythondir):
314 314 IP.user_setup(opts_all.ipythondir,rc_suffix,'install')
315 315
316 316 # upgrade user config files while preserving a copy of the originals
317 317 if opts_all.upgrade:
318 318 IP.user_setup(opts_all.ipythondir,rc_suffix,'upgrade')
319 319
320 320 # check mutually exclusive options in the *original* command line
321 321 mutex_opts(opts,[qw('log logfile'),qw('rcfile profile'),
322 322 qw('classic profile'),qw('classic rcfile')])
323 323
324 324 #---------------------------------------------------------------------------
325 325 # Log replay
326 326
327 327 # if -logplay, we need to 'become' the other session. That basically means
328 328 # replacing the current command line environment with that of the old
329 329 # session and moving on.
330 330
331 331 # this is needed so that later we know we're in session reload mode, as
332 332 # opts_all will get overwritten:
333 333 load_logplay = 0
334 334
335 335 if opts_all.logplay:
336 336 load_logplay = opts_all.logplay
337 337 opts_debug_save = opts_all.debug
338 338 try:
339 339 logplay = open(opts_all.logplay)
340 340 except IOError:
341 341 if opts_all.debug: IP.InteractiveTB()
342 342 warn('Could not open logplay file '+`opts_all.logplay`)
343 343 # restore state as if nothing had happened and move on, but make
344 344 # sure that later we don't try to actually load the session file
345 345 logplay = None
346 346 load_logplay = 0
347 347 del opts_all.logplay
348 348 else:
349 349 try:
350 350 logplay.readline()
351 351 logplay.readline();
352 352 # this reloads that session's command line
353 353 cmd = logplay.readline()[6:]
354 354 exec cmd
355 355 # restore the true debug flag given so that the process of
356 356 # session loading itself can be monitored.
357 357 opts.debug = opts_debug_save
358 358 # save the logplay flag so later we don't overwrite the log
359 359 opts.logplay = load_logplay
360 360 # now we must update our own structure with defaults
361 361 opts_all.update(opts)
362 362 # now load args
363 363 cmd = logplay.readline()[6:]
364 364 exec cmd
365 365 logplay.close()
366 366 except:
367 367 logplay.close()
368 368 if opts_all.debug: IP.InteractiveTB()
369 369 warn("Logplay file lacking full configuration information.\n"
370 370 "I'll try to read it, but some things may not work.")
371 371
372 372 #-------------------------------------------------------------------------
373 373 # set up output traps: catch all output from files, being run, modules
374 374 # loaded, etc. Then give it to the user in a clean form at the end.
375 375
376 376 msg_out = 'Output messages. '
377 377 msg_err = 'Error messages. '
378 378 msg_sep = '\n'
379 379 msg = Struct(config = OutputTrap('Configuration Loader',msg_out,
380 380 msg_err,msg_sep,debug,
381 381 quiet_out=1),
382 382 user_exec = OutputTrap('User File Execution',msg_out,
383 383 msg_err,msg_sep,debug),
384 384 logplay = OutputTrap('Log Loader',msg_out,
385 385 msg_err,msg_sep,debug),
386 386 summary = ''
387 387 )
388 388
389 389 #-------------------------------------------------------------------------
390 390 # Process user ipythonrc-type configuration files
391 391
392 392 # turn on output trapping and log to msg.config
393 393 # remember that with debug on, trapping is actually disabled
394 394 msg.config.trap_all()
395 395
396 396 # look for rcfile in current or default directory
397 397 try:
398 398 opts_all.rcfile = filefind(opts_all.rcfile,opts_all.ipythondir)
399 399 except IOError:
400 400 if opts_all.debug: IP.InteractiveTB()
401 401 warn('Configuration file %s not found. Ignoring request.'
402 402 % (opts_all.rcfile) )
403 403
404 404 # 'profiles' are a shorthand notation for config filenames
405 405 if opts_all.profile:
406 406 try:
407 407 opts_all.rcfile = filefind('ipythonrc-' + opts_all.profile
408 408 + rc_suffix,
409 409 opts_all.ipythondir)
410 410 except IOError:
411 411 if opts_all.debug: IP.InteractiveTB()
412 412 opts.profile = '' # remove profile from options if invalid
413 413 warn('Profile configuration file %s not found. Ignoring request.'
414 414 % (opts_all.profile) )
415 415
416 416 # load the config file
417 417 rcfiledata = None
418 418 if opts_all.quick:
419 419 print 'Launching IPython in quick mode. No config file read.'
420 420 elif opts_all.classic:
421 421 print 'Launching IPython in classic mode. No config file read.'
422 422 elif opts_all.rcfile:
423 423 try:
424 424 cfg_loader = ConfigLoader(conflict)
425 425 rcfiledata = cfg_loader.load(opts_all.rcfile,typeconv,
426 426 'include',opts_all.ipythondir,
427 427 purge = 1,
428 428 unique = conflict['preserve'])
429 429 except:
430 430 IP.InteractiveTB()
431 431 warn('Problems loading configuration file '+
432 432 `opts_all.rcfile`+
433 433 '\nStarting with default -bare bones- configuration.')
434 434 else:
435 435 warn('No valid configuration file found in either currrent directory\n'+
436 436 'or in the IPython config. directory: '+`opts_all.ipythondir`+
437 437 '\nProceeding with internal defaults.')
438 438
439 439 #------------------------------------------------------------------------
440 440 # Set exception handlers in mode requested by user.
441 441 otrap = OutputTrap(trap_out=1) # trap messages from magic_xmode
442 442 IP.magic_xmode(opts_all.xmode)
443 443 otrap.release_out()
444 444
445 445 #------------------------------------------------------------------------
446 446 # Execute user config
447 447
448 448 # Create a valid config structure with the right precedence order:
449 449 # defaults < rcfile < command line. This needs to be in the instance, so
450 450 # that method calls below that rely on it find it.
451 451 IP.rc = rc_def.copy()
452 452
453 453 # Work with a local alias inside this routine to avoid unnecessary
454 454 # attribute lookups.
455 455 IP_rc = IP.rc
456 456
457 457 IP_rc.update(opts_def)
458 458 if rcfiledata:
459 459 # now we can update
460 460 IP_rc.update(rcfiledata)
461 461 IP_rc.update(opts)
462 462 IP_rc.update(rc_override)
463 463
464 464 # Store the original cmd line for reference:
465 465 IP_rc.opts = opts
466 466 IP_rc.args = args
467 467
468 468 # create a *runtime* Struct like rc for holding parameters which may be
469 469 # created and/or modified by runtime user extensions.
470 470 IP.runtime_rc = Struct()
471 471
472 472 # from this point on, all config should be handled through IP_rc,
473 473 # opts* shouldn't be used anymore.
474 474
475 475 # add personal .ipython dir to sys.path so that users can put things in
476 476 # there for customization
477 477 sys.path.append(IP_rc.ipythondir)
478 478 sys.path.insert(0, '') # add . to sys.path. Fix from Prabhu Ramachandran
479 479
480 480 # update IP_rc with some special things that need manual
481 481 # tweaks. Basically options which affect other options. I guess this
482 482 # should just be written so that options are fully orthogonal and we
483 483 # wouldn't worry about this stuff!
484 484
485 485 if IP_rc.classic:
486 486 IP_rc.quick = 1
487 487 IP_rc.cache_size = 0
488 488 IP_rc.pprint = 0
489 489 IP_rc.prompt_in1 = '>>> '
490 490 IP_rc.prompt_in2 = '... '
491 491 IP_rc.prompt_out = ''
492 492 IP_rc.separate_in = IP_rc.separate_out = IP_rc.separate_out2 = '0'
493 493 IP_rc.colors = 'NoColor'
494 494 IP_rc.xmode = 'Plain'
495 495
496 496 # configure readline
497 497 # Define the history file for saving commands in between sessions
498 498 if IP_rc.profile:
499 499 histfname = 'history-%s' % IP_rc.profile
500 500 else:
501 501 histfname = 'history'
502 502 IP.histfile = os.path.join(opts_all.ipythondir,histfname)
503 503
504 504 # update exception handlers with rc file status
505 505 otrap.trap_out() # I don't want these messages ever.
506 506 IP.magic_xmode(IP_rc.xmode)
507 507 otrap.release_out()
508 508
509 509 # activate logging if requested and not reloading a log
510 510 if IP_rc.logplay:
511 511 IP.magic_logstart(IP_rc.logplay + ' append')
512 512 elif IP_rc.logfile:
513 513 IP.magic_logstart(IP_rc.logfile)
514 514 elif IP_rc.log:
515 515 IP.magic_logstart()
516 516
517 517 # find user editor so that it we don't have to look it up constantly
518 518 if IP_rc.editor.strip()=='0':
519 519 try:
520 520 ed = os.environ['EDITOR']
521 521 except KeyError:
522 522 if os.name == 'posix':
523 523 ed = 'vi' # the only one guaranteed to be there!
524 524 else:
525 525 ed = 'notepad' # same in Windows!
526 526 IP_rc.editor = ed
527 527
528 528 # Keep track of whether this is an embedded instance or not (useful for
529 529 # post-mortems).
530 530 IP_rc.embedded = IP.embedded
531 531
532 532 # Recursive reload
533 533 try:
534 534 from IPython import deep_reload
535 535 if IP_rc.deep_reload:
536 536 __builtin__.reload = deep_reload.reload
537 537 else:
538 538 __builtin__.dreload = deep_reload.reload
539 539 del deep_reload
540 540 except ImportError:
541 541 pass
542 542
543 543 # Save the current state of our namespace so that the interactive shell
544 544 # can later know which variables have been created by us from config files
545 545 # and loading. This way, loading a file (in any way) is treated just like
546 546 # defining things on the command line, and %who works as expected.
547 547
548 548 # DON'T do anything that affects the namespace beyond this point!
549 549 IP.internal_ns.update(__main__.__dict__)
550 550
551 551 #IP.internal_ns.update(locals()) # so our stuff doesn't show up in %who
552 552
553 553 # Now run through the different sections of the users's config
554 554 if IP_rc.debug:
555 555 print 'Trying to execute the following configuration structure:'
556 556 print '(Things listed first are deeper in the inclusion tree and get'
557 557 print 'loaded first).\n'
558 558 pprint(IP_rc.__dict__)
559 559
560 560 for mod in IP_rc.import_mod:
561 561 try:
562 562 exec 'import '+mod in IP.user_ns
563 563 except :
564 564 IP.InteractiveTB()
565 565 import_fail_info(mod)
566 566
567 567 for mod_fn in IP_rc.import_some:
568 568 if mod_fn == []: break
569 569 mod,fn = mod_fn[0],','.join(mod_fn[1:])
570 570 try:
571 571 exec 'from '+mod+' import '+fn in IP.user_ns
572 572 except :
573 573 IP.InteractiveTB()
574 574 import_fail_info(mod,fn)
575 575
576 576 for mod in IP_rc.import_all:
577 577 try:
578 578 exec 'from '+mod+' import *' in IP.user_ns
579 579 except :
580 580 IP.InteractiveTB()
581 581 import_fail_info(mod)
582 582
583 583 for code in IP_rc.execute:
584 584 try:
585 585 exec code in IP.user_ns
586 586 except:
587 587 IP.InteractiveTB()
588 588 warn('Failure executing code: ' + `code`)
589 589
590 590 # Execute the files the user wants in ipythonrc
591 591 for file in IP_rc.execfile:
592 592 try:
593 593 file = filefind(file,sys.path+[IPython_dir])
594 594 except IOError:
595 595 warn(itpl('File $file not found. Skipping it.'))
596 596 else:
597 597 IP.safe_execfile(os.path.expanduser(file),IP.user_ns)
598 598
599 599 # release stdout and stderr and save config log into a global summary
600 600 msg.config.release_all()
601 601 if IP_rc.messages:
602 602 msg.summary += msg.config.summary_all()
603 603
604 604 #------------------------------------------------------------------------
605 605 # Setup interactive session
606 606
607 607 # Now we should be fully configured. We can then execute files or load
608 608 # things only needed for interactive use. Then we'll open the shell.
609 609
610 610 # Take a snapshot of the user namespace before opening the shell. That way
611 611 # we'll be able to identify which things were interactively defined and
612 612 # which were defined through config files.
613 613 IP.user_config_ns = IP.user_ns.copy()
614 614
615 615 # Force reading a file as if it were a session log. Slower but safer.
616 616 if load_logplay:
617 617 print 'Replaying log...'
618 618 try:
619 619 if IP_rc.debug:
620 620 logplay_quiet = 0
621 621 else:
622 622 logplay_quiet = 1
623 623
624 624 msg.logplay.trap_all()
625 625 IP.safe_execfile(load_logplay,IP.user_ns,
626 626 islog = 1, quiet = logplay_quiet)
627 627 msg.logplay.release_all()
628 628 if IP_rc.messages:
629 629 msg.summary += msg.logplay.summary_all()
630 630 except:
631 631 warn('Problems replaying logfile %s.' % load_logplay)
632 632 IP.InteractiveTB()
633 633
634 634 # Load remaining files in command line
635 635 msg.user_exec.trap_all()
636 636
637 637 # Do NOT execute files named in the command line as scripts to be loaded
638 638 # by embedded instances. Doing so has the potential for an infinite
639 639 # recursion if there are exceptions thrown in the process.
640 640
641 641 # XXX FIXME: the execution of user files should be moved out to after
642 642 # ipython is fully initialized, just as if they were run via %run at the
643 643 # ipython prompt. This would also give them the benefit of ipython's
644 644 # nice tracebacks.
645 645
646 646 if not embedded and IP_rc.args:
647 647 name_save = IP.user_ns['__name__']
648 648 IP.user_ns['__name__'] = '__main__'
649 649 try:
650 650 # Set our own excepthook in case the user code tries to call it
651 651 # directly. This prevents triggering the IPython crash handler.
652 652 old_excepthook,sys.excepthook = sys.excepthook, IP.excepthook
653 653 for run in args:
654 654 IP.safe_execfile(run,IP.user_ns)
655 655 finally:
656 656 # Reset our crash handler in place
657 657 sys.excepthook = old_excepthook
658 658
659 659 IP.user_ns['__name__'] = name_save
660 660
661 661 msg.user_exec.release_all()
662 662 if IP_rc.messages:
663 663 msg.summary += msg.user_exec.summary_all()
664 664
665 665 # since we can't specify a null string on the cmd line, 0 is the equivalent:
666 666 if IP_rc.nosep:
667 667 IP_rc.separate_in = IP_rc.separate_out = IP_rc.separate_out2 = '0'
668 668 if IP_rc.separate_in == '0': IP_rc.separate_in = ''
669 669 if IP_rc.separate_out == '0': IP_rc.separate_out = ''
670 670 if IP_rc.separate_out2 == '0': IP_rc.separate_out2 = ''
671 671 IP_rc.separate_in = IP_rc.separate_in.replace('\\n','\n')
672 672 IP_rc.separate_out = IP_rc.separate_out.replace('\\n','\n')
673 673 IP_rc.separate_out2 = IP_rc.separate_out2.replace('\\n','\n')
674 674
675 675 # Determine how many lines at the bottom of the screen are needed for
676 676 # showing prompts, so we can know wheter long strings are to be printed or
677 677 # paged:
678 678 num_lines_bot = IP_rc.separate_in.count('\n')+1
679 679 IP_rc.screen_length = IP_rc.screen_length - num_lines_bot
680 680
681 681 # configure startup banner
682 682 if IP_rc.c: # regular python doesn't print the banner with -c
683 683 IP_rc.banner = 0
684 684 if IP_rc.banner:
685 685 BANN_P = IP.BANNER_PARTS
686 686 else:
687 687 BANN_P = []
688 688
689 689 if IP_rc.profile: BANN_P.append('IPython profile: %s\n' % IP_rc.profile)
690 690
691 691 # add message log (possibly empty)
692 692 if msg.summary: BANN_P.append(msg.summary)
693 693 # Final banner is a string
694 694 IP.BANNER = '\n'.join(BANN_P)
695 695
696 696 # Finalize the IPython instance. This assumes the rc structure is fully
697 697 # in place.
698 698 IP.post_config_initialization()
699 699
700 700 return IP
701 701 #************************ end of file <ipmaker.py> **************************
@@ -1,585 +1,589 b''
1 1 # -*- coding: utf-8 -*-
2 2 #*****************************************************************************
3 3 # Copyright (C) 2001-2004 Fernando Perez. <fperez@colorado.edu>
4 4 #
5 5 # Distributed under the terms of the BSD License. The full license is in
6 6 # the file COPYING, distributed as part of this software.
7 7 #*****************************************************************************
8 8
9 # $Id: usage.py 966 2005-12-29 08:34:07Z fperez $
9 # $Id: usage.py 990 2006-01-04 06:59:02Z fperez $
10 10
11 11 from IPython import Release
12 12 __author__ = '%s <%s>' % Release.authors['Fernando']
13 13 __license__ = Release.license
14 14 __version__ = Release.version
15 15
16 16 __doc__ = """
17 17 IPython -- An enhanced Interactive Python
18 18 =========================================
19 19
20 20 A Python shell with automatic history (input and output), dynamic object
21 21 introspection, easier configuration, command completion, access to the system
22 22 shell and more.
23 23
24 24 IPython can also be embedded in running programs. See EMBEDDING below.
25 25
26 26
27 27 USAGE
28 28 ipython [options] files
29 29
30 30 If invoked with no options, it executes all the files listed in
31 31 sequence and drops you into the interpreter while still acknowledging
32 32 any options you may have set in your ipythonrc file. This behavior is
33 33 different from standard Python, which when called as python -i will
34 34 only execute one file and will ignore your configuration setup.
35 35
36 36 Please note that some of the configuration options are not available at
37 37 the command line, simply because they are not practical here. Look into
38 38 your ipythonrc configuration file for details on those. This file
39 39 typically installed in the $HOME/.ipython directory.
40 40
41 41 For Windows users, $HOME resolves to C:\\Documents and
42 42 Settings\\YourUserName in most instances, and _ipython is used instead
43 43 of .ipython, since some Win32 programs have problems with dotted names
44 44 in directories.
45 45
46 46 In the rest of this text, we will refer to this directory as
47 47 IPYTHONDIR.
48 48
49 49
50 50 SPECIAL THREADING OPTIONS
51 51 The following special options are ONLY valid at the beginning of the
52 52 command line, and not later. This is because they control the initial-
53 53 ization of ipython itself, before the normal option-handling mechanism
54 54 is active.
55 55
56 56 -gthread, -qthread, -wthread, -pylab
57 57
58 58 Only ONE of these can be given, and it can only be given as the
59 59 first option passed to IPython (it will have no effect in any
60 60 other position). They provide threading support for the GTK, QT
61 61 and WXWidgets toolkits, and for the matplotlib library.
62 62
63 63 With any of the first three options, IPython starts running a
64 64 separate thread for the graphical toolkit's operation, so that
65 65 you can open and control graphical elements from within an
66 66 IPython command line, without blocking. All three provide
67 67 essentially the same functionality, respectively for GTK, QT and
68 68 WXWidgets (via their Python interfaces).
69 69
70 70 If -pylab is given, IPython loads special support for the mat-
71 71 plotlib library (http://matplotlib.sourceforge.net), allowing
72 72 interactive usage of any of its backends as defined in the
73 73 user's .matplotlibrc file. It automatically activates GTK, QT
74 74 or WX threading for IPyhton if the choice of matplotlib backend
75 75 requires it. It also modifies the %run command to correctly
76 76 execute (without blocking) any matplotlib-based script which
77 77 calls show() at the end.
78 78
79 79 -tk The -g/q/wthread options, and -pylab (if matplotlib is
80 80 configured to use GTK, QT or WX), will normally block Tk
81 81 graphical interfaces. This means that when GTK, QT or WX
82 82 threading is active, any attempt to open a Tk GUI will result in
83 83 a dead window, and possibly cause the Python interpreter to
84 84 crash. An extra option, -tk, is available to address this
85 85 issue. It can ONLY be given as a SECOND option after any of the
86 86 above (-gthread, -qthread, -wthread or -pylab).
87 87
88 88 If -tk is given, IPython will try to coordinate Tk threading
89 89 with GTK, QT or WX. This is however potentially unreliable, and
90 90 you will have to test on your platform and Python configuration
91 91 to determine whether it works for you. Debian users have
92 92 reported success, apparently due to the fact that Debian builds
93 93 all of Tcl, Tk, Tkinter and Python with pthreads support. Under
94 94 other Linux environments (such as Fedora Core 2/3), this option
95 95 has caused random crashes and lockups of the Python interpreter.
96 96 Under other operating systems (Mac OSX and Windows), you'll need
97 97 to try it to find out, since currently no user reports are
98 98 available.
99 99
100 100 There is unfortunately no way for IPython to determine at run-
101 101 time whether -tk will work reliably or not, so you will need to
102 102 do some experiments before relying on it for regular work.
103 103
104 104 A WARNING ABOUT SIGNALS AND THREADS
105 105
106 106 When any of the thread systems (GTK, QT or WX) are active, either
107 107 directly or via -pylab with a threaded backend, it is impossible to
108 108 interrupt long-running Python code via Ctrl-C. IPython can not pass
109 109 the KeyboardInterrupt exception (or the underlying SIGINT) across
110 110 threads, so any long-running process started from IPython will run to
111 111 completion, or will have to be killed via an external (OS-based)
112 112 mechanism.
113 113
114 114 To the best of my knowledge, this limitation is imposed by the Python
115 115 interpreter itself, and it comes from the difficulty of writing
116 116 portable signal/threaded code. If any user is an expert on this topic
117 117 and can suggest a better solution, I would love to hear about it. In
118 118 the IPython sources, look at the Shell.py module, and in particular at
119 119 the runcode() method.
120 120
121 121 REGULAR OPTIONS
122 122 After the above threading options have been given, regular options can
123 123 follow in any order. All options can be abbreviated to their shortest
124 124 non-ambiguous form and are case-sensitive. One or two dashes can be
125 125 used. Some options have an alternate short form, indicated after a |.
126 126
127 127 Most options can also be set from your ipythonrc configuration file.
128 128 See the provided examples for assistance. Options given on the comman-
129 129 dline override the values set in the ipythonrc file.
130 130
131 131 All options with a [no] prepended can be specified in negated form
132 132 (using -nooption instead of -option) to turn the feature off.
133 133
134 134 -h, --help
135 135 Show summary of options.
136 136
137 137 -pylab This can only be given as the first option passed to IPython (it
138 138 will have no effect in any other position). It adds special sup-
139 139 port for the matplotlib library (http://matplotlib.source-
140 140 forge.net), allowing interactive usage of any of its backends as
141 141 defined in the user’s .matplotlibrc file. It automatically
142 142 activates GTK or WX threading for IPyhton if the choice of mat-
143 143 plotlib backend requires it. It also modifies the @run command
144 144 to correctly execute (without blocking) any matplotlib-based
145 145 script which calls show() at the end.
146 146
147 -[no]autocall
148 Make IPython automatically call any callable object even if you
149 didnt type explicit parentheses. For example, ’str 43’ becomes
150 ’str(43)’ automatically.
147 -autocall <val>
148 Make IPython automatically call any callable object even if you
149 didn't type explicit parentheses. For example, 'str 43' becomes
150 'str(43)' automatically. The value can be '0' to disable the
151 feature, '1' for 'smart' autocall, where it is not applied if
152 there are no more arguments on the line, and '2' for 'full'
153 autocall, where all callable objects are automatically called
154 (even if no arguments are present). The default is '1'.
151 155
152 156 -[no]autoindent
153 157 Turn automatic indentation on/off.
154 158
155 159 -[no]automagic
156 160 Make magic commands automatic (without needing their first char-
157 161 acter to be %). Type %magic at the IPython prompt for more
158 162 information.
159 163
160 164 -[no]autoedit_syntax
161 165 When a syntax error occurs after editing a file, automatically
162 166 open the file to the trouble causing line for convenient fixing.
163 167
164 168 -[no]banner
165 169 Print the intial information banner (default on).
166 170
167 171 -c <command>
168 172 Execute the given command string, and set sys.argv to [’c’].
169 173 This is similar to the -c option in the normal Python inter-
170 174 preter.
171 175
172 176 -cache_size|cs <n>
173 177 Size of the output cache (maximum number of entries to hold in
174 178 memory). The default is 1000, you can change it permanently in
175 179 your config file. Setting it to 0 completely disables the
176 180 caching system, and the minimum value accepted is 20 (if you
177 181 provide a value less than 20, it is reset to 0 and a warning is
178 182 issued). This limit is defined because otherwise you’ll spend
179 183 more time re-flushing a too small cache than working.
180 184
181 185 -classic|cl
182 186 Gives IPython a similar feel to the classic Python prompt.
183 187
184 188 -colors <scheme>
185 189 Color scheme for prompts and exception reporting. Currently
186 190 implemented: NoColor, Linux, and LightBG.
187 191
188 192 -[no]color_info
189 193 IPython can display information about objects via a set of func-
190 194 tions, and optionally can use colors for this, syntax highlight-
191 195 ing source code and various other elements. However, because
192 196 this information is passed through a pager (like ’less’) and
193 197 many pagers get confused with color codes, this option is off by
194 198 default. You can test it and turn it on permanently in your
195 199 ipythonrc file if it works for you. As a reference, the ’less’
196 200 pager supplied with Mandrake 8.2 works ok, but that in RedHat
197 201 7.2 doesn’t.
198 202
199 203 Test it and turn it on permanently if it works with your system.
200 204 The magic function @color_info allows you to toggle this inter-
201 205 actively for testing.
202 206
203 207 -[no]confirm_exit
204 208 Set to confirm when you try to exit IPython with an EOF (Con-
205 209 trol-D in Unix, Control-Z/Enter in Windows). Note that using the
206 210 magic functions @Exit or @Quit you can force a direct exit,
207 211 bypassing any confirmation.
208 212
209 213 -[no]debug
210 214 Show information about the loading process. Very useful to pin
211 215 down problems with your configuration files or to get details
212 216 about session restores.
213 217
214 218 -[no]deep_reload
215 219 IPython can use the deep_reload module which reloads changes in
216 220 modules recursively (it replaces the reload() function, so you
217 221 don’t need to change anything to use it). deep_reload() forces a
218 222 full reload of modules whose code may have changed, which the
219 223 default reload() function does not.
220 224
221 225 When deep_reload is off, IPython will use the normal reload(),
222 226 but deep_reload will still be available as dreload(). This fea-
223 227 ture is off by default [which means that you have both normal
224 228 reload() and dreload()].
225 229
226 230 -editor <name>
227 231 Which editor to use with the @edit command. By default, IPython
228 232 will honor your EDITOR environment variable (if not set, vi is
229 233 the Unix default and notepad the Windows one). Since this editor
230 234 is invoked on the fly by IPython and is meant for editing small
231 235 code snippets, you may want to use a small, lightweight editor
232 236 here (in case your default EDITOR is something like Emacs).
233 237
234 238 -ipythondir <name>
235 239 The name of your IPython configuration directory IPYTHONDIR.
236 240 This can also be specified through the environment variable
237 241 IPYTHONDIR.
238 242
239 243 -log|l Generate a log file of all input. The file is named
240 244 ipython_log.py in your current directory (which prevents logs
241 245 from multiple IPython sessions from trampling each other). You
242 246 can use this to later restore a session by loading your logfile
243 247 as a file to be executed with option -logplay (see below).
244 248
245 249 -logfile|lf
246 250 Specify the name of your logfile.
247 251
248 252 -logplay|lp
249 253 Replay a previous log. For restoring a session as close as pos-
250 254 sible to the state you left it in, use this option (don’t just
251 255 run the logfile). With -logplay, IPython will try to reconstruct
252 256 the previous working environment in full, not just execute the
253 257 commands in the logfile.
254 258 When a session is restored, logging is automatically turned on
255 259 again with the name of the logfile it was invoked with (it is
256 260 read from the log header). So once you’ve turned logging on for
257 261 a session, you can quit IPython and reload it as many times as
258 262 you want and it will continue to log its history and restore
259 263 from the beginning every time.
260 264
261 265 Caveats: there are limitations in this option. The history vari-
262 266 ables _i*,_* and _dh don’t get restored properly. In the future
263 267 we will try to implement full session saving by writing and
264 268 retrieving a failed because of inherent limitations of Python’s
265 269 Pickle module, so this may have to wait.
266 270
267 271 -[no]messages
268 272 Print messages which IPython collects about its startup process
269 273 (default on).
270 274
271 275 -[no]pdb
272 276 Automatically call the pdb debugger after every uncaught excep-
273 277 tion. If you are used to debugging using pdb, this puts you
274 278 automatically inside of it after any call (either in IPython or
275 279 in code called by it) which triggers an exception which goes
276 280 uncaught.
277 281
278 282 -[no]pprint
279 283 IPython can optionally use the pprint (pretty printer) module
280 284 for displaying results. pprint tends to give a nicer display of
281 285 nested data structures. If you like it, you can turn it on per-
282 286 manently in your config file (default off).
283 287
284 288 -profile|p <name>
285 289 Assume that your config file is ipythonrc-<name> (looks in cur-
286 290 rent dir first, then in IPYTHONDIR). This is a quick way to keep
287 291 and load multiple config files for different tasks, especially
288 292 if you use the include option of config files. You can keep a
289 293 basic IPYTHONDIR/ipythonrc file and then have other ’profiles’
290 294 which include this one and load extra things for particular
291 295 tasks. For example:
292 296
293 297 1) $HOME/.ipython/ipythonrc : load basic things you always want.
294 298 2) $HOME/.ipython/ipythonrc-math : load (1) and basic math-
295 299 related modules.
296 300 3) $HOME/.ipython/ipythonrc-numeric : load (1) and Numeric and
297 301 plotting modules.
298 302
299 303 Since it is possible to create an endless loop by having circu-
300 304 lar file inclusions, IPython will stop if it reaches 15 recur-
301 305 sive inclusions.
302 306
303 307 -prompt_in1|pi1 <string>
304 308 Specify the string used for input prompts. Note that if you are
305 309 using numbered prompts, the number is represented with a ’\#’ in
306 310 the string. Don’t forget to quote strings with spaces embedded
307 311 in them. Default: ’In [\#]:’.
308 312
309 313 Most bash-like escapes can be used to customize IPython’s
310 314 prompts, as well as a few additional ones which are IPython-spe-
311 315 cific. All valid prompt escapes are described in detail in the
312 316 Customization section of the IPython HTML/PDF manual.
313 317
314 318 -prompt_in2|pi2 <string>
315 319 Similar to the previous option, but used for the continuation
316 320 prompts. The special sequence ’\D’ is similar to ’\#’, but with
317 321 all digits replaced dots (so you can have your continuation
318 322 prompt aligned with your input prompt). Default: ’ .\D.:’
319 323 (note three spaces at the start for alignment with ’In [\#]’).
320 324
321 325 -prompt_out|po <string>
322 326 String used for output prompts, also uses numbers like
323 327 prompt_in1. Default: ’Out[\#]:’.
324 328
325 329 -quick Start in bare bones mode (no config file loaded).
326 330
327 331 -rcfile <name>
328 332 Name of your IPython resource configuration file. normally
329 333 IPython loads ipythonrc (from current directory) or
330 334 IPYTHONDIR/ipythonrc. If the loading of your config file fails,
331 335 IPython starts with a bare bones configuration (no modules
332 336 loaded at all).
333 337
334 338 -[no]readline
335 339 Use the readline library, which is needed to support name com-
336 340 pletion and command history, among other things. It is enabled
337 341 by default, but may cause problems for users of X/Emacs in
338 342 Python comint or shell buffers.
339 343
340 344 Note that emacs ’eterm’ buffers (opened with M-x term) support
341 345 IPython’s readline and syntax coloring fine, only ’emacs’ (M-x
342 346 shell and C-c !) buffers do not.
343 347
344 348 -screen_length|sl <n>
345 349 Number of lines of your screen. This is used to control print-
346 350 ing of very long strings. Strings longer than this number of
347 351 lines will be sent through a pager instead of directly printed.
348 352
349 353 The default value for this is 0, which means IPython will auto-
350 354 detect your screen size every time it needs to print certain
351 355 potentially long strings (this doesn’t change the behavior of
352 356 the ’print’ keyword, it’s only triggered internally). If for
353 357 some reason this isn’t working well (it needs curses support),
354 358 specify it yourself. Otherwise don’t change the default.
355 359
356 360 -separate_in|si <string>
357 361 Separator before input prompts. Default ’0.
358 362
359 363 -separate_out|so <string>
360 364 Separator before output prompts. Default: 0 (nothing).
361 365
362 366 -separate_out2|so2 <string>
363 367 Separator after output prompts. Default: 0 (nothing).
364 368
365 369 -nosep Shorthand for ’-separate_in 0 -separate_out 0 -separate_out2 0’.
366 370 Simply removes all input/output separators.
367 371
368 372 -upgrade
369 373 Allows you to upgrade your IPYTHONDIR configuration when you
370 374 install a new version of IPython. Since new versions may
371 375 include new command lines options or example files, this copies
372 376 updated ipythonrc-type files. However, it backs up (with a .old
373 377 extension) all files which it overwrites so that you can merge
374 378 back any custimizations you might have in your personal files.
375 379
376 380 -Version
377 381 Print version information and exit.
378 382
379 383 -xmode <modename>
380 384 Mode for exception reporting. The valid modes are Plain, Con-
381 385 text, and Verbose.
382 386
383 387 - Plain: similar to python’s normal traceback printing.
384 388
385 389 - Context: prints 5 lines of context source code around each
386 390 line in the traceback.
387 391
388 392 - Verbose: similar to Context, but additionally prints the vari-
389 393 ables currently visible where the exception happened (shortening
390 394 their strings if too long). This can potentially be very slow,
391 395 if you happen to have a huge data structure whose string repre-
392 396 sentation is complex to compute. Your computer may appear to
393 397 freeze for a while with cpu usage at 100%. If this occurs, you
394 398 can cancel the traceback with Ctrl-C (maybe hitting it more than
395 399 once).
396 400
397 401
398 402 EMBEDDING
399 403 It is possible to start an IPython instance inside your own Python pro-
400 404 grams. In the documentation example files there are some illustrations
401 405 on how to do this.
402 406
403 407 This feature allows you to evalutate dynamically the state of your
404 408 code, operate with your variables, analyze them, etc. Note however
405 409 that any changes you make to values while in the shell do NOT propagate
406 410 back to the running code, so it is safe to modify your values because
407 411 you won’t break your code in bizarre ways by doing so.
408 412 """
409 413
410 414 cmd_line_usage = __doc__
411 415
412 416 #---------------------------------------------------------------------------
413 417 interactive_usage = """
414 418 IPython -- An enhanced Interactive Python
415 419 =========================================
416 420
417 421 IPython offers a combination of convenient shell features, special commands
418 422 and a history mechanism for both input (command history) and output (results
419 423 caching, similar to Mathematica). It is intended to be a fully compatible
420 424 replacement for the standard Python interpreter, while offering vastly
421 425 improved functionality and flexibility.
422 426
423 427 At your system command line, type 'ipython -help' to see the command line
424 428 options available. This document only describes interactive features.
425 429
426 430 Warning: IPython relies on the existence of a global variable called __IP which
427 431 controls the shell itself. If you redefine __IP to anything, bizarre behavior
428 432 will quickly occur.
429 433
430 434 MAIN FEATURES
431 435
432 436 * Access to the standard Python help. As of Python 2.1, a help system is
433 437 available with access to object docstrings and the Python manuals. Simply
434 438 type 'help' (no quotes) to access it.
435 439
436 440 * Magic commands: type %magic for information on the magic subsystem.
437 441
438 442 * System command aliases, via the %alias command or the ipythonrc config file.
439 443
440 444 * Dynamic object information:
441 445
442 446 Typing ?word or word? prints detailed information about an object. If
443 447 certain strings in the object are too long (docstrings, code, etc.) they get
444 448 snipped in the center for brevity.
445 449
446 450 Typing ??word or word?? gives access to the full information without
447 451 snipping long strings. Long strings are sent to the screen through the less
448 452 pager if longer than the screen, printed otherwise.
449 453
450 454 The ?/?? system gives access to the full source code for any object (if
451 455 available), shows function prototypes and other useful information.
452 456
453 457 If you just want to see an object's docstring, type '%pdoc object' (without
454 458 quotes, and without % if you have automagic on).
455 459
456 460 Both %pdoc and ?/?? give you access to documentation even on things which are
457 461 not explicitely defined. Try for example typing {}.get? or after import os,
458 462 type os.path.abspath??. The magic functions %pdef, %source and %file operate
459 463 similarly.
460 464
461 465 * Completion in the local namespace, by typing TAB at the prompt.
462 466
463 467 At any time, hitting tab will complete any available python commands or
464 468 variable names, and show you a list of the possible completions if there's
465 469 no unambiguous one. It will also complete filenames in the current directory.
466 470
467 471 This feature requires the readline and rlcomplete modules, so it won't work
468 472 if your Python lacks readline support (such as under Windows).
469 473
470 474 * Search previous command history in two ways (also requires readline):
471 475
472 476 - Start typing, and then use Ctrl-p (previous,up) and Ctrl-n (next,down) to
473 477 search through only the history items that match what you've typed so
474 478 far. If you use Ctrl-p/Ctrl-n at a blank prompt, they just behave like
475 479 normal arrow keys.
476 480
477 481 - Hit Ctrl-r: opens a search prompt. Begin typing and the system searches
478 482 your history for lines that match what you've typed so far, completing as
479 483 much as it can.
480 484
481 485 * Persistent command history across sessions (readline required).
482 486
483 487 * Logging of input with the ability to save and restore a working session.
484 488
485 489 * System escape with !. Typing !ls will run 'ls' in the current directory.
486 490
487 491 * The reload command does a 'deep' reload of a module: changes made to the
488 492 module since you imported will actually be available without having to exit.
489 493
490 494 * Verbose and colored exception traceback printouts. See the magic xmode and
491 495 xcolor functions for details (just type %magic).
492 496
493 497 * Input caching system:
494 498
495 499 IPython offers numbered prompts (In/Out) with input and output caching. All
496 500 input is saved and can be retrieved as variables (besides the usual arrow
497 501 key recall).
498 502
499 503 The following GLOBAL variables always exist (so don't overwrite them!):
500 504 _i: stores previous input.
501 505 _ii: next previous.
502 506 _iii: next-next previous.
503 507 _ih : a list of all input _ih[n] is the input from line n.
504 508
505 509 Additionally, global variables named _i<n> are dynamically created (<n>
506 510 being the prompt counter), such that _i<n> == _ih[<n>]
507 511
508 512 For example, what you typed at prompt 14 is available as _i14 and _ih[14].
509 513
510 514 You can create macros which contain multiple input lines from this history,
511 515 for later re-execution, with the %macro function.
512 516
513 517 The history function %hist allows you to see any part of your input history
514 518 by printing a range of the _i variables. Note that inputs which contain
515 519 magic functions (%) appear in the history with a prepended comment. This is
516 520 because they aren't really valid Python code, so you can't exec them.
517 521
518 522 * Output caching system:
519 523
520 524 For output that is returned from actions, a system similar to the input
521 525 cache exists but using _ instead of _i. Only actions that produce a result
522 526 (NOT assignments, for example) are cached. If you are familiar with
523 527 Mathematica, IPython's _ variables behave exactly like Mathematica's %
524 528 variables.
525 529
526 530 The following GLOBAL variables always exist (so don't overwrite them!):
527 531 _ (one underscore): previous output.
528 532 __ (two underscores): next previous.
529 533 ___ (three underscores): next-next previous.
530 534
531 535 Global variables named _<n> are dynamically created (<n> being the prompt
532 536 counter), such that the result of output <n> is always available as _<n>.
533 537
534 538 Finally, a global dictionary named _oh exists with entries for all lines
535 539 which generated output.
536 540
537 541 * Directory history:
538 542
539 543 Your history of visited directories is kept in the global list _dh, and the
540 544 magic %cd command can be used to go to any entry in that list.
541 545
542 546 * Auto-parentheses and auto-quotes (adapted from Nathan Gray's LazyPython)
543 547
544 548 1. Auto-parentheses
545 549 Callable objects (i.e. functions, methods, etc) can be invoked like
546 550 this (notice the commas between the arguments):
547 551 >>> callable_ob arg1, arg2, arg3
548 552 and the input will be translated to this:
549 553 --> callable_ob(arg1, arg2, arg3)
550 554 You can force auto-parentheses by using '/' as the first character
551 555 of a line. For example:
552 556 >>> /globals # becomes 'globals()'
553 557 Note that the '/' MUST be the first character on the line! This
554 558 won't work:
555 559 >>> print /globals # syntax error
556 560
557 561 In most cases the automatic algorithm should work, so you should
558 562 rarely need to explicitly invoke /. One notable exception is if you
559 563 are trying to call a function with a list of tuples as arguments (the
560 564 parenthesis will confuse IPython):
561 565 In [1]: zip (1,2,3),(4,5,6) # won't work
562 566 but this will work:
563 567 In [2]: /zip (1,2,3),(4,5,6)
564 568 ------> zip ((1,2,3),(4,5,6))
565 569 Out[2]= [(1, 4), (2, 5), (3, 6)]
566 570
567 571 IPython tells you that it has altered your command line by
568 572 displaying the new command line preceded by -->. e.g.:
569 573 In [18]: callable list
570 574 -------> callable (list)
571 575
572 576 2. Auto-Quoting
573 577 You can force auto-quoting of a function's arguments by using ',' as
574 578 the first character of a line. For example:
575 579 >>> ,my_function /home/me # becomes my_function("/home/me")
576 580
577 581 If you use ';' instead, the whole argument is quoted as a single
578 582 string (while ',' splits on whitespace):
579 583 >>> ,my_function a b c # becomes my_function("a","b","c")
580 584 >>> ;my_function a b c # becomes my_function("a b c")
581 585
582 586 Note that the ',' MUST be the first character on the line! This
583 587 won't work:
584 588 >>> x = ,my_function /home/me # syntax error
585 589 """
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
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